Reading Keyboard Activity
Another useful purpose of API calls is to read the keyboard and find out if a certain key has
been pressed. Events on user forms are used to manage keyboard events, but these only apply
to a particular form or a particular control on the form that has the focus at that time.
For example, suppose you write a macro to do a time-consuming task that involves it
looping around thousands of times. You may want to give the user a “get out” command to
bring it to a halt if it takes too long. You can only do this by checking the keyboard, because
the only way you can see a keyboard event is on a UserForm, and this may not have the focus
at the time the user presses the “get out” key. You use the API callGetKeyStateto do this.
You must put the following code in the declarations part of a module:
Private Declare Function GetKeyState Lib "user 32 " (ByVal nVirtKey As Long) _
As Integer
This will allow you to examine any key while the program is running. You can even
differentiate between the left and rightSHIFTkeys orCTRLkeys:
Sub Test_Key()
x = 0
Do Until x = 1
If GetKeyState(&H 9 ) < 0 Then x = 1
DoEvents
Loop
MsgBox "You pressed the TAB key"
End Sub
This program effectively runs in an infinite loop and has only been done that way for
demonstration purposes. Normally, you would place the API call somewhere within a loop
within your own code so the keyboard can be read while other events are happening.
This program sets up a simple Do Until..Loop that keeps running untilx= 1. This will
never happen until theGetKeyStateline turns up a value for the specified key that is less
than 0—that is, it has been pressed. For the purposes of the example, theTA Bkey is used,
which has a value of 09 in hexadecimal. When theTA Bkey is pressed,xchanges its value to
1 and exits from the loop. The message box is then displayed.
TheDoEventscommand is very important here. It literally allows the operating system to
catch its breath and finish processing all messages before moving onto the next instruction. If
you do not use this, then the message from the keyboard will not be processed before the next
loop is started, and the keypress will be missed.
Run this code, and it goes into an infinite loop becausexwill never equal 1. Press any key
on the keyboard and nothing happens. But press theTA Bkey, and the program will end with a
message box. Of course, it helps if you know the values of the virtual key codes if you want
to use other key combinations. They are listed in Table 20-1.
258 Microsoft Access 2010 VBA Macro Programming