ChatGPT:用delphi写一个键盘鼠标的全局钩子dll示例

作者: cnpim CNPIM 2023年06月09日

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;beginend.


本文阅读量:

声明:本信息来源于网络,仅用于学习和技术交流,如有侵权或其他问题,请联系本站处理。

技术支持:CNPIM.COM