Countdown timer in console Application [duplicate]

☆樱花仙子☆ 提交于 2019-11-28 03:38:44

问题


This question already has an answer here:

  • How can I update the current line in a C# Windows Console App? 16 answers

I have a console application and I want to create a countdown timer. This is what I have tried:

    static void Main(string[] args)
    {
        for (int a = 10; a >= 0; a--)
        {
            Console.Write("Generating Preview in {0}", a);
            System.Threading.Thread.Sleep(1000);
            Console.Clear();
        }
    }

This code works in some situations. However, the problem is that it clears the entire console window and cannot be used when there are some characters above the timer.


回答1:


There are two ways i know of doing what you want

1) Use Console.SetCursorPosition();. This is applicable when you are sure of the amount of characters that will be above the timer.

2) Use Console.CursorLeft. This is applicable in all cases.

Code Examples

static void Main(string[] args)
{
   for (int a = 10; a >= 0; a--)
   {
      Console.SetCursorPosition(0,2);
      Console.Write("Generating Preview in {0} ", a);  // Override complete previous contents
      System.Threading.Thread.Sleep(1000);
   }
}

static void Main(string[] args)
{
   Console.Write("Generating Preview in ");
   for (int a = 10; a >= 0; a--)
   {
      Console.CursorLeft = 22;
      Console.Write("{0} ", a );    // Add space to make sure to override previous contents
      System.Threading.Thread.Sleep(1000);
   }
}



回答2:


If you print "\r" to the console the cursor goes back to the beginning of the current line, so this works:

for (int a = 10; a >= 0; a--)
{
    Console.Write("\rGenerating Preview in {0:00}", a);
    System.Threading.Thread.Sleep(1000);
} 



回答3:


One easy trick you can use is to place a \r in your string to return it the cursor to the beginning of the current line:

static void Main(string[] args)
{
    Console.WriteLine("This text stays here");
    for (int a = 10; a >= 0; a--)
    {
        Console.Write("\rGenerating Preview in {0}", a);
        System.Threading.Thread.Sleep(1000);
    }
}



回答4:


Console.SetCursorPosition and related is what you probably looking for. Get current position and set it again back aster every Write/WriteLine call.

Something like:

var origRow = Console.CursorTop;
for (int a = 10; a >= 0; a--)
{
    Console.SetCursorPosition(0, origRow);
    Console.Write("Generating Preview in {0}", a);
    System.Threading.Thread.Sleep(1000);
}
Console.SetCursorPosition(0, origRow);
Console.Write("Generating Preview done.....");


来源:https://stackoverflow.com/questions/18004902/countdown-timer-in-console-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!