Declare Function GetKeyboardState Lib "user32.dll" (pbKeyState As Byte) As Long
GetKeyboardState reads the status of all of the keys on the keyboard and puts them into a 255-element byte array. Two pieces of information are recorded for each key: its toggle status and its pressed status. The &H01 bit of the array element is the pressed status: it is 1 if the key is currently being pressed and 0 if it is not. The &H80 bit of the array element is the toggle status: it is 1 if the key is toggled and 0 of it is not. Although the CapsLock, NumLock, and ScrollLock keys are the only ones generally considered toggle keys, Windows stores the toggle status of every key on the keyboard. Generally, the toggle status of the other keys are disregarded. The example shows how to extract key information from an array element. The function returns 1 if successful or 0 if an error occured.
Example:
' Read the status of the Enter key
' The virtual key code for Enter is 13 (&H0D)
Dim keystat(0 To 255) As Byte
x = GetKeyboardState(keystat(0)) ' the array is passed by referencing element #0
If (keystat(13) And &H01) = &H01 Then ' If Enter is pressed down
Debug.Print "Enter is being pressed."
End If
If (keystat(13) And &H80) = &H80 Then ' If Enter is toggled
Debug.Print "Enter is currently toggled."
End If
Related Call: GetKeyState
Category: Keyboard
Back to the index.