How can I detect if there is input waiting on stdin on windows?

前端 未结 3 1864
独厮守ぢ
独厮守ぢ 2020-12-17 02:13

I want to detect whether or not there is input waiting on stdin in Windows.

I use the following generic structure on Linux:

fd_set currentSocketSet;         


        
相关标签:
3条回答
  • 2020-12-17 02:29

    As already pointed out, in Windows you have to use GetStdHandle() and the returned handle cannot be mixed with sockets. But luckily, the returned handle can be tested with WaitForSingleObject(), just like many other handles in Windows. Therefere, you could do something like this:

    #include <stdio.h>
    #include <windows.h>
    
    BOOL key_was_pressed(void)
    {
        return (WaitForSingleObject(GetStdHandle(STD_INPUT_HANDLE),0)==WAIT_OBJECT_0);
    }
    
    void wait_for_key_press(void)
    {
        WaitForSingleObject(GetStdHandle(STD_INPUT_HANDLE),INFINITE);
    }
    
    int main()
    {
        if(key_was_pressed())
            printf("Someone pressed a key beforehand\n");
    
        printf("Wait until a key is pressed\n");
    
        wait_for_key_press();
    
        if(key_was_pressed())
            printf("Someone pressed a key\n");
        else
            printf("That can't be happening to me\n");
    
        return 0;
    }
    

    EDIT: Forgot to say that you need to read the characters from the handle in order to key_was_pressed() to return FALSE.

    0 讨论(0)
  • 2020-12-17 02:30

    As stated in the ReadConsoleInput() documentation:

    A process can specify a console input buffer handle in one of the wait functions to determine when there is unread console input. When the input buffer is not empty, the state of a console input buffer handle is signaled.

    To determine the number of unread input records in a console's input buffer, use the GetNumberOfConsoleInputEvents function. To read input records from a console input buffer without affecting the number of unread records, use the PeekConsoleInput function. To discard all unread records in a console's input buffer, use the FlushConsoleInputBuffer function.

    You can use GetStdHandle() to get a handle to STDIN for use in the above functions.

    0 讨论(0)
  • 2020-12-17 02:53

    As you know, Linux != Windows, and you're not going to get the same semantics for a "select()" in both environments.

    You didn't specify whether this is a Windows GUI or console-mode program, either. It makes a difference.

    ... HOWEVER ...

    Two Win32 APIs you might want to look at:

    • GetAsyncKeyState

    • PeekConsoleInput

    'Hope that helps

    PS:

    If this is a console-mode program, you're going to need a window handle. Call GetStdHandle(STD_INPUT_HANDLE) to get it.

    0 讨论(0)
提交回复
热议问题