c++ - 在不禁用其 key 的情况下注册全局热键

标签 c++ winapi hotkeys

我想制作一个可以捕获键盘事件的程序,即使它在任何时候都没有激活。 Hooks 太复杂了,我必须做所有事情才能让它工作(制作 DLL、读取它等等),所以我决定继续使用热键。

但是现在我遇到了一个问题。注册热键会禁用键盘上的键,因此我只能将键发送到程序,而不能在任何其他程序(例如记事本)上键入。

这是我的代码:

#include <iostream>
#include <windows.h>
using namespace std;

int main(int argc, char* argv[]) {
    RegisterHotKey(NULL, 1, NULL, 0x41); //Register A
    MSG msg = {0};

    while (GetMessageA(&msg, NULL, 0, 0) != 0) {
        if (msg.message == WM_HOTKEY) {
            cout << "A"; //Print A if I pressed it
        }
    }

    UnregisterHotKey(NULL, 1);
    return 0;
}

// and now I can't type A's

这个问题有什么简单的解决办法吗? 谢谢

最佳答案

我会让您的程序模拟一次与您实际执行的按键相同的按键。这意味着:

  1. 你按“A”。
  2. 程序获得了“A”。
  3. 程序模拟按键。

这很简单。唯一的问题是您的程序也会捕捉到模拟按键。为避免这种情况,您可以执行以下操作:

  1. 你按“A”。
  2. 程序获得了“A”。
  3. 程序注销热键。
  4. 程序模拟按键。
  5. (该程序不(!)捕获“A”。)
  6. 程序再次注册热键。

这就是整个循环。

现在,要模拟按键,您需要添加一些额外的代码。看看这个:

#include <iostream>
#include <windows.h>
using namespace std;

int main(int argc, char* argv[]) {
    RegisterHotKey(NULL, 1, 0, 0x41);            //Register A; Third argument should also be "0" instead of "NULL", so it is not seen as pointer argument
    MSG msg = {0};
    INPUT ip;
    ip.type = INPUT_KEYBOARD;
    ip.ki.wScan = 0;
    ip.ki.time = 0;
    ip.ki.dwExtraInfo = 0;
    ip.ki.wVk = 0x41;                            //The key to be pressed is A.

    while (GetMessage(&msg, NULL, 0, 0) != 0) {
        if (msg.message == WM_HOTKEY) {
            UnregisterHotKey(NULL, 1);           //Prevents the loop from caring about the following
            ip.ki.dwFlags = 0;                   //Prepares key down
            SendInput(1, &ip, sizeof(INPUT));    //Key down
            ip.ki.dwFlags = KEYEVENTF_KEYUP;     //Prepares key up
            SendInput(1, &ip, sizeof(INPUT));    //Key up
            cout << "A";                         //Print A if I pressed it
            RegisterHotKey(NULL, 1, 0, 0x41);    //you know...
        }
    }

    UnregisterHotKey(NULL, 1);
    return 0;
}

我试过了,我想它工作正常。 希望我能帮上忙 ;)

关于c++ - 在不禁用其 key 的情况下注册全局热键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11006623/

相关文章:

c++ - 如何声明对经过模板参数推导的类型的右值引用?

winapi - VB6 在使用事件 Windows 消息 Hook 进行调试时退出

winapi - 在 Win32 中如何获取 CPU 周期数?

keyboard-shortcuts - AutoHotkey - 使用有限的按键集最大化键盘组合的数量

c++ - 在二叉树解决方案中删除

c++ - 带有 boost::throw_exception 问题的 PCL 构建

c++ - 在 C++ 中读取包含大量列和行的 csv 文件的最快方法

python:使用windows api使用ttf字体呈现文本

java - 在 Windows/Linux/Mac 上的 Java 程序中对全局热键使用react?

python - 谷歌浏览器 - 如何激活谷歌浏览器并切换到特定的标签窗口?