Form.
You can use the KeyPreview property to specify whether form keyboard events are invoked before control keyboard events.
Note The keyboard events are KeyDown, KeyUp, and KeyPress.
The KeyPreview property uses the following settings.
Setting |
Description |
Visual Basic |
No |
(Default) Only the active control receives keyboard events. |
False (0) |
You can set the KeyPreview property in the form’s property sheet, a macro, or using Visual Basic.
You can set the KeyPreview property in any view.
You can use the KeyPreview property to create a keyboard-handling procedure for a form. For example, when an application uses function keys, setting the KeyPreview property to True allows you to process keystrokes at the form level rather than writing code for each control that might receive keystroke events.
To handle keyboard events only at the form level and prevent controls from receiving keyboard events, set KeyAscii to 0 in the form’s KeyPress event, and set KeyCode to 0 in the form’s KeyDown and KeyUp events.
If a form has no visible or enabled controls, it automatically receives all keyboard events.
KeyDown, KeyUp Events; KeyPress Event.
In the following example the KeyPreview property is set to True in the form’s load event. This causes the form to receive keyboard events before they are received by any control. The form KeyDown event then examines the KeyCode value to determine if the F2, F3, or F4 keys were pushed.
Private Sub Form_Load() Me.KeyPreview = TrueSub Sub Form_KeyDown(KeyCode As Integer, Shift As Integer) Const conKey_F2 = &H71 ' F2 Key constant Const conKey_F3 = &H72 ' F3 Key constant Const conKey_F4 = &H73 ' F4 Key constant Select Case KeyCode Case conKey_F2 ' Process F2 key events Case conKey_F3 ' Process F3 key events Case conKey_F4 ' Process F4 key events Case Else End SelectSub