C#实现全局钩子步骤
如何在C#中应用全局钩子?之前写的全局钩子全是用unmanaged C或C++写个DLL来建立,可大家都知道,C#是应用场景.Net Framework的,是managed,如何让C#建立全局钩子呢?因此刚开始到在网上检索,总算寻找一篇文章,318804 - HOW TO: Set a Windows Hook in Visual C# .NET,里边详尽的表明了怎么使用鼠标钩子捕捉电脑鼠标的中移动等,但是,它只有在Application里起功效,出了Application就不起作用了,就是它還是沒有建立全局钩子,并且稿子结尾处说:“Global Hooks are not supported in the .NET Framework有限责任公司”,这可该怎么办呢?
别担忧,方法一直有的,历经几番探求之后,发觉WH_KEYBORAD_LL和WH_MOUSE_LL这2个low-level的hook能够被安裝成全局变量的,这就好批了,人们暂且用这2个low-level的hook替换成掉WH_KEYBORAD和WH_MOUSE,因此刚开始检测。結果取得成功了,在C#建立全局钩子。
人们看来一下下关键代码段。
最先倒进所必须的windows涵数,关键有3个,SetWindowsHookEX用于安裝勾子,UnhookWindowsHookEX用于卸载掉勾子及其CallNextHookEX用于将hook信息的传递到链表中下个hook处理方式。
[DllImport(\"user32.dll\",CharSetCharSet=CharSet.Auto, CallingConventionCallingConvention=CallingConvention.StdCall,SetLastError=true)] privatestaticexternintSetWindowsHookEx( intidHook, HookProclpfn, IntPtrhMod, intdwThreadId); [DllImport(\"user32.dll\",CharSetCharSet=CharSet.Auto, CallingConventionCallingConvention=CallingConvention.StdCall,SetLastError=true)] privatestaticexternintUnhookWindowsHookEx(intidHook); [DllImport(\"user32.dll\",CharSetCharSet=CharSet.Auto, CallingConventionCallingConvention=CallingConvention.StdCall)] privatestaticexternintCallNextHookEx( intidHook, intnCode, intwParam, IntPtrlParam); 相关这2个low-level hook在Winuser.h中的界定
///WindowsNT/2000/XP: Installsahookprocedurethatmonitorslow-levelmouseinputevents. ///[Page] privateconstintWH_MOUSE_LL=14; /// ///WindowsNT/2000/XP: Installsahookprocedurethatmonitorslow-levelkeyboardinputevents. /// privateconstintWH_KEYBOARD_LL=13; 在安裝全局钩子的那时候,人们还要做替换成了,将WH_MOUSE和WH_KEYBORAD分別换为WH_MOUSE_LL和WH_KEYBORAD_LL:
//installhook hMouseHook=SetWindowsHookEx( WH_MOUSE_LL, //原先是WH_MOUSE MouseHookProcedure, Marshal.GetHINSTANCE( Assembly.GetExecutingAssembly().GetModules()[0]), 0); //installhook hKeyboardHook=SetWindowsHookEx( WH_KEYBOARD_LL,//原先是
相关文章
- 2条评论
- 只影羡兔2022-05-30 11:18:22
- orslow-levelkeyboardinputevents. /// privateconstintWH_KEYBOARD_LL=13; 在安裝全局钩子的那时候,人们还要做替换成了,将WH_MOUSE和WH_KE
- 野欢柔侣2022-05-30 12:30:08
- testaticexternintUnhookWindowsHookEx(intidHook); [DllImport(\"user32.dll\",CharSetCharSet=CharSet.Auto, Calli