Delphi control state of CapsLock

My program runs in the background and uses a timer to regularly check for the presence or absence of Capslock.

My question is, is there 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;

      

+3


source to share


1 answer


Do this by using a low-level keyboard WH_KEYBOARD_LL

. Install the hook with SetWindowHookEx

. You will be notified of every keyboard event in the hook proc. Determine the original state by calling GetKeyboardState

.

Please note that you must read the documentation carefully. For GetKeyboardState

he says:



If the key is a toggle key, such as CAPS LOCK, then the least significant bit is 1 when the key is toggled and 0 if the key is not encrypted.

Therefore, it is wrong to check the entire byte for zero. Check only the least significant bit. Use and $1

to select this bit.

+6


source







All Articles