定期更改标签文本属性
本文关键字:文本 属性 标签 | 更新日期: 2023-09-27 18:24:53
我有一个标签。我需要每3秒钟更改一次文本属性。请让我知道怎么做。我尝试使用定时器,但我的应用程序正在进入无限循环。我不希望发生这种事/任何帮助都将不胜感激!
timer1.Interval = 5000;
timer1.Enabled = true;
timer1.Tick += new System.EventHandler (OnTimerEvent);
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
refreshStatusBar();
}
在类构造函数中,需要初始化Label
和.NETFramework的Timer
组件的初始文本。
timer.Tick += new EventHandler(timer_Tick);
timer.Interval = (1000) * (3); // Timer will tick every 3 seconds
timer.Enabled = true;
timer.Start();
label.Text = DateTime.Now.ToString(); // initial label text.
然后在计时器的tick处理程序中,更新Label
的text属性。
private void timer_Tick(object sender, ElapsedEventArgs e)
{
label.Text = DateTime.Now.ToString(); // update text ...
}
您应该使用线程,当您想停止调用您的线程时。Abort();
更新:同步上下文方法:
System.Threading.SynchronizationContext sync;
private void Form1_Load(object sender, System.EventArgs e)
{
sync = SynchronizationContext.Current;
System.Windows.Forms.Timer tm = new System.Windows.Forms.Timer { Interval = 1000 };
tm.Tick += tm_Tick;
tm.Start();
}
//Handles tm.Tick
private void tm_Tick(object sender, System.EventArgs e)
{
sync.Post(dopost, DateAndTime.Now.ToString());
}
public void dopost(string txt)
{
Label1.Text = txt;
}