为什么这样的鼠标钩子只能对调用窗口有用?(附源码)

smilelhh 2004-09-20 11:19:19
例子都是书上的。只对本调用窗口有用!
library mhk;

uses Windows, Messages, SysUtils;

type mydata = record
data1: array[1..2] of DWORD;
data2: TMOUSEHOOKSTRUCT;
end;
var hObject: THandle;
pMem: Pointer;
NextHook: HHook;
procSaveExit: Pointer;

procedure UnMapMem;
begin
if Assigned(pMem) then begin
UnMapViewOfFile(pMem);
pMem := nil
end;
end;

procedure MapMem;
begin
hObject := CreateFileMapping($FFFFFFFF, nil, Page_ReadWrite, 0, $FFFF, pChar('_IOBuffer'));
if hObject = 0 then raise Exception.Create('创建公用数据的Buffer不成功!');
pMem := MapViewOfFile(hObject, FILE_MAP_WRITE, 0, 0, SizeOf(mydata));
if not Assigned(pMem) then begin
begin
UnMapMem;
raise Exception.Create('创建公用数据的映射关系不成功!');
end;
end;
end;

procedure DLLMain(dwReason: DWord); far;
begin
case dwReason of
DLL_PROCESS_ATTACH: begin
pMem := nil;
hObject := 0;
MapMem; //以下的公有数据,如tHWND,tMessageID将直接使用本Buf.
end;
DLL_PROCESS_DETACH: UnMapMem;
DLL_THREAD_ATTACH,
DLL_THREAD_DETACH: ; //缺省
end;
end;


function GetPublicP: Pointer; export;
begin //这里引出了公用数据区的指针,你可以在你的应用程序中自由操作它。 但建议去掉此接口。
Result := pMem;
end;

function HookHandler(iCode: Integer; wParam: WPARAM; lParam: LPARAM):
LRESULT; stdcall; export;
begin
Result := 0;
if iCode < 0 then
begin
Result := CallNextHookEx(NextHook, iCode, wParam, lParam);
exit;
end;

case wparam of
WM_MOUSEMOVE:
begin
mydata(pmem^).data2 := pMOUSEHOOKSTRUCT(lparam)^;
PostMessage(mydata(pMem^).data1[1], mydata(pMem^).data1[2], wParam, integer(@(mydata(pmem^).data2)));
end;
end; //发送消息}
Result := CallNextHookEx(NextHook, iCode, wParam, lParam);

end;

function OpenGetKeyHook(sender: HWND; MessageID: WORD): BOOL; export;
begin
Result := False;
if NextHook <> 0 then Exit; //已经安装了本钩子
mydata(pmem^).data1[1] := sender;
mydata(pmem^).data1[2] := messageid;

NextHook := SetWindowsHookEx(WH_mouse, HookHandler, HInstance, 0);
Result := NextHook <> 0;
end;

function CloseGetKeyHook: BOOL; export;
begin
if NextHook <> 0 then begin
UnhookWindowshookEx(NextHook); //把钩子链链接到下一个钩子处理上.
NextHook := 0;
end;
Result := NextHook = 0;
end;

procedure HookExit; far;
begin
CloseGetKeyHook;
ExitProc := procSaveExit;
end;

exports
OpenGetKeyHook,
CloseGetKeyHook,
GetPublicP;

begin
NextHook := 0;
procSaveExit := ExitProc;
DLLproc := @DLLMain;
ExitProc := @HookExit;
DLLMain(DLL_PROCESS_ATTACH);
end.

end.
...全文
128 5 打赏 收藏 举报
写回复
5 条回复
切换为时间正序
当前发帖距今超过3年,不再开放新的回复
发表回复
Nebulaliu 2004-10-14
  • 打赏
  • 举报
回复
up
smilelhh 2004-09-23
  • 打赏
  • 举报
回复
自己解决了:
将WH_mouse改成Wh_mouse_ll
smilelhh 2004-09-20
  • 打赏
  • 举报
回复
up self
ahjoe 2004-09-20
  • 打赏
  • 举报
回复
你在win98下试过没?
progray 2004-09-20
  • 打赏
  • 举报
回复
mark
发帖
Windows SDK/API

1177

社区成员

Delphi Windows SDK/API
社区管理员
  • Windows SDK/API社区
加入社区
帖子事件
创建了帖子
2004-09-20 11:19
社区公告
暂无公告