platinoob_
platinoob_

Reputation: 161

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.

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

Upvotes: 0

Views: 989

Answers (1)

Serge Ballesta
Serge Ballesta

Reputation: 148870

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.

So you should directly use the 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...

Upvotes: 2

Related Questions