简体   繁体   中英

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{
    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. 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);

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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