非阻塞 ReadConsoleInput

Non-blocking ReadConsoleInput

我正在编写一个与鼠标交互的 Win32 控制台应用程序。我正在使用 ReadConsoleInput 来获得 window 的相对鼠标移动。这是我的问题的简化版本:

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 运行远离光标。)

我希望每次移动鼠标时清屏并将光标设置为鼠标坐标。这部分正在工作

我希望 0 在鼠标 移动时打印屏幕。这将产生 0 运行ning 远离鼠标光标的效果。这 不起作用 ,因为 ReadConsoleInput 将阻塞直到它接收到输入。

在收到更多输入之前,不会打印 0。除非用户不断敲击键盘,否则不会打印任何内容,因为只要移动鼠标,屏幕就会被清除。

问题

即使没有输入,我也希望循环继续。 ReadConsoleInput 等待读取输入,这意味着循环将暂停,直到敲击键盘或移动鼠标。

我正在寻找 ReadConsoleInput 的替代方法,或者寻找一种使其成为非阻塞的方法。

这些都记录在 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 with the console handle to wait for a next available input. This is also documented in ReadConsoleInput