Prerequisites |
VB version supporting the Byte data type. Although this
code will toggle the actual keyboard state on a NT/2000 system, it will not toggle the corresponding keyboard lights. See the link
above for NT-specific code. |
|
|
|
BAS
Module Code |
|
Place the following code into the general declarations
area of a bas module: |
|
Option Explicit
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Copyright ©1996-2011 VBnet/Randy Birch, All Rights Reserved.
' Some pages may also contain other copyrights by the author.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Distribution: You can freely use this code in your own
' applications, but you may not reproduce
' or publish this code on any web site,
' online service, or distribute as source
' on any media without express permission.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
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 |
|
Form
Code |
|
On a form, add a 3 command buttons (Command1, Command2,
Command3) and a label (Label1). Add the following code to the form: |
|
Option Explicit
Private Sub Form_Load()
Label1.Caption = IIf(CapsLock() = 1, "On", "Off")
End Sub
Function CapsLock() As Boolean
CapsLock = GetKeyState(VK_CAPITAL) And 1 = 1
End Function
Private Sub Command1_Click()
'toggle key state on each press
GetKeyboardState kbArray
kbArray.kbByte(VK_CAPITAL) = IIf(kbArray.kbByte(VK_CAPITAL) = 1, 0, 1)
SetKeyboardState kbArray
Label1.Caption = IIf(CapsLock() = 1, "On", "Off")
End Sub
Private Sub Command2_Click()
'turn capslock on
GetKeyboardState kbArray
kbArray.kbByte(VK_CAPITAL) = 1
SetKeyboardState kbArray
Label1.Caption = IIf(CapsLock() = 1, "On", "Off")
End Sub
Private Sub Command3_Click()
'turn capslock off
GetKeyboardState kbArray
kbArray.kbByte(VK_CAPITAL) = 0
SetKeyboardState kbArray
Label1.Caption = IIf(CapsLock() = 1, "On", "Off")
End Sub |
|
Comments |
The keyboard APIs for VB4-16 and VB3 do not support the
byte data type.
By changing the Windows constant to VK_NUMLOCK = &H90, you can use the above method to activate the NumLock key instead. |
|