其中涉及到的一些API,网上均能查到详细的解释,这里不再熬述。源码下载
因为是全局钩子,所以要用dll注入。用到的鼠标消息结构如下:
- PMouseHookStruct = ^TMouseHookStruct;
- {$EXTERNALSYM tagMOUSEHOOKSTRUCT}
- tagMOUSEHOOKSTRUCT = packed record
- pt: TPoint;
- hwnd: HWND;
- wHitTestCode: UINT;
- dwExtraInfo: DWORD;
- end;
- TMouseHookStruct = tagMOUSEHOOKSTRUCT;
DLL代码,Mouse_HookDLL
- library Mouse_HookDLL;
-
-
- uses
- SysUtils,
- Windows,
- Messages,
- Classes;
-
- {$R *.res}
-
- var
- NextHook : HHook;
-
- CallHandle : HWND;
-
- MessageID : Word;
-
- function HookProc(code:Integer;wParam:WPARAM;lParam:LPARAM):LRESULT;stdcall;
- begin
- Result := 0;
- if code < 0 then
- Result := CallNextHookEx(NextHook,code,wParam,lParam);
- case wParam of
- WM_NCMOUSEMOVE,WM_MOUSEMOVE:
- begin
-
- SendMessage(CallHandle,MessageID,wParam,Integer(@pMouseHookStruct(lParam)^));
- end;
- end;
- end;
-
- function StartHook(MsgID:Word):Bool;stdcall;
- begin
- Result := False;
- if NextHook <> 0 then
- Exit;
- MessageID := MsgID;
-
- NextHook := SetWindowsHookEx(WH_MOUSE_LL,@HookProc,HInstance,0);
- Result := NextHook <> 0;
- end;
-
- function StopHook:Bool;stdcall;
- begin
- if NextHook <> 0 then
- begin
- UnHookWindowsHookEx(NextHook);
- NextHook := 0;
- end;
- Result := NextHook = 0;
- end;
-
- procedure SetCallHandle(sender:HWND);stdcall;
- begin
- CallHandle := sender;
- NextHook := 0;
- end;
-
- exports
- StartHook name 'StartHook',
- StopHook name 'StopHook',
- SetCallHandle name 'SetCallHandle';
-
- begin
- end.
调用者代码,HookTest
- unit HookTest;
-
- interface
-
- uses
- Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
- Dialogs, StdCtrls;
-
- type
- TfrmHookTest = class(TForm)
- Label1: TLabel;
- procedure FormCreate(Sender: TObject);
- procedure FormClose(Sender: TObject; var Action: TCloseAction);
- private
-
-
- procedure WndProc(var Message: TMessage);override;
- public
-
- end;
-
- var
- frmHookTest: TfrmHookTest;
-
- const
- WM_TestMsg = WM_User + 100;
-
- implementation
-
- {$R *.dfm}
- function StartHook(MsgID:Word):Bool;stdcall;external 'Mouse_HookDLL.dll';
- function StopHook:Bool;stdcall;external 'Mouse_HookDLL.dll';
- procedure SetCallHandle(sender:HWND);stdcall;external 'Mouse_HookDLL.dll';
-
- procedure TfrmHookTest.FormClose(Sender: TObject; var Action: TCloseAction);
- begin
- StopHook;
- end;
-
- procedure TfrmHookTest.FormCreate(Sender: TObject);
- begin
- SetCallHandle(Self.Handle);
- if not StartHook(WM_TestMsg) then
- begin
- ShowMessage('挂钩失败!');
- end;
- end;
-
- procedure TfrmHookTest.WndProc(var Message: TMessage);
- var
- x,y:integer;
- begin
-
- if Message.Msg = WM_TestMsg then
- begin
- x := pMouseHookStruct(Message.LParam)^.pt.X;
- y := pMouseHookStruct(Message.LParam)^.pt.Y;
-
- Self.Label1.Caption := '鼠标当前位置:x='+IntToStr(x)+' : y='+IntToStr(y);
- end;
- inherited;
- end;
-
- end.
运行结果
http://blog.csdn.net/bdmh/article/details/5888287
|
请发表评论