CapsLock and NumLock

By | 2002-06-01

How to Activate CapsLock and NumLock from Code

Original Author: Ian Ippolito (psc)

Assumptions

The keyboard APIs for VB4-16 and VB3 do not support the byte data type.
By changing the Windows constant to Public Const VK_NUMLOCK = &H90, you can use the above to activate the NumLock key.

API Declarations

Public Const VK_CAPITAL = &H14
Public Type KeyboardBytes
?á?á?á?á?ákbByte(0 To 255) As Byte
End Type
Public kbArray As KeyboardBytes
Public Declare Function GetKeyState Lib “user32” (ByVal nVirtKey As Long) As Long
Public Declare Function GetKeyboardState Lib “user32” (kbArray As KeyboardBytes) As Long
Public Declare Function SetKeyboardState Lib “user32” (kbArray As KeyboardBytes) As Long

Code

On a form, add a 3 command buttons (cmdToggle, cmdTurnOff, cmdTurnOff) and a label. Add the following code to the form:
Private Function CapsLock() As Integer
CapsLock = GetKeyState(VK_CAPITAL) And 1 = 1
End Function
Private Sub Form_Load()
If CapsLock() = 1 Then Label1 = "On" Else Label1 = "Off"
End Sub
Private Sub cmdToggle_Click()
GetKeyboardState kbArray
kbArray.kbByte(VK_CAPITAL) = IIf(kbArray.kbByte(VK_CAPITAL) = 1, 0, 1)
SetKeyboardState kbArray
Label1 = IIf(CapsLock() = 1, "On", "Off")
End Sub
Private Sub cmdTurnOn_Click()
GetKeyboardState kbArray
kbArray.kbByte(VK_CAPITAL) = 1
SetKeyboardState kbArray
Label1 = IIf(CapsLock() = 1, "On", "Off")
End Sub
Private Sub cmdTurnOff_Click()
GetKeyboardState kbArray
kbArray.kbByte(VK_CAPITAL) = 0
SetKeyboardState kbArray
Label1 = IIf(CapsLock() = 1, "On", "Off")
End Sub

Author: dwirch

Derek Wirch is a seasoned IT professional with an impressive career dating back to 1986. He brings a wealth of knowledge and hands-on experience that is invaluable to those embarking on their journey in the tech industry.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.