onlyou13

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
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.

 

posted on 2023-02-16 21:25  onlyou13  阅读(246)  评论(0编辑  收藏  举报