2017-06-21 56 views
0

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

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

我通过使用名称来引用该方法在程序中“时钟;”如下所示:

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

是否有可能秒添加到时钟,并使其不断更新,并做一个简单的方法?一种新手程序员可以解释的方式,因为我需要这样做。 谢谢!

+2

你的问题将得到改善,并会进行审议如果将代码作为文本直接包含在您的问题中,而不是要求用户访问外部网站,则会有更多人参与。 – hatchet

+0

谢谢你,我重新做了这个问题,用代码片段代替图像。 – Tovleman

回答

0

为了在你的时间输出秒就可以使用

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

要更新时,您可以使用System.Timer,或者如果你想要的东西快速和容易(虽然有点哈克),你可以只需使用一个带有System.Threading.Sleep(500)的循环并调用其中的时钟方法即可。当然,这将永远运行(或直到你关闭命令窗口)。

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(); 
    } 
相关问题