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

Trying to read keyboard input without blocking (Windows, C++)(尝试在不阻塞的情况下读取键盘输入(Windows、C++))

本文介绍了尝试在不阻塞的情况下读取键盘输入(Windows、C++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

如果我按下一个键,它会被回显,并且应用程序会一直等到我按下 Enter 键才能继续.值为 26 时,它不会执行预期的代码.如果我使用 65 之类的值作为要捕获的值,如果我按 A 然后按 Enter,它将重新路由执行.

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 键?

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?

推荐答案

试试 ReadConsoleInput 避免熟模式,和 GetNumberOfConsoleInputEvents 避免阻塞.

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

这篇关于尝试在不阻塞的情况下读取键盘输入(Windows、C++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:尝试在不阻塞的情况下读取键盘输入(Windows、C++)

基础教程推荐