如何检测 C++ 中的组合键输入?

How to detect combined key input in C++?

假设您在电脑上玩游戏,使用箭头键或 WASD 移动角色,假设您按住 向上箭头 键/W左箭头键/A一起,如果游戏允许,你的角色会在中间的某处移动,即使你按住两个第一个 other later, while continue to hold the first, none of the 2 will get interrupted and then 忽略.

我知道如何检测用户是否按下了箭头 key/letter,

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

int main() {
    while (1) {
        int ch = getch();
        if (ch == 224) {
            ch = getch();
            switch (ch) {
            case 72: cout << "up\n";    break;
            case 80: cout << "down\n";  break;
            case 77: cout << "right\n"; break;
            case 75: cout << "left\n";  break;
            default: cout << "unknown\n";
            }
        }
        else 
            cout << char(ch) << '\n';
    }
}

但是我找不到方法来做我在这个问题开头提到的事情


感谢任何帮助尝试

即使 conio.h 函数级别相当低,它们也不足以满足您的需求:您不想从控制台缓冲区中提取字符(getch 所做的)但知道一些键的状态(pressed/released)。

所以你应该直接使用WINAPI函数GetKeyState。您的程序将不再 MS/DOS 兼容,但我认为这在 2020 年不是一个真正的问题...