简体   繁体   English

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

[英]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.

相关问题 C#按下键时的注意事项 - C# Notice when a key is pressed 在 wpf c# 中按下 Enter 键时,如何设置标签并将整数值从 TextBox 显示到标签? - How do i set the label and display an integer value from a TextBox to the label when the enter key is pressed in wpf c#? 按下键时C#和Unity3D - C# and Unity3D while key is being pressed C#:如何在文本框的 keydown 事件中禁止按键被无限按下? - C#: How do you disable a key from being pressed indefinetly in textbox's keydown event? (C#) 按下按键时播放声音,再次按下按键时停止 - (C#) Play a sound when the key is pressed and stop it when the key is pressed again 当使用C#在Windows窗体中按Enter键时,如何从动态文本框中提交和检索文本? - How to submit and retrieve text from dynamic textbox when Enter key is pressed in Windows forms using C#? c#控制台-执行某些操作,直到按下键 - c# Console-Do something until key pressed 在 C# 中按下某个键时,UserControl 不会引发 KeyPress 事件 - UserControl not raising a KeyPress event when a key is pressed in C# 按下Backspace键时删除TextBox内容C# - Delete TextBox content when Backspace key is pressed C# 按下键时激活按钮C#Universal App - Activate button when key is pressed C# Universal App
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM