繁体   English   中英

按下键时从do退出(c#)

[英]exit from a do while when a key is pressed (c#)

我正在编写代码,在显示屏上显示一系列字符。 我希望当按下某个键(任何键)时,程序会从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);

我相信您可以使用Console.KeyAvailable处理这种情况。 要使其工作,请更改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);

我认为这应该做的

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM