Reputation: 3
I'm making a code where a series of characters are shown on the display. And I want that when a key is pressed (Any key) the program exits from the do while.
do{
Console.SetCursorPosition(Console.WindowWidth/2-2,3);
switch(fotograma++%4)
{
case 0 :
Console.Write("|");
break;
case 1 :
Console.Write("/");
break;
case 2 :
Console.Write("-");
break;
case 3 :
Console.Write("\\");
break;
}
System.Threading.Thread.Sleep(50);
}while(true);
Upvotes: 0
Views: 1048
Reputation: 93
I think this should do the job
Console.WriteLine("Press any key to stop");
do {
while (! Console.KeyAvailable) {
// Do something
}
} while (Console.ReadKey(true).Key != ConsoleKey.Escape);
Upvotes: 1
Reputation: 76
I believe you can use Console.KeyAvailable to handle this scenario. To make it work, change your while loop to look like this:
do{
Console.SetCursorPosition(Console.WindowWidth/2-2,3);
switch(fotograma++%4)
{
case 0 :
Console.Write("|");
break;
case 1 :
Console.Write("/");
break;
case 2 :
Console.Write("-");
break;
case 3 :
Console.Write("\\");
break;
}
System.Threading.Thread.Sleep(50);
}while(!Console.KeyAvailable);
Upvotes: 3