最近一个朋友在做个监控程序,需要监控键盘和鼠标的活动,但是用C#的程序(其他语言的HOOK都很平常了),他也查了KB,问我怎么实现。我也查了一下如这个KB就是:
KB318804 “HOW TO: Set a Windows Hook in Visual C# .NET”
基本意思是.NET的DLL没法被unmanaged code的进程调用,所以.NET无法写全局钩子。
但觉得还是不可思议啊,.NET不能底层了?但在还是在KB中得到了答案,WH_KEYBOARD_LL和WH_MOUSE_LL是可以在.NET里面用的全局钩子。
主要实现代码
[DllImport("user32.dll", CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall, SetLastError = true)]
private static extern int SetWindowsHookEx(
int idHook,
HookProc lpfn,
IntPtr hMod,
int dwThreadId);
[DllImport("user32.dll", CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall, SetLastError = true)]
private static extern int UnhookWindowsHookEx(int idHook);
[DllImport("user32.dll", CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall)]
private static extern int CallNextHookEx(
int idHook,
int nCode,
int wParam,
IntPtr lParam);
[DllImport("user32")]
private static extern int ToAscii(
int uVirtKey,
int uScanCode,
byte[] lpbKeyState,
byte[] lpwTransKey,
int fuState);
[DllImport("user32")]
private static extern int GetKeyboardState(byte[] pbKeyState);
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
private static extern short GetKeyState(int vKey); 使用SetWindowsHookEx函数(API函数),指定一个Hook类型、自己的Hook过程是全局还是局部Hook,同时给出Hook过程的进入点,就可以轻松的安装自己的Hook。
// 创建鼠标实例.
MouseHookProcedure = new HookProc(MouseHookProc);
//安装 鼠标hook
hMouseHook = SetWindowsHookEx(
WH_MOUSE_LL,
MouseHookProcedure,
Marshal.GetHINSTANCE(
Assembly.GetExecutingAssembly().GetModules()[0]),
0);
// 创建键盘实例.
KeyboardHookProcedure = new HookProc(KeyboardHookProc);
//安装 键盘hook
hKeyboardHook = SetWindowsHookEx(
WH_KEYBOARD_LL,
KeyboardHookProcedure,
Marshal.GetHINSTANCE(
Assembly.GetExecutingAssembly().GetModules()[0]),
0); 卸载Hook UnhookWindowsHookEx()函数(API函数)
具体可以查看源码
[招生]科锐逆向工程师培训(2024年11月15日实地,远程教学同时开班, 第51期)
上传的附件: