Here's another example: Suppose you've written a VBA macro that will be executed from a toolbar button. Furthermore, suppose you want the macro to perform differently if the user presses the Shift key when the button is clicked. Normally, there is no way to detect whether the Shift key is pressed. But you can use the GetKeyState API function to find out. The GetKeyState function tells you whether a particular key is pressed. It takes a single argument, nVirtKey, which represents the code for the key that you are interested in.
Chapter 11 has several additional examples of using Windows API functions.
The following code demonstrates how to detect whether the Shift key is pressed when the Button_Click event handler procedure is executed. Notice that I define a constant for the Shift key (using a hexadecimal value) and then use this constant as the argument for GetKeyState. If GetKeyState returns a value less than zero, it means that the Shift key was pressed; otherwise, the Shift key was not pressed.
Declare Function GetKeyState Lib "user32" _ (ByVal nVirtKey As Long) As Integer
Const VK_SHIFT As Integer = &H10 If GetKeyState(VK_SHIFT) < 0 Then MsgBox "Shift is pressed"
MsgBox "Shift is not pressed" End If End Sub
A workbook on the companion CD-ROM demonstrates how to detect the following keys (as well as any combinations): Ctrl, Shift, and Alt.
Was this article helpful?