非阻塞ReadConsoleInput [英] Non-blocking ReadConsoleInput
问题描述
我正在编写一个与鼠标交互的Win32控制台应用程序.我正在使用ReadConsoleInput
来像这样获得相对于窗口的鼠标移动.这是我的问题的简化版本:
I'm writing a Win32 console application that interacts with the mouse. I'm using ReadConsoleInput
to get the window-relative mouse movements like so. Here's a simplified version of my problem:
int main(void)
{
HANDLE hStdin;
DWORD cNumRead;
INPUT_RECORD irInBuf[128];
hStdin = GetStdHandle(STD_INPUT_HANDLE);
SetConsoleMode(hStdin, ENABLE_WINDOW_INPUT | ENABLE_MOUSE_INPUT | ENABLE_PROCESSED_INPUT);
while (1)
{
mouse_position_changed = 0;
ReadConsoleInput(hStdin, irInBuf, 128, &cNumRead);
/* input handler here: changes the cursor position if the mouse position changed;
clears screen if mouse position changed;
sets mouse_position_changed (self-explanatory).
(this part of the code is irrelevant to the quesiton at hand) */
if (!mouse_position_changed)
putchar('0');
}
}
(我已经删除了包括错误检查在内的大部分代码.这是我正在做的一个简单的,精简的版本;它的规模比使0远离游标要大得多.)
无论何时移动鼠标,我都希望清除屏幕并将光标设置为鼠标坐标.这部分正在工作.
I want the screen to be cleared and the cursor set to the mouse coordinates whenever the mouse is moved. This part is working.
我希望0
.这将使0远离鼠标光标.这不起作用,因为 ReadConsoleInput
将阻塞,直到接收到输入为止.
I want 0
to be printed the screen whenever the mouse is not moved. This will have the effect of 0's running away from the mouse cursor. This is not working, because ReadConsoleInput
will block until it receives input.
在接收到更多输入之前,不打印0
.除非用户不断按下键盘,否则不会打印任何内容,因为每当鼠标移动时,屏幕都会被清除.
The 0
is not printed until more input is received. Unless the user continually hits the keyboard, nothing is printed because whenever the mouse is moved, the screen is cleared.
即使没有输入,我也希望循环继续进行. ReadConsoleInput
等待读取输入,这意味着循环将暂停直到按下键盘或移动鼠标为止.
I would like the loop to continue even when no input is present. ReadConsoleInput
waits for input to be read, which means that the loop will pause until the keyboard is hit, or the mouse is moved.
我正在寻找ReadConsoleInput
的替代品,或使其成为非阻塞性的方式.
I'm looking for an alternative to ReadConsoleInput
, or a way to make it non-blocking.
推荐答案
GetNumberOfConsoleInputEvents 确定是否存在控制台输入.您可以使用 PeekConsoleInput .
This is all documented in ReadConsoleInput. You can determine if there is a console input with GetNumberOfConsoleInputEvents. And you are able to to determine the type of console input events with PeekConsoleInput.
因此,仅需 GetNumberOfConsoleInputEvents .
您还可以将 WaitForSingleObject 与控制台句柄一起使用等待下一个可用输入. ReadConsoleInput
You can also use WaitForSingleObject with the console handle to wait for a next available input. This is also documented in ReadConsoleInput
这篇关于非阻塞ReadConsoleInput的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!