views:

248

answers:

3

I want to intercept messages that are being sent to a window in a different process. What is the best way to do this? I can't see the messages when I use the WH_GETMESSAGE hook, and I'm not sure if I can subclass across processes? Any help would be much appreciated.

+4  A: 

If the message is sent rather than posted WH_GETMESSAGE won't see it. You need WH_CALLWNDPROC. If you're working across processes you'll need a system-wide hook in a DLL. You don't mention how you invoked SetWindowsHookEx, so I don't know if your hooking failed because it wasn't global, or because the message you were looking for was sent.

If you haven't worked with system-wide hooks before, I have an example of a system-wide hook on my website here. That's a keyboard hook, but the principle is the same.

Stop me if I'm unintentionally talking down here - your question was so short I can't infer your expertise level. But messing around with hooks does imply some experience...

Bob Moore
Sorry, I should have provided more detail. I did get WH_CALLWNDPROC to read the messages, but I how can I remove the message from the queue using that? I want to prevent some messages from reaching the target window.
Jon Tackabury
Then don't pass the message to CallNextHookEx
Bob Moore
It doesn't matter if I call CallNextHookEx or not, the message always reaches the target window. :(
Jon Tackabury
From MSDN: "The CallWndProc hook procedure can examine the message, but it cannot modify it. After the hook procedure returns control to the system, the message is passed to the window procedure". That implies that you can prevent the message going to the next hookproc, but not the recipient window. Bummer...
Bob Moore
It's possible to swallow keystrokes (I've done this), but it looks like you can't swallow a sent message. Sorry it took so long to get around to looking at this, I've been out delivering wedding invitations. No, not _my_ wedding :-)
Bob Moore
Thanks for following up. :) I'll keep hunting for a good solution.
Jon Tackabury
A: 

You'll need to set a system wide message hook. Here is a tutorial.

Reed Copsey
+2  A: 

You need to inject your own code into the process that owns the windows you wish to intercept messages from. Fortunately, SetWindowsHookEx() makes this fairly easy, although you may have a bit of trouble at first if you've only used it for in-process hooking up to now.

I can recommend two excellent articles on the subject:

  1. Joseph Newcomber's Hooks and DLLs
  2. Robert Kuster's Three Ways to Inject Your Code into Another Process
Shog9