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

南楼画角 提交于 2019-12-29 08:45:15

问题


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?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/2654504/trying-to-read-keyboard-input-without-blocking-windows-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!