Why must SetWindowsHookEx be used with a windows message queue

The low-level hooks, WH_KEYBOARD_LL and WH_MOUSE_LL are different from all the other hooks. They don’t require a DLL to be injected into the target process. Instead, Windows calls your hook callback directly, inside your own process. To make that work, a message loop is required. There is no other mechanism for Windows to make callbacks on your main thread, the callback can only occur when you’ve called Get/PeekMessage() so that Windows is in control.

A global hook like WH_KEYBOARD is very different. It requires a DLL and the callback occurs within the process that processes the keyboard message. You need some kind of inter-process communication to let your own program be aware of this. Named pipes are the usual choice. Which otherwise of course requires that this injected process pumps a message loop. It wouldn’t get keyboard messages otherwise.

Favor a low-level hook, they are much easier to get going. But do pump or it won’t work. And beware of timeouts, if you’re not responsive enough then Windows will kill your hook without notice.

Understanding the low-level mouse and keyboard hook (win32)

Leave a Comment