Search code examples
c#winformstimer

My Timer is not reset when click on reset button C#


initialize the components

System.Timers.Timer t; int 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. But when I start the timer and stop it, it doesn't get reset to 00.00.00

Method of 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();
        

Solution

  • 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. This will also be much more accurate since timers do not guarantee any particular tick-frequency.