我在C#中创建了一个简单的钩子键盘,所以我有以下代码:
private static IntPtr hKeyboardHook = IntPtr.Zero;
private const int WH_KEYBOARD_LL = 13;
private const int WM_KEYDOWN = 0x100;
private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr 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, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
private static extern int UnhookWindowsHookEx(IntPtr idHook);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr 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);
private delegate int HookProc(int nCode, int wParam, IntPtr lParam);
[DllImport("kernel32.dll")]
public static extern IntPtr GetModuleHandle(string lpModuleName);
private static LowLevelKeyboardProc _proc = HookCallback;
public void initialization()
{
using (Process curProcess = Process.GetCurrentProcess())
using (ProcessModule curModule = curProcess.MainModule)
{
hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, _proc, GetModuleHandle(curModule.ModuleName), 0);
}
}
private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
{
int vkCode = Marshal.ReadInt32(lParam);
if (vkCode >= 32 && vkCode < 160)
Console.Write((Keys)vkCode);
if (vkCode == 13)
Console.WriteLine("\n");
}
return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam);
}
没问题,工作正常!!我的程序抓住在其他程序中按下的所有键并将其写在控制台上。 但我想要按下按键的程序名称,我不知道我该怎么做。
任何人都可以帮助我?
答案 0 :(得分:2)
您使用的是低级别挂钩(WH_KEYBOARD_LL
)。在窗口管理器决定哪个程序将接收消息之前调度低级别挂钩。因此,没有“按下键的程序的名称”,因为窗口管理器尚未决定按键将被传送到哪个程序。 (您可以通过调用GetForegroundWindow
来尝试猜测。)
(只是好奇:你试图用键盘钩解决的最终问题是什么?也许有更好的方法。我希望你不是在写一个键盘记录器。)