/// <summary> /// 卸载钩子 /// </summary> public void UNLOAD_WINDOWS_KETBOARD_HOOK() { if (hHook != IntPtr.Zero) { //如果钩子已经挂上则取消钩子,否则不用取消 HookApi.UnhookWindowsHookEx(hHook); _hookProcHandle.Free(); hHook = IntPtr.Zero; } }
/// <summary> /// 钩子回调 /// </summary> /// <param name="nCode"></param> /// <param name="wParam"></param> /// <param name="lParam"></param> /// <returns></returns> public IntPtr KEYBOARD_HOOKPRO(int nCode, IntPtr wParam, IntPtr lParam) { KBDLLHOOKSTRUCT kb = new KBDLLHOOKSTRUCT(); HookApi.CopyMemory(ref kb, lParam, 20); //结果就在这里了 UNLOAD_WINDOWS_KETBOARD_HOOK(); SET_WINDOWS_KEYBOARD_HOOK(); curkeypresscode(kb.vkCode, (int)Control.ModifierKeys); return(HookApi.CallNextHookEx(hHook, nCode, wParam, lParam)); }
/// <summary> /// 设置钩子 /// </summary> public void SET_WINDOWS_KEYBOARD_HOOK() { if (hHook == IntPtr.Zero) { HookPro hk = new HookPro(this.KEYBOARD_HOOKPRO); _hookProcHandle = GCHandle.Alloc(hk); //挂钩子 hHook = HookApi.SetWindowsHookEx( WH_KEYBOARD_LL, hk, Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]), 0); if (hHook == IntPtr.Zero) { throw new Exception("安装钩子不成功!"); // 挂钩子不成功返回值 0 } } }