hooking keyboard input twice

Joined
Nov 15, 2011
Messages
1
Reaction score
0
Hi,
I'm building a program that at some point needs to hook the keyboard input to prevent the user from pressing some key combinations. Then, at a later point I need to unhook the keyboard, and then, I need to hook again the keyboard.
I succeed in hooking the keyboard for the first time and then unhhok the keyboard, but when I try to hook it again using the same code, it seems that the hooking-method is not called at all, although 'SetWindowsHookEx' method succeeds.
Here is how I do it:

First, declarations:

[DllImport("user32", EntryPoint = "SetWindowsHookExA", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall, SetLastError = true, ExactSpelling = true)]
private static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hMod, int dwThreadId);
[DllImport("user32", EntryPoint = "UnhookWindowsHookEx", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall, SetLastError = true, ExactSpelling = true)]
private static extern int UnhookWindowsHookEx(int hHook);
[DllImport("user32", EntryPoint = "CallNextHookEx", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern int CallNextHookEx(int hHook, int nCode, int wParam, IntPtr lParam);
private static int LowLevelKeyboardProc(int nCode, int wParam, IntPtr lParam)
{
...
return CallNextHookEx(intLLKeyboard, nCode, wParam, lParam);
}
private delegate int HookProc(int nCode, int wParam, IntPtr lParam);
private static HookProc KeyboardDelegate = null; //Static member
private static int intLLKeyboard = 0; //Static member



Then, setting the hook:

KeyboardDelegate = new HookProc(LowLevelKeyboardProc);
System.Reflection.Module[] modules = System.Reflection.Assembly.GetExecutingAssembly().GetModules();
intLLKeyboard = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardDelegate, System.Runtime.InteropServices.Marshal.GetHINSTANCE(modules[0]), 0);



Later, unhooking :

UnhookWindowsHookEx(intLLKeyboard);




Then, trying to hook again :

KeyboardDelegate = new HookProc(LowLevelKeyboardProc);
System.Reflection.Module[] modules = System.Reflection.Assembly.GetExecutingAssembly().GetModules();
intLLKeyboard = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardDelegate, System.Runtime.InteropServices.Marshal.GetHINSTANCE(modules[0]), 0);

At this point 'intLLKeyboard' is not null, but nevertheless, it seems that the hooking procedure isn't called at all.
 

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