How to capture keyboard action without pausing the C++ program?

Asked

Viewed 4,941 times

4

How do I capture a keyboard action without pausing the program? For example:

char tecla;
do{
    scanf("%c", &tecla);
    printf("%c",tecla); 
}while(tecla != '0');

I wanted it to be on a loop, but when you type something on the keyboard you can capture and perform a certain action within the program. The program will run on the terminal, every loop and I will clear the screen and print other things again.

  • handles with interruption. The way to do this depends on the language, your program is to run on desktop?. creates a keyboard interrupt that runs something when a key is pressed. are you using c or c++? so answer I search and complement the answer

  • you can post your code?

2 answers

4


Can’t do this with pure C++ as it depends on the operating system and console used. (Source)

An alternative is to use the function kbhit() available in the library conio.h. It checks if any key has been pressed, so just Chaar the function before scanf. However, it is necessary to pay attention because there are different implementations for Windows and Linux. (Source)

In Windows, you can also use the function ReadConsoleInput to read and empty the input buffer of the console. Note that this function also captures mouse events, so you need to check the type of event received.

One consideration about all this is that, depending on what you want, it is not good to do checks on a loop. This wastes CPU. One approach to solve this is to create new threads to do the "heavy" processing and leave the main thread responsible for reading and writing on the console.

  • 1

    That’s what I thought too, for me it didn’t work, I’m using MAC =\

3

I found in this link my answer

kbhit

char tecla;
do{
if(kbhit()){
    tecla = getch();

    switch(tecla){
        case 'W': //cima
            break;
        case 'S': //baixo
            break;
    }
}
//executo meu programa bazeado na tecla
}while(tecla != '0');

The function kbhit() identifies when a keyboard action occurs, but it is only present in the header <conio.h> which was made exclusively for MS/DOS. So it doesn’t work if you are using a Macosx.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.