library GlobalHooks; uses Windows; {$R *.res} const WH_KEYBOARD_LL = 13; WH_MOUSE_LL = 14; type TKeyboardHook = record Hook: HHOOK; Callback: function(nCode: Integer; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall; end; TMouseHook = record Hook: HHOOK; Callback: function(nCode: Integer; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall; end; var KeyboardHook: TKeyboardHook; MouseHook: TMouseHook; function KeyboardHookCallback(nCode: Integer; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall; begin if (nCode = HC_ACTION) and ((wParam = WM_KEYDOWN) or (wParam = WM_KEYUP)) then begin // 处理键盘事件 // ... end; Result := CallNextHookEx(KeyboardHook.Hook, nCode, wParam, lParam); end; function MouseHookCallback(nCode: Integer; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall; begin if (nCode = HC_ACTION) and ((wParam = WM_LBUTTONDOWN) or (wParam = WM_LBUTTONUP) or (wParam = WM_RBUTTONDOWN) or (wParam = WM_RBUTTONUP)) then begin // 处理鼠标事件 // ... end; Result := CallNextHookEx(MouseHook.Hook, nCode, wParam, lParam); end; function InstallKeyboardHook(Callback: function(nCode: Integer; wParam: WPARAM; lParam: LPARAM): LRESULT): Boolean; begin Result := False; if not Assigned(Callback) then Exit; if Assigned(KeyboardHook.Callback) then Exit; KeyboardHook.Hook := SetWindowsHookEx(WH_KEYBOARD_LL, @KeyboardHookCallback, HInstance, 0); if KeyboardHook.Hook = 0 then Exit; KeyboardHook.Callback := Callback; Result := True; end; function InstallMouseHook(Callback: function(nCode: Integer; wParam: WPARAM; lParam: LPARAM): LRESULT): Boolean; begin Result := False; if not Assigned(Callback) then Exit; if Assigned(MouseHook.Callback) then Exit; MouseHook.Hook := SetWindowsHookEx(WH_MOUSE_LL, @MouseHookCallback, HInstance, 0); if MouseHook.Hook = 0 then Exit; MouseHook.Callback := Callback; Result := True; end; function RemoveKeyboardHook: Boolean; begin Result := False; if KeyboardHook.Hook = 0 then Exit; if UnhookWindowsHookEx(KeyboardHook.Hook) then begin KeyboardHook.Hook := 0; KeyboardHook.Callback := nil; Result := True; end; end; function RemoveMouseHook: Boolean; begin Result := False; if MouseHook.Hook = 0 then Exit; if UnhookWindowsHookEx(MouseHook.Hook) then begin MouseHook.Hook := 0; MouseHook.Callback := nil; Result := True; end; end; exports InstallKeyboardHook, InstallMouseHook, RemoveKeyboardHook, RemoveMouseHook; begin end.
标签:wParam,begin,end,Hook,delphi,示例,dll,Callback,KeyboardHook From: https://www.cnblogs.com/onlyou13/p/17128388.html