Win32 - read from stdin with timeout

前端 未结 6 1444
时光取名叫无心
时光取名叫无心 2020-12-06 10:11

I\'m trying to do something which I think should be simple: do a blocking read from standard input, but timing out after a specified interval if no data is available.

<
6条回答
  •  鱼传尺愫
    2020-12-06 11:18

    Using GetStdHandle + WaitForSingleObject works fine. But be sure to set the approriate flags and flush the console buffer as well before entering the loop.

    In short (without error checks)

    std::string inStr;
    DWORD fdwMode, fdwOldMode;
    HANDLE hStdIn = GetStdHandle(STD_INPUT_HANDLE);
    GetConsoleMode(hStdIn, &fdwOldMode);
    // disable mouse and window input
    fdwMode = fdwOldMode ^ ENABLE_MOUSE_INPUT ^ ENABLE_WINDOW_INPUT;
    SetConsoleMode(hStdIn, fdwMode);
    // flush to remove existing events
    FlushConsoleInputBuffer(hStdIn);
    while (!abort)
    {
        if (WaitForSingleObject(hStdIn, 100) == WAIT_OBJECT_0)
        {
             std::getline(std::cin, inStr);
        }
    }
    // restore console mode when exit
    SetConsoleMode(hStdIn, fdwOldMode);
    

提交回复
热议问题