Partilhar via


Visual Basic Concepts

Allowing Developers to Set Access Keys for Your Control

Placing ampersand characters (&) in the captions of Label controls and CommandButton controls creates access keys with which the end user of an application can shift focus to the control. You can create a similar effect in your ActiveX controls.

For example, suppose you have created a user-drawn button. In the Property Let for your button's Caption property, you can examine the text of the caption the user has entered. If there's an ampersand in front of a letter, you can assign that letter to the AccessKeys property of the UserControl object.

When the end user presses one of the access keys enabled in this fashion, your UserControl object receives an AccessKeyPress event. The argument of this event contains the access key that was pressed, allowing you to support multiple access keys on a control.

Access Keys for Control Assemblies

Control assemblies may contain constituent controls that can get the focus, and that support access keys of their own. You can use this fact to provide access key functionality.

Suppose you've authored a general-purpose control that consists of a text box and a label; you want the user to be able to set an access key in the label's caption, and forward the focus to the text box. You can accomplish this by giving the label and text box TabIndex values of zero and one (the TabIndex values on the UserControl are not visible outside your control), and delegating the Caption property of your control to the label, thus:

Property Get Caption() As String
   Caption = Label1.Caption
End Property

Property Let Caption(NewCaption As String)
   Label1.Caption = NewCaption
   PropertyChanged "Caption"
End Property

When a developer assigns the text "&Marsupial" to your Caption property, the label control will do all the access key work for you.

Note   When the end user presses an access key on one of your constituent controls, the UserControl does not receive an AccessKeyPress event.

Control Assemblies with Fixed Text

For fixed-purpose control assemblies, such as an Address control, you can put ampersand characters (&) in the captions of constituent controls. Unfortunately, these hard-coded access keys may conflict with other access key choices the user wishes to make on a form.

In a more sophisticated variation of this scheme, you might add an AccessKeyXxxx property to your control for the appropriate constituent controls. That is, if the caption of the label next to the txtLastname control was "Last Name," you would add an AccessKeyLastName property. The developer using your control could assign any character from the label's caption to this property, and in the Property Let code you could change the caption to contain the ampersand.