Technology Programming

Programmatically Get and Set the State of the CapsLock and NumLock Keys

The VK_CAPITALvirtual 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.
Delphi tips navigator:
» How to Disable the Default PopUp (Context) Menu for a TEdit (TMemo, etc.) component
« How to Translate a Virtual Key Code to a Character

Leave a reply