Write Your First Visual Basic Program
To understand this property,
lets look on
the following example:
Start new project, and add 1 Command
(named Command1) to your form.
verify that the Form's KeyPreview
property is set to "False".
Add the following code to your
Private Sub Command1_KeyPress(KeyAscii As
Print "Button Pressed"
Private Sub Form_KeyPress(KeyAscii As Integer)
The code above will
print "Button Pressed" on
the form when the Command Button's KeyPress event
will be executed, and print "Form Pressed" when the
Form's KeyPress event
will be executed.
Run the program and press any key on the
"Button Pressed" is appearing on the form, but
The Form's KeyPress event hasn't been
When the KeyPreview property is "False",
if any control is
found on the form (the command button in this case),
It will get all the Key
events (KeyPress, KeyDown and KeyUp)
instead of the form.
To allow the
Form's Key events be executed,
set the KeyPreview property to
Lets try it. Set the KeyPreview
property to "True", run the
and press any key.
The Form's KeyPress event has been
in addition to the Button's KeyPress event that
Notice That the form's KeyPress event executed