Reputation: 1147
Im trying to use SetWindowsHookEx to Hook Mouse in some process. Im using Delphi 7. Code (DLL):
function MouseProc(code: integer; wParam: WPARAM; lParam: LPARAM)
: LongInt; stdcall;
var
AppWnd: HWND;
begin
Result := 0;
if (code < 0) then
Result := CallNextHookEx(HookHandle, code, wParam, lParam)
else begin
AppWnd := FindWindowW('ichookapplication', nil);
SendMessage(AppWnd, MW_MOUSEHOOKED, wParam, GetCurrentProcessId);
Result := CallNextHookEx(HookHandle, code, wParam, lParam);
end;
end;
procedure HookThreadId(theadId: Cardinal) export; stdcall;
var
e: DWORD;
begin
HookHandle := SetWindowsHookEx(WH_MOUSE, @MouseProc, 0, theadId);
if (HookHandle = 0) then
begin
e := GetLastError;
MessageBox(0, 'error', PAnsiChar(IntToStr(e)), MB_OK);
end;
end;
MW_MOUSEHOOKED is WM_USER + 101;
application:
//loading code
if (dll = 0) then
begin
dll := LoadLibrary('mhook.dll');
@Hook := nil;
@SetThreadHook := nil;
end;
if (dll > HINSTANCE_ERROR) then
begin
pH := GetProcAddress(dll, 'Hook');
@Hook := pH;
pSth := GetProcAddress(dll, 'HookThreadId');
@SetThreadHook := pSth;
end;
// attach code
h := FindWindow(nil, 'Form1');
terminalProc := GetWindowThreadProcessId(h, nil);
if (terminalProc = 0) then
begin
ShowMessage(IntToStr(GetLastError));
Exit;
end;
SetThreadHook(terminalProc);
So. SetWindowsHookEx returns 1428 error: Cannot set nonlocal hook without a module handle. But as i know if im using dll hmodule is not needed... How i whant it will work: Every mouse event will passing to my app (window class is 'ichookapplication') using WM_DATA (wParam is event data, lParam is ProcessId)
Thanks!
Upvotes: 1
Views: 2392
Reputation: 612944
WH_MOUSE
is a global hook. The DLL will be injected into hooked processes. You do need to supply a module handle. The name associated with error code 1428
is pretty clear, ERROR_HOOK_NEEDS_HMOD
. It's not as though it's difficult to provide a module handle. Pass HInstance
.
If you don't want to inject, then you'll need to use WH_MOUSE_LL
instead of WH_MOUSE
.
Upvotes: 2