Non-blocking Read of Console Input that Works with Visual Studio Test

I had a console program and wanted to be able to exit that when the user pressed X. I couldn’t just use Console.Read or Console.ReadKey because they block. So I used Console.KeyAvailable to check if the user typed something before reading that input. While that worked great when the program was run from a command prompt, it didn’t work when the program was run using Visual Studio Test, because then there is no real console input. My workaround was to check which type of object Console.In returns. Here is my code:

private static bool CheckExit()
{
    bool retval = false;
    if (Console.In.GetType().FullName != “System.IO.StreamReader+NullStreamReader” && Console.KeyAvailable)
    {
        ConsoleKeyInfo key = Console.ReadKey(true);
        if (key.KeyChar == ‘x’ || key.KeyChar == ‘X’)
            retval = true;
    }
    return retval;
}

Advertisements