1 首先倒入所需要的windows函数,主要有三个,SetWindowsHookEX用来安装钩子,UnhookWindowsHookEX用来卸载钩子以及CallNextHookEX用来将hook信息传递到链表中下一个hook处理过程。
2 在安装全局钩子的时候,我们就要做替换了,将WH_MOUSE和WH_KEYBORAD分别换成WH_MOUSE_LL和WH_KEYBORAD_LL:
//SetWindowsHookEX 用于安装钩子
[DllImport(\"user32.dll\",CharSetCharSet=CharSet.Auto, CallingConventionCallingConvention=CallingConvention.StdCall,SetLastError=true)] private static extern int SetWindowsHookEx( intidHook, HookProclpfn, IntPtrhMod, intdwThreadId);
//UnHookWindowsHookEX 用于卸载钩子
[DllImport(\"user32.dll\",CharSetCharSet=CharSet.Auto, CallingConventionCallingConvention=CallingConvention.StdCall,SetLastError=true)] private static extern int UnhookWindowsHookEx(intidHook);
//CallNextHookEX 用于将hook信息传递到链表中下一个hook处理过程
[DllImport(\"user32.dll\",CharSetCharSet=CharSet.Auto, CallingConventionCallingConvention=CallingConvention.StdCall)] private static extern int CallNextHookEx( intidHook, intnCode, intwParam, IntPtrlParam);
//installhook 其中第一个参数WH_MOUSE_LL原来是WH_MOUSE
hMouseHook=SetWindowsHookEx(WH_MOUSE_LL,MouseHookProcedure,Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]),0);
//installhook 其中第一个参数WH_KEYBOARD_LL原来是WH_KEYBORAD
hKeyboardHook=SetWindowsHookEx(WH_KEYBOARD_LL,KeyboardHookProcedure,Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]), 0);
//下面是关于鼠标和键盘的两个Callback函数:
private int MouseHookProc(int nCode, int wParam, IntPtr lParam)
{ // if ok and someone listens to our events
if ((nCode >= 0) && (OnMouseActivity != null))
{
//Marshall the data from callback.
MouseLLHookStruct mouseHookStruct = (MouseLLHookStruct)Marshal. PtrToStructure(lParam, typeof(MouseLLHookStruct));
//detect button clicked
MouseButtons button = MouseButtons.None;
short mouseDelta = 0;
本内容试读结束,登录后可阅读更多
下载后可阅读完整内容,剩余2页未读,立即下载