简体   繁体   English

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

[英]How to detect combined key input in C++?

Let's say you play a game on the computer, you move your character with arrow keys or WASD, if, let's say, you press and hold the up arrow key/ W and left arrow key/ A together , if the game allows it, your character will move somewhere in between , even if you press and hold one of the 2 first and the other later , while continue holding the first, none of the 2 will get interrupted and then ignored .假设您在计算机上玩游戏,您使用箭头键或 WASD 移动角色,假设您同时按住向上箭头键/ W向左箭头键/ A 如果游戏允许,您的角色会在两者之间移动,即使您先按住 2 中的一个,然后再按住另一个同时继续按住第一个,这 2 中的任何一个都不会被打断然后被忽略

I know how to detect if the user pressed an arrow 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';
    }
}

but I can't find a way to do what I mentioned at the beginning of this question但我找不到方法来做我在这个问题开头提到的事情


Any attempt to help is appreciated任何帮助的尝试表示赞赏

Even if conio.h function are rather low level, they are not low enough for what you want: you do not want to extract characters from a console buffer (what getch does) but know the state (pressed/released) of some keys.即使conio.h function 级别相当低,它们也不足以满足您的要求:您不想从控制台缓冲区中提取字符( getch所做的),但知道某些键的 state(按下/释放)。

So you should directly use the WINAPI function GetKeyState .所以你应该直接使用 WINAPI function GetKeyState Your program will no longer be MS/DOS compatible, but I do not think that is is a real question in 2020...您的程序将不再与 MS/DOS 兼容,但我认为这在 2020 年不是一个真正的问题......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM