显示每15秒循环一次的计时器
本文关键字:一次 计时器 15秒 循环 显示 | 更新日期: 2023-09-27 18:15:27
我编写了这段代码,但是在屏幕上显示的时间循环和实际经过的时间之间存在延迟。
Timer t = new Timer();
int time = 15;
string timestr;
t.Interval = 1000;
t.Tick += new EventHandler(Time);
void Time(object sender, EventArgs e)
{
if (time == 0)
{ time = 15; }
if (time != 0)
{
time--;
timestr = time.ToString();
label.Text = timestr;
}
}
我的猜测是你偏离了一秒,因为计时器不会触发它的第一个事件,直到达到间隔值。
一个快速的解决方案是在启动事件时自己触发事件:
t.Start();
Time(t, EventArgs.Empty);
我想你应该试试这个。在Time函数结束前添加Application.DoEvents()行。
void Time(object sender, EventArgs e)
{
if (time == 0)
{ time = 15; }
if (time != 0)
{
time--;
timestr = time.ToString();
label.Text = timestr;
}
Application.DoEvents();
}