我正在使用 SetWindowsHookEx() 创建键盘挂钩。创建似乎成功,但注册的过程永远不会被调用。有什么我做错了吗?
#region Windows API Functions Declarations
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
private static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
private static extern bool UnhookWindowsHookEx(int idHook);
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
private static extern int CallNextHookEx(int idHook, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string lpModuleName);
#endregion
=
private void CreateHook()
{
int id_hook = (int)HookType.WH_KEYBOARD_LL;
HookProc lpfn = new HookProc(this.KeyboardHookProc);
using (ProcessModule curModule = Process.GetCurrentProcess().MainModule)
hHook = SetWindowsHookEx(id_hook, lpfn, GetModuleHandle(curModule.ModuleName), 0);
if (hHook == 0)
throw new Exception("could not start monitoring mouse events");
}
=
private int KeyboardHookProc(int code, IntPtr wParam, IntPtr lParam)
{
if (code >= 0)
Console.WriteLine((Keys)wParam.ToInt32());
return CallNextHookEx(0, code, wParam, lParam);
}
=