之前偶然看到类似的软件,查询并切换CapsLock键、NumLock键按键状态的软件,就顺便查了一下相关的Delphi代码,特记之如下:
查询按键状态的过程
procedure CheckKeyState(); var KeyState: TKeyboardState; CapsLockState , NumLockState : Boolean; begin GetKeyboardState(KeyState); CapsLockState := KeyState[VK_CAPITAL] = 1; NumLockState := KeyState[VK_NUMLOCK] = 1; end;
切换CapsLock键状态的过程
procedure ToggleCapsLock; var KeyState: TKeyboardState; begin GetKeyboardState(KeyState); if (KeyState[VK_CAPITAL] = 0) then begin Keybd_Event(VK_CAPITAL, 1, KEYEVENTF_EXTENDEDKEY or 0, 0); Keybd_Event(VK_CAPITAL, 1, KEYEVENTF_EXTENDEDKEY or KEYEVENTF_KEYUP, 0); end else begin Keybd_Event(VK_CAPITAL, 0, KEYEVENTF_EXTENDEDKEY or 0, 0); Keybd_Event(VK_CAPITAL, 0, KEYEVENTF_EXTENDEDKEY or KEYEVENTF_KEYUP, 0); end; end;
切换NumLock键状态的过程
procedure ToggleNumLock; var KeyState: TKeyboardState; begin GetKeyboardState(KeyState); 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;
Excellent! Thanks.
A friendly suggestion:
begin
var kbState := getKeyboardState(keyState);
keybd_event(VK_NUMLOCK, kbState[VK_NUMLOCK] xor 1, KEYEVENTF_EXTENDEDKEY or 0, 0);
keybd_event(VK_NUMLOCK, kbState[VK_NUMLOCK] xor 1, KEYEVENTF_EXTENDEDKEY or KEYEVENTF_KEYUP, 0);
end;
Baz.