2014-03-03 34 views
-3

如何在窗体打开时运行时钟?当我打开窗体,并应能够在时钟运行的同时点击其他对象C#GUI创建运行时钟,同时执行另一项任务

DateTime present = DateTime.Now; 

label1.Text = present.Hour.ToString()+ present.Minute.ToString() + present.Second.ToString(); 

我想运行时钟:

我使用这个代码。

+3

到目前为止您尝试过什么,以及您尝试过哪些问题?详细解释问题。 – Servy

+2

WinForms? WPF?等 – LarsTech

+0

对不起,我刚刚开始学习和不知道在c# –

回答

0

您需要创建System.Threading.Timer对象并在其上的Tick事件中更新您的标签文本。此外它更正确的做

DateTime.Now.ToString("hhMMss"); 

DateTime.Now.ToShortTimeString(); 

,而不是几个的ToString()的调用。

结果代码将是类似的东西

new System.Threading.Timer((state) => { BeginInvoke((Action)delegate() { label1.Text = DateTime.Now.ToShortTimeString(); }); }, null, 1000, 1000); 
+0

函数很多检查我的第二种方法。也许它匹配想要你尝试。 – blfuentes

+0

感谢这工作! –

+0

@blacai你的解决方案在WPF项目中都可以接受。我在WinForms中。 –

0

您可以用类尝试DispatcherTimer

DispatcherTimer dpTimer = new DispatcherTimer(); 

    public MainWindow() 
    { 
     InitializeComponent(); 
     dpTimer.Tick += new EventHandler(dpTick); 
     dpTimer.Interval = new TimeSpan(0, 0, 1); 
     dpTimer.Start(); 
    } 

    private void dpTick(object sender, EventArgs e) 
    { 
     DateTime present = DateTime.Now; 
     timer_label.Content = present.Hour.ToString() + present.Minute.ToString() + present.Second.ToString(); 
    } 

如果你想使用定时器,检查该解决方案:

 new System.Threading.Timer((state) => 
     { 
      Action action =() => timer_label.Content = DateTime.Now.ToString("hh:MM:ss"); 
      Dispatcher.BeginInvoke(action); 
     }, null, 1000, 1000);