控制台应用程序中的倒数计时器 [英] Countdown timer in console Application

查看:65
本文介绍了控制台应用程序中的倒数计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制台应用程序,我想创建一个倒数计时器。这是我尝试过的:

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.

推荐答案

我知道有两种方法可以做您想做的事

There are two ways i know of doing what you want

1)使用 Console.SetCursorPosition(); 。当您确定超过计时器的字符数时,此方法适用。

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

2)使用 Console.CursorLeft 。这适用于所有情况。

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

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

这篇关于控制台应用程序中的倒数计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆