[英]My Timer is not reset when click on reset button C#
initialize the components初始化组件
System.Timers.Timer t; System.Timers.Timer t; int h, m, s;
整数 h, m, s;
I want to reset
the timer when I click on the reset
button and turn it to 00.00.00
, but when I try to reset
it with the code
the timer stops.当我单击
reset
按钮并将其设置为00.00.00
时,我想reset
计时器,但是当我尝试使用code
reset
它时,计时器停止。 But when I start the timer and stop it, it doesn't get reset to 00.00.00
但是当我启动计时器并停止它时,它不会重置为
00.00.00
Method of timer
timer
的方法
private void OnTimeEvent(object sender, ElapsedEventArgs e)
{
Invoke(new Action(() =>
{
s += 1;
if (s == 60)
{
s = 0;
m += 1;
}
if (m == 60)
{
m = 0;
h += 1;
}
lbltime.Text = string.Format("{0}:{1}:{2}", h.ToString().PadLeft(2, '0'),
m.ToString().PadLeft(2, '0'), s.ToString().PadLeft(2, '0'));
}));
}
Form load event表单加载事件
t = new System.Timers.Timer();
t.Interval = 1000;
t.Elapsed += OnTimeEvent;
t.Start();
Reset Button Which is not working
t.Dispose();
Try something like this:尝试这样的事情:
Stopwatch stopwatch = Stopwatch.StartNew();
private void OnTimeEvent(object sender, ElapsedEventArgs e)
{
Invoke(new Action(() => lbltime.Text = stopwatch.Elapsed.ToString("hh:mm:ss")));
}
private void OnResetButtonClick(object sender, EventArgs e)
{
stopwatch.Restart();
}
This uses a stopwatch to measure the time, and a timer to update the label from the stopwatch.这使用秒表测量时间,并使用计时器从秒表更新 label。 This will also be much more accurate since timers do not guarantee any particular tick-frequency.
这也将更加准确,因为计时器不保证任何特定的滴答频率。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.