How to break into debugger when specific Windows message is sent or posted

We have recently been fighting a weird problem in our .NET application that was caused by a duplicate WM_KEYDOWN message. It relatively is easy to figure out who receives the message (Spy++ helps a lot), but how to find out who sends it?

If you know (or suspect) the process that sends your message, here’s how to debug it in Visual Studio 2013:

1. Run the program you want to debug.
2. Attach debugger, make sure native debugger is selected.
3. Break into debugger, if it’s not there already.
4. Open window Debug->Windows->Modules, load symbols for user32.dll
5. Open BreakPoints window.
6. Add new break point at each of the functions below. IMPORTANT: set language to C++ (does not seem to work otherwise).
7. Functions: _PostMessageA@16, _PostMessageW@16, _SendMessageA@16, SendMessageW@16.
8. For each breakpoint set the following condition: *(int*)(esp+8) == 0x100
9. Resume the app and enjoy.

Explanation of the condition:

ESP is the stack pointer
*ESP is the return address
*(ESP+4) is the first parameter, hWnd
*(ESP+8) is the second parameter, uMsg

So, our condition basically amounts to uMsg == WM_KEYDOWN.
If you want to break on sending a WM_KEYDOWN message to a specific window handle, you can set the condition like so:
*(int*)(esp+4) == 0xmyhandlehere && *(int*)(esp+8) == 0x100

Leave a Reply

Your email address will not be published. Required fields are marked *