0

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

Yksisarvinen
  • 18,008
  • 2
  • 24
  • 52
platinoob_
  • 151
  • 1
  • 11
  • Added [tag:windows] tag, since `conio.h` is a MS-DOS library. Feel free to revert it if it's incorrect. – Yksisarvinen Dec 11 '20 at 11:03
  • If it indeed is windows, then https://stackoverflow.com/questions/2067893/c-console-keyboard-events or is the question actually about DOS? –  Dec 11 '20 at 11:05
  • @Yksisarvinen, I actually do code in Windows in Visual Studio 2019 but I am not doing a windows program, I don't use WinAPI, I think is crossplatform, also instead of `getch()` I use `_getch()` bcs otherwise I get errors – platinoob_ Dec 11 '20 at 11:06
  • Cross-platform C++ only has line-based character I/O (conio.h is not a standard header). Even getting individual characters without having to press enter each time is platform-dependent. Let alone key events that would allow you to recognize simultaneous key presses. So... pick a platform I guess? –  Dec 11 '20 at 11:15

1 Answers1

2

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...

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252