Multiple Keyboard Hooks With SetWindowsHookEx

J

jonfroehlich

I have successfully implemented global keyboard hooks using
SetWindowsHookEx. A simplified version of this code is represented in
the KeyHook class below. However, if I attempt to create two instances
of KeyHook in code, only the first instance will actually work. The
second instance fails in Start() where SetWindowsHookEx returns 0 and
GetLastWin32Error returns 32. For example,

KeyHook keyHook1 = new KeyHook();
KeyHook keyHook2 = new KeyHook();
keyHook1.Start();
keyHook2.Start(); <-- this instance does not obtain a hook handle

I was hoping to be able to create multiple instances of KeyHook so
that I could, for example, create a KeyTrapper class that has its own
instance of KeyHook. Any help would be appreciated.

public class KeyHook{
private delegate int HookProc(int code, IntPtr wParam, IntPtr
lParam);
private HookProc _hookDelegate;
private int _hookHandle = 0;

public virtual bool Start()
{
_hookDelegate = new HookProc(HookProcedure);
_hookHandle = SetWindowsHookEx(WH_KEYBOARD_LL, _hookDelegate,
GetModuleHandle(null), 0);
}

private int HookProcedure(int code, IntPtr wParam, IntPtr lParam)
{
KBDLLHOOKSTRUCT hookStruct =
(KBDLLHOOKSTRUCT)Marshal.PtrToStructure(lParam,
typeof(KBDLLHOOKSTRUCT));
return CallNextHookEx(_hookDelegate,code, wParam, lParam);
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top