Listen for key press in .NET console app

karlstackoverflow picture karlstackoverflow · May 5, 2011 · Viewed 305.3k times · Source

How can I continue to run my console application until a key press (like Esc is pressed?)

I'm assuming its wrapped around a while loop. I don't like ReadKey as it blocks operation and asks for a key, rather than just continue and listen for the key press.

How can this be done?

Answer

Jeff Sternal picture Jeff Sternal · May 5, 2011

Use Console.KeyAvailable so that you only call ReadKey when you know it won't block:

Console.WriteLine("Press ESC to stop");
do {
    while (! Console.KeyAvailable) {
        // Do something
   }       
} while (Console.ReadKey(true).Key != ConsoleKey.Escape);