Tip 4: Adding Access Keys to Controls That Don't Have a Caption Property

Created: March 1, 1995

Abstract

When you assign an access key to a control, you allow your user to move quickly between one control and another control on the same form. This article tells you how to assign access keys in Visual Basic®.

Assigning Access Keys

In Visual Basic®, a user presses the ALT key and the access letter character at the same time to move the focus to the designated control. Access keys can be assigned to a control through the control's Caption property. If, for example, the Caption property is set to the text "Name", you can assign an access key to the control by specifying the Caption property as "&Name". The ampersand character informs Windows® that the ALT key plus the (in this case) "N" key will move the focus to this control. The access key is displayed underlined in the control's caption when your application is executed. The catch is that access keys can only be assigned to controls that have a Caption property.

There is, however, a technique you can use to quickly move the focus to a control that does not have a Caption property.

When you place controls on a form, the TabIndex property determines which control will receive the focus next. The control with the next highest TabIndex value automatically receives the focus.

You can place a Label control, which has a Caption property, in front of a control that cannot receive the focus, such as a Text Box. Because a Label control cannot receive the focus, the next control in the TabIndex order receives the focus.

Let's assume that you want to assign an access key to a Text Box. First, you would draw a Label control on your form and set its Caption property so it is assigned an access key, for example, &Name. Next, you would add a Text Box control beside or near the Label control. Make sure the TabIndex value of the Text Box is one greater than that of the Label control.

When your application program is running, you can move the focus to the Text Box by pressing the access key assigned to the Label control.

You must remember that this technique will only work as long as the TabIndex property of the Label control is always one less than the control you want to actually move the focus to.