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:

Tagged , , , , , ,

12 thoughts on “Non-blocking keyboard input in C#

  1. Dish says:

    Thank you for your code.

  2. Adam says:

    Thank you! I was trying to understand how to use KeyAvailable in combination with ReadKey and this cleared it right up. Thanks

  3. Tulasi says:

    Great code …..Thank you

  4. Gbozoki says:

    Unfortunately this prevents the input/output from being redirected.

  5. cherry says:

    hey, i copy and paste the codes.. but the words “KeyAvailable”, “ConsoleKeyInfo” and “ReadKey” have errors.. I want to ask whether is it because you must import something or add reference?

  6. richard says:

    Hi Cherry,
    “KeyAvailable”, “ConsoleKeyInfo” and “ReadKey” are all in the System namespace in the mscorlib assembly but you would normally be using that anyway in your code. Could you paste some example code here for me to see where your problem is?

  7. No says:

    Doesn’t work

  8. Daniel Byrne says:

    Thank you. Works well.

  9. Someone says:

    This works great for me. Thank you.

    Remember if this code “appears” blocking it is likely because you copy/pasted the infinite while() loop. It has nothing to do with if (Console.KeyAvailable) {} itself.

  10. Mystyc Cheez says:

    This was incredibly helpful, thank you! 😀

Leave a Reply

%d bloggers like this: