Delphi monitoring status of CapsLock key

delphi, winapi

Solution

Do this with a low level keyboard hook, `WH_KEYBOARD_LL`. Install the hook with `SetWindowHookEx`. You'll get notified of every keyboard event in the hook proc. Detect the original state by calling `GetKeyboardState`.

Note that you must read the documentation more carefully. For `GetKeyboardState` it says:

If the key is a toggle key, for example CAPS LOCK, then the low-order bit is 1 when the key is toggled and is 0 if the key is untoggled.

Therefore it is erroneous to test the entire byte against zero. Test just the low-order bit. Use `and $1` to pick out that bit.

Problem

My program runs in the background, and uses a timer to regularly check if Capslock is ON or OFF. My question is if there exists a better solution than using a timer? ``` procedure TForm1.Timer2Timer(Sender: TObject); var KeyState: TKeyboardState; begin GetKeyboardState(KeyState) ; if (KeyState[VK_CAPITAL] = 0) then CheckBox1.Checked:=False //Capslock is OFF else CheckBox1.Checked:=True; //Capslock is ON end; ```

Original source