December 5, 1995
This article explains how to retrieve the current state of any virtual key in a Microsoft® Visual Basic® application.
The Microsoft® Windows® application programming interface (API) GetKeyState function can be used in a Microsoft Visual Basic® application to retrieve the current state of any virtual key. To use this function, include the following Declare statement in the General Declarations section of your form:
Private Declare Function GetKeyState Lib "user32" (ByVal nVirtKey As Long) As
Integer
The GetKeyState function will return the state (key is up, key is down, key is toggled on or off) of the virtual key you pass to the function.
In the example program below, you want to retrieve the state of the three toggle keys—caps lock, num lock, and scroll lock. To do this, you call the GetKeyState function with the virtual-key code for each individual key you want to test. For example, to retrieve the state of the caps lock key, you execute the statement:
Key = GetKeyState(VK_CAPITAL)
The value returned by the GetKeyState function can then be tested. If the low-order bit is 1, then the toggle key is on. If the low-order bit is 0, then the toggle key is off. Therefore, you can use the statement:
If Key And 1 Then
to test if the toggle key is on.
This program shows how to use the GetKeyState function to determine whether a toggle key (caps lock, num lock, scroll lock) is on or off.
Private Declare Function GetKeyState Lib "user32" (ByVal nVirtKey As Long)
As Integer
Const VK_NUMLOCK = &H90
Const VK_SCROLL = &H91
Const VK_CAPITAL = &H14
Private Sub Command1_Click()
Dim Key As Integer
Key = GetKeyState(VK_NUMLOCK)
If Key And 1 Then
text1.Text = "Num Lock is On"
Else
text1.Text = "Num Lock is Off"
End If
Key = GetKeyState(VK_SCROLL)
If Key And 1 Then
Text2.Text = "Scroll Lock is On"
Else
Text2.Text = "Scroll Lock is Off"
End If
Key = GetKeyState(VK_CAPITAL)
If Key And 1 Then
Text3.Text = "Caps Lock is On"
Else
Text3.Text = "Caps Lock is Off"
End If
End Sub
Run the example program by pressing f5. Click the Command Button. The state of the num lock, scroll lock, and caps lock keys appears in the corresponding Text Box controls.