您應該使用Low Level Keyboard Hook,因爲即使您的應用程序沒有焦點,您也可以獲得每次擊鍵的通知。
我已經創建了一個小例子對你
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Vcl.ExtCtrls;
const
WM_UpdateScreen = WM_USER + 1;
type
TForm1 = class(TForm)
PanelCapsLock: TPanel;
PanelNumlock: TPanel;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
FHook: hHook;
KeyState: TKeyboardState;
public
procedure UpdateScreen(var message: TMessage); message WM_UpdateScreen;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
type
pKBDLLHOOKSTRUCT = ^KBDLLHOOKSTRUCT;
KBDLLHOOKSTRUCT = packed record
vkCode: DWORD;
scanCodem: DWORD;
flags: DWORD;
time: DWORD;
dwExtraInfo: ULONG_PTR;
end;
var
hkHook: hHook;
function LowLevelKeyboardProc(code: Integer; WParam: WParam; LParam: LParam): LRESULT stdcall;
const
LLKHF_UP = $0080;
var
Hook: pKBDLLHOOKSTRUCT;
bControlKeyDown: Boolean;
begin
try
Hook := pKBDLLHOOKSTRUCT(LParam);
case code of
HC_ACTION:
begin
if (Hook^.flags and LLKHF_UP) <> 0 then
if Hook.vkCode in [VK_NUMLOCK, VK_CAPITAL] then
PostMessage(Form1.Handle, WM_UpdateScreen, Hook.vkCode, 0);
end;
end;
finally
Result := CallNextHookEx(hkHook, code, WParam, LParam);
end;
end;
procedure HookIt;
begin
hkHook := SetWindowsHookEx(WH_KEYBOARD_LL, @LowLevelKeyboardProc, hInstance, 0);
end;
procedure UnHookIt;
begin
UnHookWindowsHookEx(hkHook);
end;
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
UnHookIt;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
GetKeyboardState(KeyState);
PostMessage(Handle, WM_UpdateScreen, VK_CAPITAL, 1);
PostMessage(Handle, WM_UpdateScreen, VK_NUMLOCK, 1);
HookIt;
end;
procedure TForm1.UpdateScreen(var message: TMessage);
begin
if message.LParam = 0 then
if KeyState[message.WParam] = 0 then
KeyState[message.WParam] := 1
else
KeyState[message.WParam] := 0;
if KeyState[VK_NUMLOCK] = 0 then
PanelNumlock.Color := clSilver
else
PanelNumlock.Color := clLime;
if KeyState[VK_CAPITAL] = 0 then
PanelCapsLock.Color := clSilver
else
PanelCapsLock.Color := clLime;
end;
end.
基本上在formCreate
我勾了鍵盤,並告訴我的程序在運作,我需要我的通知。在我的例子中,我叫它LowLevelKeyboardProc
然後,你只需要測試fot哪個鍵被按下,如果它是Num Lock的CapsLock之一,然後nofify表單。
操作系統? –
@JasonC Windows 7 –
您的最後一段已經提出了一種可能的解決方案:使用'GetCursorPos'和'SendMessage(...,WM_MOUSEMOVE,...)'強制消息循環更新應用程序中當前的鍵盤狀態在背景中。 – mghie