/// <summary> /// to set the hook function /// </summary> /// <returns></returns> public int SetHook() { //delegate? hProc = new Win32HookAPI.HookProc(MouseHookProc); //set the hook function as hProc,即钩子函数的地址指针 hHook = Win32HookAPI.SetWindowsHookEx(idHookType, hProc, IntPtr.Zero, 0); return(hHook); }
/// <summary> /// Hook function to minitor mouse action /// </summary> /// <param name="nCode"></param> /// <param name="wParam"></param> /// <param name="lParam"></param> /// <returns></returns> private int MouseHookProc(int nCode, IntPtr wParam, IntPtr lParam) { //将数据从非托管内存块封送到新分配的指定类型的托管对象 Win32HookAPI.MouseHookStruct MyMouseHookStruct = (Win32HookAPI.MouseHookStruct)Marshal.PtrToStructure(lParam, typeof(Win32HookAPI.MouseHookStruct)); if (nCode < 0) { return(Win32HookAPI.CallNextHookEx(hHook, nCode, wParam, lParam)); } else { this.Point = new Point(MyMouseHookStruct.pt.x, MyMouseHookStruct.pt.y); return(Win32HookAPI.CallNextHookEx(hHook, nCode, wParam, lParam)); } }
/// <summary> /// uninstall hook function /// </summary> public void UnHook() { Win32HookAPI.UnhookWindowsHookEx(hHook); }