2

I am setting a global hook with the following code:

SetWindowsHookEx(WH_MOUSE_LL, MouseProc, NULL, 0)

I have a breakpoint set so that when I first run the application I can see that the MouseProc method is called. This works but after the first time it is no longer called. Is the Hook automatically removed, how do I get this so that the hook automatically persists? I am writing this application for windows and this is a C++ win32 project.

Mark Achrin
  • 357
  • 2
  • 7
  • 15
  • Please post the code for your MouseProc. – drescherjm Jan 07 '14 at 15:52
  • 1
    You need to pass a valid module handle. You probably meant to say `GetModuleHandle(NULL)`. – chris Jan 07 '14 at 15:53
  • Thank you for the answers but I figured out that breakpointing was actually what was causing the problem. It seems the hook is uninstalled when you breakpoint, it works perfectly until I breakpoint. – Mark Achrin Jan 07 '14 at 15:57

2 Answers2

8

I have a breakpoint set

That's enough to explain the problem. The debugger will break of course. Which prevents further mouse messages from being delivered to the window with the focus. Windows puts up with that for 5 seconds, then unceremoniously disables your hook because it thinks your code is broken.

The timeout is configurable, you can use Regedit.exe to set the HKEY_CURRENT_USER\Control Panel\Desktop\LowLevelHooksTimeout value. Not present by default, add the DWORD value first. The unit is milliseconds.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • Yep, spot on with this answer. I figured this out just before you posted. Thanks for going on to explain why this is the case though, I really appreciate your help Hans. – Mark Achrin Jan 07 '14 at 18:42
2

First you need to do:

return CallNextHookEx(_hook, nCode, wParam, lParam);

in your MouseProc, so it should return.

Second, it's not possible to debug most of codes which does have hook, your app will crash, because windows expecting your MouseProc function to return as soon as possible with return. Also your code should have Message handling code, like GetMessage, TranslateMessage and DispatchMessage.

Example code: SetWindowsHookEx for WH_MOUSE

Community
  • 1
  • 1
72DFBF5B A0DF5BE9
  • 4,954
  • 3
  • 21
  • 24