Link label windows forms

Link label windows forms

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

LinkLabel

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Определение

Получает или задает значение, показывающее, была ли посещена ссылка. Gets or sets a value indicating whether the user has visited the link.

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

Значение true , если ссылка была посещена. В противном случае — значение false . true if the link has been visited; otherwise, false .

Примеры

В следующем примере демонстрируется использование 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.

Читайте также:  Anime studio debut windows

Комментарии

LinkLabelЭлемент управления не будет автоматически отметьте, что ссылка является просмотренной ссылкой. A LinkLabel control does not automatically denote that a link is a visited link. Чтобы отобразить ссылку в виде просмотренной ссылки, можно установить значение этого свойства true в обработчике событий для LinkClicked события LinkLabel . To display the link as a visited link, you can set the value of this property to true in an event handler for the LinkClicked event of a LinkLabel. Просмотренная ссылка отображается с использованием цвета, указанного в VisitedLinkColor свойстве LinkLabel элемента управления. A visited link is displayed using the color specified in the VisitedLinkColor property of the LinkLabel control. После закрытия формы, содержащей LinkLabel элемент управления, все состояние отображения, связанное со ссылкой, удаляется. Once the form containing the LinkLabel control is closed, the all display state associated with the link is deleted. Чтобы сохранить состояние отображения ссылки, необходимо сохранить состояние отображения ссылки в параметре реестра, связанном с приложением. In order to retain the display state of the link, you need to store the display state of the link in a registry setting associated with your application.

Если в элементе управления указана только одна ссылка LinkLabel , можно использовать LinkVisited свойство объекта, LinkLabel чтобы указать ссылку как посещенную. If you have only one link specified in a LinkLabel control, you can use the LinkVisited property of the LinkLabel to specify the link as visited. Кроме того, можно использовать LinkVisited свойство, если определено несколько ссылок, но параметр применяется только к первой ссылке, определенной в элементе управления. You can also use the LinkVisited property if you have multiple links defined, but the setting only applies to the first link defined in the control.

Элемент управления 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.

Читайте также:  Как восстановить microsoft edge windows 10

Практическое руководство. Изменение внешнего вида элемента управления 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.

Link Label. Link Clicked Событие

Определение

Происходит при щелчке ссылки в элементе управления. Occurs when a link is clicked within the control.

Тип события

Примеры

В следующем примере демонстрируется использование LinkLabel класса. The following example demonstrates using the LinkLabel class. В примере обрабатывается LinkClicked событие путем открытия веб-сайта. The example handles the LinkClicked event by opening a Web site.

В следующем примере демонстрируется использование 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.

Комментарии

Как правило, LinkClicked событие обрабатывается для выполнения задач, когда пользователь щелкает ссылку в элементе управления. Typically, the LinkClicked event is handled to perform tasks when the user clicks on a link in the control. Обработчику события для LinkClicked события передается экземпляр LinkLabelLinkClickedEventArgs класса, который содержит LinkLabel.Link объект, связанный со ссылкой, которая была нажата. 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. Сведения, указанные в LinkData свойстве класса, можно использовать LinkLabel.Link для определения того, какая ссылка была нажата, или тип задачи, выполняемой при щелчке ссылки. 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. Например, если LinkLabel элемент управления имеет LinkLabel.Link объект LinkData , определенный свойством, для которого задано значение строки www.microsoft.com , эти сведения можно использовать в обработчике событий для LinkClicked события, чтобы отобразить веб-сайт. 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.

Читайте также:  Слить диск windows 10

Дополнительные сведения об обработке событий см. в разделе обработка и вызов событий. For more information about handling events, see Handling and Raising Events.

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.

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