Home > Back-end >  How do I stop a while loop when ANY keystroke is registered in c#
How do I stop a while loop when ANY keystroke is registered in c#

Time:04-08

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;

CodePudding user response:

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
}       

CodePudding user response:

I'm not so sure if I understand the question rigth, but here the code that would print the msg until any key would be pressed.

while (!Console.KeyAvailable)
{
    Console.WriteLine("\nWAKE UP."); //repeats forever until
    if (Console.KeyAvailable)
    {
        break; //Stop the loop after a key as been pressed
    }
}
  • Related