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

One thought on “Non-blocking Read of Console Input that Works with Visual Studio Test”

  1. Wow that was odd. I just wrote an extremely long comment but after I clicked submit my comment didn’t show up. Grrrr well I’m not writing all that over again. Anyway, just wanted to say superb blog! fecekgaacdcc

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s