我试图从另一个应用程序中获取用户按下的键,但我能得到的只是在没有键盘条件(大写/小写/按下 shift)的情况下按下的键的位置,我想获取实际的键
我的代码:
private const int WH_KEYBOARD_LL = 13;
private const int WM_KEYDOWN = 0x0100;
private static LowLevelKeyboardProc _proc = HookCallback;
private static IntPtr _hookID = IntPtr.Zero;
private static int enteredChar;
public static int EnteredChar
{
get { return enteredChar; }
}
public static void start()
{
_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)
{
// char letter=(char) Marshal.ReadByte(lParam);
enteredChar = Marshal.ReadInt32(lParam);
Console.WriteLine((Keys)enteredChar);
}
return CallNextHookEx(_hookID, nCode, wParam, lParam);
}
public static int returnKey()
{
return enteredChar;
}