要实现对双击左CTRL键的监控,必须玩钩子了。
代码很简单,新建VCL Form的工程,在窗体上放两个按钮,分别叫做 btnHook 和 btnUnHook。
调用就是 BeginHook 和 EndHook 这两个函数,窗体代码如下:
unit frmTestHookWinKey; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ShellAPI; type TForm1 = class(TForm) btnHook: TButton; btnUnHook: TButton; procedure btnHookClick(Sender: TObject); procedure btnUnHookClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} var KeyHook: HHook; HitTime: Cardinal; // 击键的间隔时间 HitThreshold: Integer; // 击键的间隔时间门限 function HookKey(Code: integer; wParam: wParam; lParam: lParam): LRESULT; stdcall; type PKBDLLHOOKSTRUCT = ^KBDLLHOOKSTRUCT; KBDLLHOOKSTRUCT = record vkCode: DWORD; ScanCode: DWORD; Flags: DWORD; Time: DWORD; dwExtraInfo: DWORD; end; begin // 如果左 CTRL 键按下 if (Code = HC_ACTION) and (PKBDLLHOOKSTRUCT(lParam).vkCode = VK_LCONTROL) and (wParam = WM_KEYDOWN) then begin if HitTime > 0 then begin HitTime := GetTickCount - HitTime; // 取得间隔时间 if HitTime <= HitThreshold then begin // 如果间隔时间在门限时间之内,则调用记事本 WinExec('notepad.exe', SW_SHOWNORMAL); HitTime := 0; end else HitTime := GetTickCount; end else HitTime := GetTickCount; end; Result := CallNextHookEx(KeyHook, Code, wParam, lParam); end; procedure BeginHook; begin KeyHook := SetWindowsHookEx(13 {=WH_KEYBOARD_LL}, @HookKey, HInstance, 0); end; procedure EndHook; begin UnhookWindowsHookEx(KeyHook); end; procedure TForm1.btnHookClick(Sender: TObject); begin BeginHook; end; procedure TForm1.btnUnHookClick(Sender: TObject); begin EndHook; end; procedure TForm1.FormCreate(Sender: TObject); begin HitTime := 0; HitThreshold := 200; // 200 ms end; end.
既然调用记事本都搞定了,干些其他的事儿自然不在话下了。
这段代码完全可以封装为一个模块,将监控的按键、间隔时间及回调函数当作参数传入即可。