[英]exit from a do while when a key is pressed (c#)
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 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);
I believe you can use Console.KeyAvailable to handle this scenario. 我相信您可以使用Console.KeyAvailable处理这种情况。 To make it work, change your while loop to look like this:
要使其工作,请更改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(!Console.KeyAvailable);
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.