Add ALT key shortcuts to VB controls

You often want to write your application so that your forms are easily navigated by mouse as well as by keyboard.

To add an Alt-key shortcut to most controls in Visual Basic 6.0, simply add an ampersand (&) in the Caption property of the object in front of the letter you want to use in the Alt sequence. You will see that the Caption of the object in the form designer will underline the selected letter.

Example:
Command button Caption: Save
Command button Caption with Alt keyboard shortcut: &Save
The text on the button will now appear as Save. When the application is running, pressing Alt-s will fire the Click event for that button.

For objects like textboxes, which do not have Caption properties, add the keyboard shortcut to the Caption of a control which cannot accept focus (e.g. a label or frame control) which directly precedes the text box in the Tab Order.

Example:
I have a textbox, txtUsername, which accepts an input. It is set to Tab Index 5. I create a label, lblUsername, and set it to Tab Index 4, then set the Caption of lblUsername to: &Username. Pressing Alt-U will set the focus to txtUsername.

If you have more than one button or menu using the same Alt shortcut, some functionality may change. For example, for a Command Button, a shortcut key will normally fire the Click event automatically when the shortcut key is pressed. However, if more than one control is using the same shortcut key, focus will simply be cycled between all controls with the same keyboard shortcut. Events will not fire automatically. The button (or other control) would have to be clicked another way (e.g. space bar or mouse). To avoid this, be sure to choose different shortcut letters for each control or menu that will appear on the same form.


Author: DPAK/ASAK
Created: Sep 19 2005 (last modified Dec 7 2005)
Categories: Visual Basic
TechByte #1

Warning: By visiting this site and/or by using any information contained herein, you agree to the Techbytes.ca terms of use.



Add a comment about this TechByte

If you wish to add a comment regarding this TechByte, please use the form below. Please note that by submitting comments using this form you are allowing all of the information submitted to be visible on this website. Any comments submitted using this form will only be shown on the website if they are approved by the administrators of this site. IF APPROVED, COMMENTS MAY TAKE SEVERAL DAYS TO BE POSTED.

Posted By: (Optional)

Comments: