简体   繁体   English

尝试不阻塞地读取键盘输入(Windows,C ++)

[英]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. 我正在尝试编写一个Windows控制台应用程序(使用g ++编译的C ++),它将在循环中执行一系列指令,直到完成OR,直到按下ctrl-z(或其他一些按键)。 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. 如果我按下一个键,它会被回显,应用程序会等待,直到我按Enter继续。 With the value 26, it doesn't execute the intended code. 值为26时,它不执行预期的代码。 If I use something like 65 for the value to catch, it will reroute execution if I press A then Enter afterward. 如果我使用类似65的值来捕获值,那么如果我按A然后按Enter键将重新路由执行。

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? ..之后无需按Enter键?

尝试使用ReadConsoleInput以避免cooked模式,并使用GetNumberOfConsoleInputEvents来避免阻塞。

If G++ supports conio.h then you could do something like this: 如果G ++支持conio.h,那么你可以这样做:

#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. 这个链接可能会为您解释一些事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM