Hook SendMessage

c++ / delphi package - dll injection and api hooking
Post Reply
Crocotronic
Posts: 4
Joined: Sat Aug 18, 2012 1:45 pm

Hook SendMessage

Post by Crocotronic »

Hello,
i tried to hook the function SendMessage from User32 (just to come into contact with the component). If I hook the function and call SendMessage in the same programm it will work. But if I hook the function and send messages in other programms it will not work (no messagebox appears). Here is my code:

Code: Select all

SendMsgNextHook : function (hWnd: HWND; Msg: Cardinal; wParam: Integer; lParam: Integer): integer; stdcall;

function SendMsgHookProc(hWnd: HWND; Msg: Cardinal; wParam: Integer; lParam: Integer): integer; stdcall;
begin
  if MessageBox(0, PChar(inttostr(Msg)), 'Execute?', MB_YESNO or MB_ICONQUESTION) = IDYES then
    result:= SendMsgNextHook(hWnd, Msg, wParam, lParam)
  else
    result:= ERROR_ACCESS_DENIED;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
 HookAPI('user32.dll', 'SendMessageA', @SendMsgHookProc, @SendMsgNextHook);
 SendMessage(Handle,0,0,0) // Works, but not in other programms
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
 UnhookAPI(@SendMsgNextHook);
end;
Could you help?

Greetings,
Crocotronic

EDIT: Damn, it's just process wide, right? How to realize it system wide?
iconic
Site Admin
Posts: 1065
Joined: Wed Jun 08, 2005 5:08 am

Re: Hook SendMessage

Post by iconic »

How to realize it system wide?
You have to insert your hooking code into a tiny DLL and call InjectLibrary(ALL_SESSIONS or SYSTEM_PROCESSES, ..) etc. By the way, you do realize that SendMessage is called a lot? You will end up flooding yourself with MessageBoxes, I'd recommend looking only for particular messages or using OutputDebugString instead of MessageBox

--Iconic
Crocotronic
Posts: 4
Joined: Sat Aug 18, 2012 1:45 pm

Re: Hook SendMessage

Post by Crocotronic »

Oh, I see! Thank you very much again. I will try it later - and yes, the code doesn't make sense ^^ I should check the message before I call the MessageBox.

EDIT: Works perfect too
madshi
Site Admin
Posts: 10754
Joined: Sun Mar 21, 2004 5:25 pm

Re: Hook SendMessage

Post by madshi »

@Crocotronic, I usually recommend starting your hook project by using one of the demos and modifying it to hook those APIs you need. That's the safest way to make sure that your hook dll etc is all structured "the right way".
Post Reply