'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 1:[1]
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
}
Solution 2:[2]
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
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | John V |
| Solution 2 | Ramil Aliyev |
