How to Trap Keystrokes in the Form Instead of Form's Controls (99688)



The information in this article applies to:

  • Microsoft Visual Basic Standard Edition for Windows 2.0
  • Microsoft Visual Basic Standard Edition for Windows 3.0
  • Microsoft Visual Basic Professional Edition for Windows 2.0
  • Microsoft Visual Basic Professional Edition for Windows 3.0

This article was previously published under Q99688

SUMMARY

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 Input

This example demonstrates the difference between Form_KeyPress and Form_KeyDown to attempt to trap and prevent all keyboard input for a text box.
  1. Start Visual Basic or from the File menu, choose New Project if Visual Basic is already running. Form1 is created by default.
  2. Set the KeyPreview property of Form1 to True.
  3. Add a text box (Text1) to Form1.
  4. Add the following code to the Form_KeyDown event of Form1:
       KeyCode = 0
    
    						
  5. From the Run menu, choose Start or press the F5 key.
The Text1 box still accepts input, which you may not have expected. This behavior is by design.

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.

Modification Type:MajorLast Reviewed:12/12/2003
Keywords:KB99688