views:

92

answers:

3

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.

A: 

As Per MSDN , WH__KEYBOARD___LL is applied globally not application specific.

If you want to install hook for a process specific threads use WH___KEYBOARD.

Ashish
Its not about global or application specific.Issue is that when calling thread terminates ,hooking also terminates.
Alien01
You are right , I have injected hooks dll in ms excel and i have installed hook by specifying threadId of the main app window which terminated only when application exits and it works fine.
Ashish
A: 

Just install the hook in the main function. If you need it only when a specific thread runs, you can use a volatile flag.

dwo
+1  A: 

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.

Hans Passant