Recipe 17.12. Adding Hyperlinks to a (Desktop) Form


You want to add a standard hypertext link to text on a Windows form, without resorting to HTML or other browser technology.


Use the LinkLabel control.


The LinkLabel control is similar to a standard Label control, except that it has additional properties and events that provide the behavior expected of a hypertext link as displayed in a browser window. For example, the color of the link before being clicked the first time is determined by the LinkLabel's LinkColor property, and its color after it has been clicked is determined by its VisitedLinkColor property. The defaults for these colors work very well, and the results are much like what you expect after using a browser for any length of time.

The LinkLabel holds text of any reasonable length, and you can set all or just a part of the text as the active, clickable part by setting its LinkArea property. The Start and Length numbers in the LinkArea determine exactly which group of contiguous characters in the label are colored as an active link. Clicks on the LinkLabel within the LinkArea activate its LinkClicked event, whereas clicks anywhere else on the LinkLabel activate the usual Click event.

The code you put in the LinkClicked event is what really makes this control behave like a link should. The following code, for example, sets the LinkArea's LinkVisited property to true, which causes its VisitedLinkColor to show. It also creates a true link to an Internet URL, in this case opening a web site in the default browser:

 Private Sub LinkLabel1_LinkClicked( _       ByVal sender As System.Object, _       ByVal e As System.Windows.Forms. _       LinkLabelLinkClickedEventArgs) _       Handles LinkLabel1.LinkClicked    ' ----- Open that important web site.    LinkLabel1.LinkVisited = True    System.Diagnostics.Process.Start( _       "") End Sub 

Figure 17-16 shows a small dialog window that displays a single LinkLabel control. The LinkArea is set to the last part of the LinkLabel's text, and the previous code is activated when this area is clicked. Your default browser will then display very interesting O'Reilly Media pages for your enjoyment.

Figure 17-16. Using a LinkLabel to include a hyperlink on your form

Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: