尝试在不阻塞的情况下读取键盘输入(Windows、C++)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2654504/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 14:17:37  来源:igfitidea点击:

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

c++windowskeyboard

提问by chaosTechnician

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?):

我正在尝试编写一个 Windows 控制台应用程序(在 C++ 中使用 g++ 编译),它将在循环中执行一系列指令,直到完成或直到按下 ctrl-z(或其他一些按键)。我目前用来捕获它的代码不起作用(否则我不会问,对吧?):

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.

如果我按下一个键,它会被回显,并且应用程序会一直等到我按下 Enter 键才能继续。值为 26 时,它不会执行预期的代码。如果我使用类似 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 键?

采纳答案by Ben Voigt

Try ReadConsoleInputto avoid cooked mode, and GetNumberOfConsoleInputEventsto avoid blocking.

尝试ReadConsoleInput以避免熟模式,并尝试GetNumberOfConsoleInputEvents以避免阻塞。

回答by Ben Voigt

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.

这个链接可能会为你解释更多。