본문 바로가기

프로그래밍/Delphi

DLL을 이용한 마우스 전역 후킹(Hooking)

hookdll.pas

library hookdll;

uses
  windows;

var
  HookDeMouse: hHook;
  X, Y: Integer;
  HookMsg: cardinal;
{$R *.res}

function myHookProc(code: Integer; wParam, lParam: LongInt): LongInt; stdcall;

begin
  CallNextHookEx(HookDeMouse, Code, wParam, lParam);

  X := PMouseHookStruct(lParam).pt.X;
  Y := PMouseHookStruct(lParam).pt.Y;

  PostMessage(HWND_BROADCAST, HookMsg, X, Y);

  result := CallNextHookEx(HookDeMouse, Code, wParam, lParam);

end;

{procedure for install the hook}

procedure HookOn; stdcall;
begin

  HookDeMouse := SetWindowsHookEx(WH_MOUSE, @myHookProc, HInstance, 0);

end;

{procedure to uninstall the hook}

procedure HookOff; stdcall;
begin

  UnhookWindowsHookEx(HookDeMouse);

end;

exports HookOn,
  HookOff;

begin
  HookMsg := RegisterWindowMessage('myhookdll_hookmsg');

end.
사용예제 : hook.pas
hook.pas
-----------------------------------------------------------------------
unit hook;

interface

uses
 Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
 Dialogs, StdCtrls;

type
 TForm1 = class(TForm)
   Label1: TLabel;
   Button1: TButton;
   Button2: TButton;
   procedure Button1Click(Sender: TObject);
   procedure Button2Click(Sender: TObject);
   procedure AppMessage(var Msg: TMsg; var Handled: boolean);
 private
   { Private declarations }
 public
   { Public declarations }
 end;

function HookOn:integer; stdcall; external 'hookdll.dll';
function HookOff:integer; stdcall; external 'hookdll.dll';

var
 Form1: TForm1;
 HookMsg: cardinal;

implementation

{$R *.dfm}

procedure TForm1.AppMessage(var Msg: TMsg; var Handled: boolean);
begin

 if Msg.message = HookMsg then begin
   Label1.Caption := IntToStr(Msg.wParam) + ' : ' + IntToStr(msg.lParam);
 end;

end;

procedure TForm1.Button1Click(Sender: TObject);
begin

 if HookOn = 0 then
 begin

   MessageDlg('Hook Not Install.', mtError, [mbOK], 0);
   Exit;

 end;

Application.OnMessage := AppMessage;

end;

procedure TForm1.Button2Click(Sender: TObject);
begin

 HookOff;

end;

initialization
HookMsg := RegisterWindowMessage('myhookdll_hookmsg');

end.