Non-blocking ReadConsoleInput

核能气质少年 提交于 2019-12-02 17:44:06

问题


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');
    }
}

(I've removed most of the code including error checks. This is a simple, watered-down version of what I'm doing; it's much larger-scale than making 0's run away from the cursor.)

I want the screen to be cleared and the cursor set to the mouse coordinates whenever the mouse is moved. This part is working.

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.

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.

The problem

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.

I'm looking for an alternative to ReadConsoleInput, or a way to make it non-blocking.


回答1:


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.

So GetNumberOfConsoleInputEvents is all you need.

You can also use WaitForSingleObject with the console handle to wait for a next available input. This is also documented in ReadConsoleInput



来源:https://stackoverflow.com/questions/46658472/non-blocking-readconsoleinput

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!