繁体   English   中英

单击重置按钮 C# 时,我的计时器未重置

[英]My Timer is not reset when click on reset button C#

初始化组件

System.Timers.Timer t; 整数 h, m, s;

当我单击reset按钮并将其设置为00.00.00时,我想reset计时器,但是当我尝试使用code reset它时,计时器停止。 但是当我启动计时器并停止它时,它不会重置为00.00.00

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'));

        }));
}

表单加载事件

        t = new System.Timers.Timer();
        t.Interval = 1000;
        t.Elapsed += OnTimeEvent;
        t.Start();

       Reset Button Which is not working
        t.Dispose();
        

尝试这样的事情:

    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();
    }

这使用秒表测量时间,并使用计时器从秒表更新 label。 这也将更加准确,因为计时器不保证任何特定的滴答频率。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM