Trying to read keyboard input without blocking (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++)
- 从python回调到c++的选项 2022-11-16
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- C++ 协变模板 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 近似搜索的工作原理 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 静态初始化顺序失败 2022-01-01