Professional Documents
Culture Documents
6
Handling Keyboard Input
Capturing the keyboard stroke or keystroke in Visual Basic is done using the KeyCode or KeyAscii value. A
quick way to find out the KeyCode or KeyAscii value of a certain key is to put a test message box in the
appropriate event. Consider the following example:
Once you know the KeyCode or KeyAscii value, use an If/Then/Else or Select Case statement to execute
code pertaining to the key typed. This sample code moves an object with the arrow keys.
There are actually a whole pile of built-in constants for KeyCode values which can be used instead.
Setting the KeyAscii to 0 (the character code for null) cancels the keystroke.
The Shift argument holds a value which will tell you the state of the Shift, Ctrl, and Alt keys. The value will
be between 0 and 7.
• If Shift has a value of 0 . . . None of these keys are being held down.
• If Shift has a value of 1 . . . Shift key on the keyboard is being held down.
• If Shift has a value of 2 . . . Ctrl key on the keyboard is being held down.
• If Shift has a value of 3 . . . Shift key and Ctrl key on the keyboard are being held down.
• If Shift has a value of 4 . . . Alt key on the keyboard is being held down.
• If Shift has a value of 5 . . . Shift key and Alt key on the keyboard are being held down.
• If Shift has a value of 6 . . . Ctrl key and Alt key on the keyboard are being held down.
• If Shift has a value of 7 . . . All three keys (Shift, Ctrl, and Alt) are being held down.
Here’s an example which tests to see if the user has press Ctrl + X on the keyboard. If it is being press, the
program will end executing:
SendKeys STATEMENT
The SendKeys statement sends a keystroke to your application as if it were actually typed. Here are few
examples:
Consider the following example which highlights whatever text in a textbox (named txtInput) when it
receives focus:
The main purpose of the MouseDown and MouseUp events is to distinguish between a left click and a right
click.
The built-in Button argument holds a value corresponding to which button was clicked. The Shift argument
holds a value corresponding to the state of the Ctrl, Alt, and Shift keys. The X and Y arguments will tell you
the exact coordinates of where the user clicked. Consider the following example:
The MouseMove event is triggered constantly as the user moves the mouse. This event also contains
Button and Shift arguments.
You may have seen that aggravating program which wants you to click a button, but moves the button away
once you put your mouse over it. This is very easy to do with the MouseMove event. Add a command
button named cmdClickMe to a Form named frmMain and add this code:
Rnd is a Visual Basic function which can help you generate random numbers.