SetWindowsHookEx WH_KEYBOARD_LL not getting events

寵の児 提交于 2019-11-30 16:45:25

Your P/Invoke declarations are wrong, you are using int where IntPtr is required and mixing up idHook and hHook. After editing your code, this worked:

IntPtr hHook;
private delegate IntPtr HookProc(int nCode, IntPtr wp, IntPtr lp);
HookProc lpfn;

private IntPtr KeyboardHookProc(int code, IntPtr wParam, IntPtr lParam) {
  if (code >= 0)
    Console.WriteLine((Keys)wParam.ToInt32());
  return CallNextHookEx(hHook, code, wParam, lParam);
}

private void CreateHook() {
  int id_hook = 13;
  lpfn = new HookProc(this.KeyboardHookProc);
  using (ProcessModule curModule = Process.GetCurrentProcess().MainModule)
    hHook = SetWindowsHookEx(id_hook, lpfn, GetModuleHandle(curModule.ModuleName), 0);
  if (hHook == IntPtr.Zero)
    throw new Exception("could not start monitoring mouse events");
}
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
private static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
private static extern bool UnhookWindowsHookEx(IntPtr hHook);
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
private static extern IntPtr CallNextHookEx(IntPtr hHook, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string lpModuleName);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!