Article ID: 99688 - Last Review: December 12, 2003 - Revision: 2.0 How to Trap Keystrokes in the Form Instead of Form's ControlsThis article was previously published under Q99688 On This PageSUMMARY
To trap most keystrokes (see NOTE below) at the form level instead of
passing them to the form's controls, set the form's KeyPreview property to
True and use KeyAscii=0 in the Form_KeyPress event. This prevents
keystrokes from going to the form's controls.
NOTE: the technique described in this article will not intercept the ENTER key on command buttons. Command buttons are subclassed Windows push button controls and the ENTER key is an accelerator key that is passed to the superclass; Visual Basic never receives it. Also note that KeyCode=0 in the Form_KeyDown event won't prevent keystrokes going to the form's controls. This behavior is by design. MORE INFORMATION
A form's KeyPreview property determines whether form keyboard events are
invoked before control keyboard events. The keyboard events are KeyDown,
KeyUp, and KeyPress.
You can use the KeyPreview property to create a keyboard-handling procedure for a form. For example, when an application uses function keys, it's likely that you'll want to process the keystrokes at the form level rather than writing code for each control that might receive keystroke events. If a form has no visible and enabled controls, it automatically receives all keyboard events. To handle keyboard events only at the form level and not allow controls to receive keyboard events, set KeyAscii to 0 in the form's KeyPress event. Using Form_KeyPress Versus Form_KeyDown to Prevent Text Box InputThis example demonstrates the difference between Form_KeyPress and Form_KeyDown to attempt to trap and prevent all keyboard input for a text box.
To prevent the Text1 box from accepting input, add KeyAscii = 0 to the Form_KeyPress event of Form1. This traps and disables all input to all the controls on the form, as desired. The Form_KeyPress event enables you to handle the keystrokes the way you want. APPLIES TO
| Article Translations
|

Back to the top
