Skip to content

Instantly share code, notes, and snippets.

@afvanwoudenberg
Last active October 19, 2018 13:00
Show Gist options
  • Save afvanwoudenberg/cfd1e50e563c3b3ac338fc156da935a5 to your computer and use it in GitHub Desktop.
Save afvanwoudenberg/cfd1e50e563c3b3ac338fc156da935a5 to your computer and use it in GitHub Desktop.
VBA code to turn the keyboard LEDs (Num Lock, Caps Lock and Scroll Lock) on and off
' modKeyboardLeds
' Aswin van Woudenberg
Option Explicit
Private Declare Function GetVersionEx Lib "kernel32" Alias "GetVersionExA" _
(lpVersionInformation As OSVERSIONINFO) As Long
Private Declare Sub keybd_event Lib "user32" (ByVal bVk As Byte, _
ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long)
Private Declare Function GetKeyboardState Lib "user32" (pbKeyState As Byte) As Long
Private Declare Function SetKeyboardState Lib "user32" (lppbKeyState As Byte) As Long
Private Type OSVERSIONINFO
dwOSVersionInfoSize As Long
dwMajorVersion As Long
dwMinorVersion As Long
dwBuildNumber As Long
dwPlatformId As Long
szCSDVersion As String * 128
End Type
Public Const VK_NUMLOCK = &H90
Public Const VK_SCROLL = &H91
Public Const VK_CAPITAL = &H14
Private Const KEYEVENTF_EXTENDEDKEY = &H1
Private Const KEYEVENTF_KEYUP = &H2
Private Const VER_PLATFORM_WIN32_NT = 2
Private Const VER_PLATFORM_WIN32_WINDOWS = 1
Public Function GetKeyState(iKey As Integer) As Boolean
Dim keys(0 To 255) As Byte
GetKeyboardState keys(0)
GetKeyState = (keys(iKey) = 1)
End Function
Public Sub SetKeyState(iKey As Integer, bState As Boolean)
Dim o As OSVERSIONINFO
Dim keys(0 To 255) As Byte
o.dwOSVersionInfoSize = Len(o)
GetVersionEx o
Select Case o.dwPlatformId
Case VER_PLATFORM_WIN32_WINDOWS ' Win95/98/ME
If bState Then
keys(iKey) = 1
Else
keys(iKey) = 0
End If
SetKeyboardState keys(0)
Case VER_PLATFORM_WIN32_NT ' WinNT/2k
GetKeyboardState keys(0)
If (keys(iKey) = 1) <> bState Then
' Simulate Key Press
keybd_event iKey, &H45, KEYEVENTF_EXTENDEDKEY Or 0, 0
' Simulate Key Release
keybd_event iKey, &H45, KEYEVENTF_EXTENDEDKEY Or KEYEVENTF_KEYUP, 0
End If
End Select
End Sub
Public Sub SetKeyboardLeds(bStateNumLock As Boolean, bStateCapsLock As Boolean, bStateScrollLock As Boolean)
SetKeyState VK_NUMLOCK, bStateNumLock
SetKeyState VK_CAPITAL, bStateCapsLock
SetKeyState VK_SCROLL, bStateScrollLock
End Sub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment