Dutton

Non-blocking keyboard input in C#

I know this one is pretty noddy, but these posts are as much a way of me storing code snippets I might need quickly in the future as any form of 'public service' so I'll post it anyway.

I quite frequently want to capture key presses in my apps, and to do this I use Console.ReadKey which returns a nice ConsoleKeyInfo object to tell me what's just been pressed. The problem is this call blocks until a key has been pressed and sometimes I don't want to block out the main execution thread or have to create a separate thread *just* to handle the keyboard input.

This is where Console's KeyAvailable property comes in.  It returns true if there is a key press available in the input stream without blocking allowing you to do something like:

while (true)
{
    if (Console.KeyAvailable)
    {
        ConsoleKeyInfo key = Console.ReadKey(true);
        switch (key.Key)
        {
            case ConsoleKey.F1:
                Console.WriteLine("You pressed F1!");
                break;
            default:
                break;
        }
    }
    // Do something more useful
}

Share this: