我正在使用本文中的代码:
private const int WH_KEYBOARD_LL = 13;
private const int WM_KEYDOWN = 0x0100;
private static LowLevelKeyboardProc _proc = HookCallback;
private static IntPtr _hookID = IntPtr.Zero;
public static void Main()
{
_hookID = SetHook(_proc);
//Application.Run();
//UnhookWindowsHookEx(_hookID);
}
private static IntPtr SetHook(LowLevelKeyboardProc proc)
{
using (Process curProcess = Process.GetCurrentProcess())
using (ProcessModule curModule = curProcess.MainModule)
{
return SetWindowsHookEx(WH_KEYBOARD_LL, proc,
GetModuleHandle(curModule.ModuleName), 0);
}
}
private delegate IntPtr LowLevelKeyboardProc(
int nCode, IntPtr wParam, IntPtr lParam);
private static IntPtr HookCallback(
int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
{
int vkCode = Marshal.ReadInt32(lParam);
***custom code***
}
return CallNextHookEx(_hookID, nCode, wParam, lParam);
}
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int idHook,
LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool UnhookWindowsHookEx(IntPtr hhk);
[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);
稍作修改,但有时当我按几个键太快时,计算机会“减慢”一点并变得有点“滞后”。
因此,当它异步触发事件 HookCallback 时,它有时会有点滞后,但我猜是这种方法“HookCallback”中的代码使其滞后还是它自己挂钩?我有一个想法,每次输入“HookCallback”时都创建一个新线程,这可能会有所帮助,但我是否想在每次按下键时启动一个新线程?我已经收到了一个异步调用,所以我不知道是否应该启动另一个线程。
所以我的问题很简单,它在哪里以及为什么会减慢计算机的速度,是自行挂钩还是自定义代码?或者我应该将自定义代码放在不同的线程中?
我还有另一个问题,有时在几次按键后“HookCallback”没有被调用,好像我已经“解开”了事件,它根本不会捕获任何击键。除非我手动执行,否则我如何确保它永远不会取消事件?
谢谢你。