1. Home
  2. Computing & Technology
  3. Delphi Programming

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

By Zarko Gajic, About.com

Programmatically Toggle CapsLock / NumLock

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.

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

More Delphi Programming Quick Tips

Explore Delphi Programming

More from About.com

  1. Home
  2. Computing & Technology
  3. Delphi Programming
  4. Coding Delphi Applications
  5. Delphi Tips and Tricks
  6. Delphi 2006 Tips
  7. Programmatically Get and Set the State of the CapsLock and NumLock Keys (Delphi)

©2008 About.com, a part of The New York Times Company.

All rights reserved.