Search code examples
c#while-loopuser-inputkeypresskeystroke

How do I stop a while loop when ANY keystroke is registered in c#


I've been searching around for an answer but all I can find are solutions for if a user inputs a specific key. I want ANY key that is pressed to halt the repeating message in the loop. So if no key is pressed, the loop's message keeps going.

do
{
    while (! Console.KeyAvailable) 
    {
        Console.WriteLine("\nWAKE UP."); //repeats forever until
    }       
} 
while (Console.ReadKey(true).Key != ConsoleKey.Escape); //here the key that stops the loop is Escape

return;

Solution

  • The outer do/while loop is causing your inner loop to repeat until the escape key is pressed. If you remove the do/while loop, you'll get the behavior you're looking for:

    while (!Console.KeyAvailable) 
    {
        Console.WriteLine("\nWAKE UP."); //repeats forever until
    }