C
cAkk
Unregistered / Unconfirmed
GUEST, unregistred user!
目的是要捕获鼠标在屏幕上所在的窗口句柄,先DLL和form都自定义一个消息,<br>然后安装Hook时,把form的句柄传过去,当DLL捕获鼠标消息时,向该句柄发送<br>自定义消息,鼠标所在窗口句柄放在wParam里面:<br><br>DLL如下:<br>=================<br>library capwnd;<br><br>uses<br> SysUtils, Classes,windows,messages;<br>var<br> hNextHookProc: HHook;<br> procSaveExit: Pointer;<br> receiver,msg_id:integer;<br><br>const STR_MSGMOUSEPOSchar='WM_MOUSEPOS';<br><br>function MousePosHookHandler(iCode: Integer; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall;<br>var h:hwnd;<br>begin<br> if iCode &lt; 0 then<br> Result := CallNextHookEx(hNextHookProc, iCode, wParam, lParam)<br> else<br> begin<br> if wParam = WM_MOUSEMOVE then<br> begin<br> h:=windowfrompoint(PMouseHookStruct(lParam).pt);<br> if h&lt;&gt;0 then postmessage(receiver,msg_id,PMouseHookStruct(lParam).hwnd,0);<br> end;<br> Result := 0;<br> end;<br>end;<br><br>function EnableMouseHook(hld:hwnd): BOOL; export;<br>begin<br> Result := False;<br> receiver:=hld;<br> if hNextHookProc &lt;&gt; 0 then Exit;<br> hNextHookProc := SetWindowsHookEx(WH_MOUSE, MousePosHookHandler,HInstance, 0);<br> Result :=hNextHookProc &lt;&gt; 0 ;<br>end;<br><br>function DisableMouseHook: BOOL; export;<br>begin<br> if hNextHookProc &lt;&gt; 0 then<br> begin<br> UnhookWindowshookEx(hNextHookProc);<br> hNextHookProc := 0;<br> end;<br> Result := hNextHookProc = 0;<br>end;<br><br>procedure MouseHookExit;<br>begin<br> if hNextHookProc &lt;&gt; 0 then DisableMouseHook;<br> ExitProc := procSaveExit;<br>end;<br><br>procedure IntoDll; stdcall;<br>begin<br> msg_id:=RegisterWindowMessage(STR_MSGMOUSEPOS);<br> receiver:=0;<br>end;<br><br>exports<br> EnableMouseHook,<br> DisableMouseHook;<br>begin<br> Intodll;<br> hNextHookProc := 0;<br> procSaveExit := ExitProc;<br> ExitProc := @MouseHookExit;<br>end.<br><br><br>form如下:<br>==========<br>unit main;<br><br>interface<br><br>uses<br> Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,<br> StdCtrls;<br><br>type<br> TForm1 = class(TForm)<br> Button1: TButton;<br> Button2: TButton;<br> procedure FormCreate(Sender: TObject);<br> procedure FormClose(Sender: TObject; var Action: TCloseAction);<br> procedure WndProc(var Mess: TMessage); override;<br> private<br> { Private declarations }<br> public<br> { Public declarations }<br> end;<br><br>var<br> Form1: TForm1;<br> msg_id:integer;<br>const STR_MSGMOUSEPOSchar='WM_MOUSEPOS';<br><br>implementation<br>function EnableMouseHook(hld:hwnd): BOOL; external 'capwnd.DLL';<br>function DisableMouseHook: BOOL; external 'capwnd.DLL';<br><br>{$R *.DFM}<br><br>procedure TForm1.FormCreate(Sender: TObject);<br>begin<br> msg_id:=RegisterWindowMessage(STR_MSGMOUSEPOS);<br> EnableMouseHook(handle);<br>end;<br><br>procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);<br>begin<br> DisableMouseHook;<br>end;<br>procedure TForm1.WndProc(var Mess: TMessage);<br>begin<br> if (mess.msg=msg_id) then<br> caption:=inttostr(mess.WParam);<br> inherited;<br>end;<br><br>end.<br>