Search code examples
c++windowswinapisetwindowshookex

not able to install hooks for all threads in a process


I am hooking keyboard in application . Requirement is to hook keyboard in all threads in the process.

I used SetWindowsHookEx API

SetWindowsHookEx(WH_KEYBOARD_LL, (HOOKPROC)::KeyboardHookProc, hInst, 0);

The hook is created for all the threads in process. This works fine until calling thread exists .As soon as calling thread terminates hook stop working.

Is there any way to hook on process rather than threads in process.


Solution

  • This fine print in the SDK docs for LowLevelKeyboardProc is crucial:

    This hook is called in the context of the thread that installed it. The call is made by sending a message to the thread that installed the hook. Therefore, the thread that installed the hook must have a message loop.

    In other words, you must keep the thread alive and the thread must pump a message loop. The behavior you see now is entirely by design.