Mega Code Archive

 
Categories / Delphi / Hardware
 

Programmatically Get and Set the State of the CapsLock and NumLock Keys (Delphi)

Title: Programmatically Get and Set the State of the CapsLock and NumLock Keys (Delphi) The VK_CAPITAL virtual key constant defines the Caps Lock key. The VK_NUMLOCK constant defines the Num Lock key. If you need to programmatically turn on or off the Caps Lock or Num Lock key, you can use the following procedure: procedure ToggleNumLock; var KeyState: TKeyboardState; begin //note: Use VK_CAPITAL for Caps Lock GetKeyboardState(KeyState) ; //simulate key events (down + up) if (KeyState[VK_NUMLOCK] = 0) then begin Keybd_Event(VK_NUMLOCK, 1, KEYEVENTF_EXTENDEDKEY or 0, 0) ; Keybd_Event(VK_NUMLOCK, 1, KEYEVENTF_EXTENDEDKEY or KEYEVENTF_KEYUP, 0) ; end else begin Keybd_Event(VK_NUMLOCK, 0, KEYEVENTF_EXTENDEDKEY or 0, 0) ; Keybd_Event(VK_NUMLOCK, 0, KEYEVENTF_EXTENDEDKEY or KEYEVENTF_KEYUP, 0) ; end; end; Note: The keybd_event function synthesizes a keystroke. We call it two times to generate WM_KEYUP and WM_KEYDOWN messages.