[英]C++ How do I make a program detect my keystrokes globally?
I'm making a program and I want it to detect whenever I press F6 and then call an if statement. 我正在编写一个程序,希望我在按F6键并随后调用if语句时进行检测。 This should work globally, not just when I'm focused on my program.
这应该在全球范围内起作用,而不仅仅是在我专注于我的程序时。 How can I do that?
我怎样才能做到这一点?
Since you're on Windows, you can set up a keyboard hook using SetWindowsHookEx
with WH_KEYBOARD
or WH_KEYBOARD_LL
. 由于您使用的是Windows,因此可以使用带有
WH_KEYBOARD
或WH_KEYBOARD_LL
SetWindowsHookEx
来设置键盘挂钩。 Then process keypresses in your matching KeyboardProc or LowLevelKeyboardProc function, and filter out any F6 presses. 然后在匹配的KeyboardProc或LowLevelKeyboardProc函数中处理按键,并过滤掉所有F6按键。 Make sure you call
CallNextHookEx
for any non-F6 keypress, since failing to call CallNextHookEx
will "eat" the keyboard message. 请确保你调用
CallNextHookEx
为任何非F6按键,因为没有调用CallNextHookEx
将“吃”的键盘消息。
You'll want to do this in a DLL; 您将需要在DLL中执行此操作; you'll need both 32-bit and 64-bit versions of the DLL, since 32-bit apps can only be injected with a 32-bit DLL and 64-bit apps can only be injected with a 64-bit DLL.
您将需要DLL的32位和64位版本,因为32位应用程序只能注入32位DLL,而64位应用程序只能注入64位DLL。
You could also try something based around RegisterHotKey
. 您也可以尝试基于
RegisterHotKey
。 This is somewhat safer than a hook, although if another application calls RegisterHotKey
and specifies F6 before yours does, you won't be able to register the hotkey. 这比钩子更安全,尽管如果另一个应用程序调用
RegisterHotKey
并在您的应用程序之前指定F6,则您将无法注册该热键。
Since you don't want any extra modifiers on your hotkey, the call would look something like this: 由于您不希望热键上有任何额外的修饰符,因此该调用看起来像这样:
RegisterHotKey(myHwnd, 1, 0, VK_F6);
where myHwnd
is the HWND of your window (or optionally nullptr
if you'd rather process the WM_HOTKEY
messages in your message loop), 1
is the identifier of the hotkey and can be whatever int you like, 0
specifies no modifier keys (Ctrl, Alt, Windows key, etc.), and VK_F6
is the virtual keycode for F6. 其中
myHwnd
是窗口的HWND(如果希望在消息循环中处理WM_HOTKEY
消息,则可以选择nullptr
), 1
是热键的标识符,可以是您喜欢的int, 0
指定修饰键(Ctrl, Alt,Windows键等),而VK_F6
是F6的虚拟键码。
The function you need is RegisterHotKey(VK_F6 ...)
, and it will cause WM_HOTKEY
to be sent. 您需要的功能是
RegisterHotKey(VK_F6 ...)
,它将导致发送WM_HOTKEY
。 You'll therefore need a Windows message loop. 因此,您将需要Windows消息循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.