Linklabel in windows forms

How to: Link to an Object or Web Page with the Windows Forms LinkLabel Control

The Windows Forms LinkLabel control allows you to create Web-style links on your form. When the link is clicked, you can change its color to indicate the link has been visited. For more information on changing the color, see How to: Change the Appearance of the Windows Forms LinkLabel Control.

Linking to Another Form

Set the Text property to an appropriate caption.

Set the LinkArea property to determine which part of the caption will be indicated as a link. How it is indicated depends on the appearance-related properties of the link label. The LinkArea value is represented by a LinkArea object containing two numbers, the starting character position and the number of characters. The LinkArea property can be set in the Properties window or in code in a manner similar to the following:

In the LinkClicked event handler, invoke the Show method to open another form in the project, and set the LinkVisited property to true .

An instance of the LinkLabelLinkClickedEventArgs class carries a reference to the LinkLabel control that was clicked, so there is no need to cast the sender object.

Linking to a Web Page

The LinkLabel control can also be used to display a Web page with the default browser.

Set the Text property to an appropriate caption.

Set the LinkArea property to determine which part of the caption will be indicated as a link.

Link Label. Link Clicked Event

Definition

Occurs when a link is clicked within the control.

Event Type

Examples

The following example demonstrates using the LinkLabel class. The example handles the LinkClicked event by opening a Web site.

The following example demonstrates using the LinkLabel class, with multiple LinkArea sections defined, to display a label on a form. The example demonstrates setting the AutoSize, LinkBehavior, DisabledLinkColor, LinkColor, and VisitedLinkColor properties to customize the look of the LinkLabel. The first LinkArea is specified using the LinkLabel.LinkArea property. Additional links are added to the LinkLabel using the LinkLabel.LinkCollection.Add method. The example handles the LinkClicked event by starting the Web browser for hyperlinks, and displaying a MessageBox for other links.

Читайте также:  M2070 не сканирует windows 10

Remarks

Typically, the LinkClicked event is handled to perform tasks when the user clicks on a link in the control. The event handler for the LinkClicked event is passed an instance of the LinkLabelLinkClickedEventArgs class that contains a LinkLabel.Link object that is associated with the link that was clicked. You can use information specified in the LinkData property of LinkLabel.Link class to determine which link was clicked or what type of task to perform when the link is clicked. For example, if a LinkLabel control has a LinkLabel.Link object defined with its LinkData property set to the string www.microsoft.com , you can use this information in an event handler for the LinkClicked event to display the Web site.

For more information about handling events, see Handling and Raising Events.

Link Label. Links Свойство

Определение

Получает коллекцию ссылок, содержащихся в элементе управления LinkLabel. Gets the collection of links contained within the LinkLabel.

Значение свойства

Класс LinkLabel.LinkCollection, представляющий ссылки, содержащиеся в элементе управления LinkLabel. A LinkLabel.LinkCollection that represents the links contained within the LinkLabel control.

Примеры

В следующем примере демонстрируется использование LinkLabel класса с несколькими LinkArea определенными разделами для вывода метки на форму. The following example demonstrates using the LinkLabel class, with multiple LinkArea sections defined, to display a label on a form. В примере показано задание AutoSize свойств, LinkBehavior , DisabledLinkColor , LinkColor и VisitedLinkColor для настройки вида LinkLabel . The example demonstrates setting the AutoSize, LinkBehavior, DisabledLinkColor, LinkColor, and VisitedLinkColor properties to customize the look of the LinkLabel. Первый LinkArea указывается с помощью LinkLabel.LinkArea Свойства. The first LinkArea is specified using the LinkLabel.LinkArea property. В LinkLabel с помощью метода добавляются дополнительные ссылки LinkLabel.LinkCollection.Add . Additional links are added to the LinkLabel using the LinkLabel.LinkCollection.Add method. Этот пример обрабатывает LinkClicked событие, запуская веб-браузер для гиперссылок и отображая MessageBox для других ссылок. The example handles the LinkClicked event by starting the Web browser for hyperlinks, and displaying a MessageBox for other links.

Комментарии

LinkLabelЭлемент управления может отображать любое количество ссылок в тексте элемента управления. A LinkLabel control can display any number of links within the text of the control. Это свойство позволяет получить доступ к LinkLabel.LinkCollection экземпляру, связанному с LinkLabel , который представляет коллекцию ссылок, отображаемых в элементе управления. This property enables you to access the LinkLabel.LinkCollection instance associated with the LinkLabel that represents the collection of links displayed in the control. Затем можно использовать члены LinkLabel.LinkCollection класса для добавления, удаления и поиска ссылок в коллекции. You can then use the members of the LinkLabel.LinkCollection class to add, remove, and find links in the collection. Дополнительные сведения о типах задач, которые можно выполнять с помощью коллекции ссылок, см. в разделе LinkLabel.LinkCollection . For more information on the types of tasks you can perform with the link collection, see LinkLabel.LinkCollection.

Читайте также:  Arch linux systemd boot

При LinkLabel создании элемента управления Гиперссылка по умолчанию, содержащая весь текст в LinkLabel элементе управления, добавляется в LinkLabel.LinkCollection . When a LinkLabel control is created, a default hyperlink that contains all the text within the LinkLabel control is added to the LinkLabel.LinkCollection. Эту ссылку по умолчанию можно переопределить, указав новую область ссылки со LinkArea свойством или указав ссылку с помощью Add метода LinkLabel.LinkCollection . You can override this default link by specifying a new link area with the LinkArea property, or specify a link using the Add method of the LinkLabel.LinkCollection. Можно также удалить гиперссылку по умолчанию с помощью Remove метода LinkLabel.LinkCollection класса. You can also remove the default hyperlink by using the Remove method of the LinkLabel.LinkCollection class.

Если не нужно указывать более одной ссылки для вывода в LinkLabel , можно использовать LinkArea свойство. If you do not need to specify more than one link to display within the LinkLabel, you can use the LinkArea property.

Linklabel in windows forms

Для отображения простого текста на форме, доступного только для чтения, служит элемент Label. Чтобы задать отображаемый текст метки, надо установить свойство Text элемента.

LinkLabel

Особый тип меток представляют элементы LinkLabel, которые предназначены для вывода ссылок, которые аналогичны ссылкам, размещенным на стандартных веб-станиц.

Также, как и с обычными ссылками на веб-страницах, мы можем по отношению к данному элементу определить три цвета:

Свойство ActiveLinkColor задает цвет ссылки при нажатии

Свойство LinkColor задает цвет ссылки до нажатия, по которой еще не было переходов

Свойство VisitedLinkColor задает цвет ссылки, по которой уже были переходы

Кроме цвета ссылки для данного элемента мы можем задать свойство LinkBehavior , которое управляет поведением ссылки. Это свойство принимает четыре возможных значения:

SystemDefault : для ссылки устанавливаются системные настройки

AlwaysUnderline : ссылка всегда подчеркивается

HoverUnderline : ссылка подчеркивается только при наведении на нее курсора мыши

Читайте также:  Windows 10 fps fix

NeverUnderline : ссылка никогда не подчеркивается

По умолчанию весь текст на данном элементе считается ссылкой. Однако с помощью свойства LinkArea мы можем изменить область ссылки. Например, мы не хотим включать в ссылку первые шесть символов. Для этого задаем подсвойство Start :

Чтобы выполнить переход по ссылке по нажатию на нее, надо дополнительно написать код. Данный код должен обрабатывать событие LinkClicked , которое есть у элемента LinkLabel. Например, пусть у нас на форме есть элемент ссылки называется linkLabel1 и который содержит некоторую ссылку:

Чтобы перейти по ссылке, зададим обработчик LinkClicked:

Элемент управления LinkLabel (Windows Forms) LinkLabel Control (Windows Forms)

LinkLabel Элемент управления Windows Forms позволяет добавлять веб-ссылки на Windows Forms приложения. The Windows Forms LinkLabel control enables you to add Web-style links to Windows Forms applications. Элемент управления можно использовать LinkLabel для всех элементов, для которых можно использовать Label элемент управления. можно также задать часть текста в виде ссылки на объект или веб-страницу. You can use the LinkLabel control for everything that you can use the Label control for; you can also set part of the text as a link to an object or Web page.

в этом разделе In This Section

Общие сведения об элементе управления LinkLabel LinkLabel Control Overview
Описание элемента управления, его основных возможностей и свойств. Explains what this control is and its key features and properties.

Практическое руководство. Изменение внешнего вида элемента управления LinkLabel в Windows Forms How to: Change the Appearance of the Windows Forms LinkLabel Control
Описывает способы указания цвета и подчеркивания ссылок в стиле Web в метках ссылок. Lists ways to specify the color and underlining of Web-style links in link labels.

Практическое руководство. Отображение веб-страницы из элемента управления LinkLabel в Windows Forms (Visual Basic) How to: Display a Web Page from a Windows Forms LinkLabel Control (Visual Basic)
Показывает, как отображать веб-страницу в браузере по умолчанию, когда пользователь щелкает LinkLabel элемент управления Windows Forms. Shows how to display a Web page in the default browser when a user clicks a Windows Forms LinkLabel control.

Справочник Reference

Класс LinkLabel LinkLabel class
Описание класса и всех его членов. Describes this class and has links to all its members.

Элементы управления для использования в формах Windows Forms Controls to Use on Windows Forms
Содержит полный список элементов управления Windows Forms со ссылками на сведения об их использовании. Provides a complete list of Windows Forms controls, with links to information about their use.

Оцените статью