chaosTechnician
chaosTechnician

Reputation: 1700

Trying to read keyboard input without blocking (Windows, C++)

I'm trying to write a Windows console application (in C++ compiled using g++) that will execute a series of instructions in a loop until finished OR until ctrl-z (or some other keystroke) is pressed. The code I'm currently using to catch it isn't working (otherwise I wouldn't be asking, right?):

if(kbhit() && getc(stdin) == 26)
  //The code to execute when ctrl-z is pressed

If I press a key, it is echoed and the application waits until I press Enter to continue on at all. With the value 26, it doesn't execute the intended code. If I use something like 65 for the value to catch, it will reroute execution if I press A then Enter afterward.

Is there a way to passively check for input, throwing it out if it's not what I'm looking for or properly reacting when it is what I'm looking for? ..and without having to press Enter afterward?

Upvotes: 4

Views: 7578

Answers (2)

user113476
user113476

Reputation:

If G++ supports conio.h then you could do something like this:

#include <conio.h>
#include <stdio.h>

void main()
{
    for (;;)
    {
        if (kbhit())
        {
            char c = getch();
            if (c == 0) {
                c = getch(); // get extended code
            } else {
                if (c == 'a') // handle normal codes
                    break;
            }
        }
    }
}

This link may explain things a little more for you.

Upvotes: 2

Ben Voigt
Ben Voigt

Reputation: 283733

Try ReadConsoleInput to avoid cooked mode, and GetNumberOfConsoleInputEvents to avoid blocking.

Upvotes: 4

Related Questions