我想捕获用户键盘输入以对键盘媒体键做出良好反应:播放/暂停,尤其是下一个和上一个。我尝试将 SetWindowsHookEx 与低级 WH_KEYBOARD_LL 参数一起使用,以确保我可以从这个 WINAPI 函数中获得最大的责任,但我一无所获。如果我在钩子回调中设置断点,当我按下常规键(例如字母或 F 修饰符)时,调试器会在任何键盘事件上停止,但当我按下某个媒体键(例如 Play/Payse)时它永远不会停止。我尝试下载演示 SetWindowsHookEx 用法的演示应用程序,但没有一个适用于 MM 键。我也读过这个相关的问题,但里面没有答案。
我用这段代码来设置钩子:
private const int WH_KEYBOARD_LL = 13;
private const int WM_KEYUP = 0x0101;
private static LowLevelKeyboardProc _proc = HookCallback;
private static IntPtr _hookID = IntPtr.Zero;
public static IntPtr SetHook()
{
using (var curProcess = Process.GetCurrentProcess())
{
using (var curModule = curProcess.MainModule)
{
return SetWindowsHookEx(WH_KEYBOARD_LL, _proc, GetModuleHandle(curModule.ModuleName), 0);
}
}
}
public static void UnsetHook()
{
UnhookWindowsHookEx(_hookID);
}
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_KEYUP)
{
int vkCode = Marshal.ReadInt32(lParam);
Debug.WriteLine((Keys)vkCode);
}
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);
我找到了RegisterHotKey
对我的任务有帮助的信息,但由于我也想对常规密钥做出反应,因此与一个 API 成员一起处理所有常规密钥和 MM 密钥会很舒服。这是死的方法还是我错过了什么?