如何在窗体打开时运行时钟?当我打开窗体,并应能够在时钟运行的同时点击其他对象C#GUI创建运行时钟,同时执行另一项任务
DateTime present = DateTime.Now;
label1.Text = present.Hour.ToString()+ present.Minute.ToString() + present.Second.ToString();
我想运行时钟:
我使用这个代码。
如何在窗体打开时运行时钟?当我打开窗体,并应能够在时钟运行的同时点击其他对象C#GUI创建运行时钟,同时执行另一项任务
DateTime present = DateTime.Now;
label1.Text = present.Hour.ToString()+ present.Minute.ToString() + present.Second.ToString();
我想运行时钟:
我使用这个代码。
您需要创建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);
您可以用类尝试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);
到目前为止您尝试过什么,以及您尝试过哪些问题?详细解释问题。 – Servy
WinForms? WPF?等 – LarsTech
对不起,我刚刚开始学习和不知道在c# –