C#GUI在以相同形式执行另一项任务时创建运行时钟
窗体打开时,如何运行时钟 我正在使用以下代码:C#GUI在以相同形式执行另一项任务时创建运行时钟,c#,multithreading,user-interface,clock,C#,Multithreading,User Interface,Clock,窗体打开时,如何运行时钟 我正在使用以下代码: DateTime present = DateTime.Now; label1.Text = present.Hour.ToString()+ present.Minute.ToString() + present.Second.ToString(); 打开表单时,我需要一个正在运行的时钟,并且应该能够在时钟运行时单击其他对象。您需要创建System.Threading.Timer对象,并在其勾号事件上更新标签文本。而且这样做更正确 D
DateTime present = DateTime.Now;
label1.Text = present.Hour.ToString()+ present.Minute.ToString() + present.Second.ToString();
打开表单时,我需要一个正在运行的时钟,并且应该能够在时钟运行时单击其他对象。您需要创建System.Threading.Timer对象,并在其勾号事件上更新标签文本。而且这样做更正确
DateTime.Now.ToString("hhMMss");
或
而不是几个.ToString()调用
结果代码是这样的
new System.Threading.Timer((state) => { BeginInvoke((Action)delegate() { label1.Text = DateTime.Now.ToShortTimeString(); }); }, null, 1000, 1000);
您可以尝试使用类
dispatchermer
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);
到目前为止,您尝试了什么?您在尝试时遇到了什么问题?请详细解释问题。对不起,我刚刚开始学习,对c#中的函数不太了解。请检查我的第二种方法。也许它符合您想要尝试的内容。@blacai您的两种解决方案在WPF项目中都是可以接受的。我的是WinForms。是的,你是对的,但他应该将所选的一个标记为解决方案。
new System.Threading.Timer((state) =>
{
Action action = () => timer_label.Content = DateTime.Now.ToString("hh:MM:ss");
Dispatcher.BeginInvoke(action);
}, null, 1000, 1000);