切换CapsLock和NumLock键状态的Delphi代码

  之前偶然看到类似的软件,查询并切换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;
有人爱: 醉倚黄昏
有事做: https://zyhh.me/delphi/toggle-capslock-numlock.html
有所期待: 一个有雨有肉的夜晚,和你没头没尾分一瓶酒。
评论 (1)
  1. # 1
    Baz Cuda 2024-06-08 13:31

    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.