如何在控制台应用程序中不断更新时钟?

时间:2017-06-21 18:11:27

标签: visual-studio console clock

com我正在为我的编程考试制作一个项目,这将是一个简单的考试,因此我只需要创建一个简单的基本控制台应用程序。但是,即使它很简单,我真的想要加强它。 我已经制作了一个简单的时钟:

        static public void clock()
    {
        Console.SetCursorPosition(0, 0);
        Console.WriteLine("{0:D} {0:t}", DateTime.Now);
        Console.WriteLine("");
    }

我在程序中使用名称" clock;"如下所示:

                        Console.Clear();
                    clock();
                    Console.WriteLine("┌───────────────────────────────────┐");
                    Console.WriteLine("|      Welcome to the Festival      |");
                    Console.WriteLine("└───────────────────────────────────┘");

是否可以为时钟添加秒数,并使其连续更新,并以简单的方式执行此操作?新手程序员可以解释的方式,因为我需要这样做。 谢谢!

2 个答案:

答案 0 :(得分:0)

要在时间输出中包含秒数,您可以使用

Console.WriteLine("{0:D} {0:T}", DateTime.Now);

要更新时间,您可以使用System.Timer,或者如果您想要快速简单的东西(虽然有点hacky),您可以使用带System.Threading.Sleep(500)的循环并调用其中的clock方法。当然,这将永远运行(或直到你关闭命令窗口)。

答案 1 :(得分:0)

这绝对不是万无一失的,因为没有“简单”的方法可以正确地做到这一点......但它可能适用于您的目的:

    static void Main(string[] args)
    {
        Task.Run(() => {
            while (true)
            {
                // save the current cursor position
                int x = Console.CursorLeft;
                int y = Console.CursorTop;

                // update the date/time
                Console.SetCursorPosition(0, 0);
                Console.Write(DateTime.Now.ToString("dddd, MMMM d, yyyy hh:mm:ss"));

                // put the cursor back where it was
                Console.SetCursorPosition(x, y);

                // what one second before updating the clock again
                System.Threading.Thread.Sleep(1000);
            }
        });

        Console.SetCursorPosition(0, 2);
        Console.WriteLine("┌───────────────────────────────────┐");
        Console.WriteLine("|      Welcome to the Festival      |");
        Console.WriteLine("└───────────────────────────────────┘");

        Console.WriteLine("");
        Console.Write("Please enter your name: ");
        string name = Console.ReadLine();
        Console.WriteLine("Hello {0}!", name);

        Console.WriteLine("");
        Console.Write("Press Enter to Quit...");
        Console.ReadKey();
    }
相关问题