0

When I use this code. I click stop it sets the timer to 00:00. But when I click on start again the timer continues counting from where it stops. Is there a way to reset the timer when I click on stop?

   public MainWindow()
        {
            InitializeComponent();

        }

        DispatcherTimer timer = new DispatcherTimer();

        int increment = 0;

        private void Timer()
        {

            timer.Interval = new TimeSpan(0, 0, 0, 1);
            timer.Tick += TimerTicker;

            TimeSpan time = TimeSpan.FromSeconds(increment);
            lblTimer.Content = time.ToString(@"mm\:ss");

        }


        void TimerTicker(object sender, EventArgs e)
        {
            increment++;

            TimeSpan time = TimeSpan.FromSeconds(increment);
            lblTimer.Content = time.ToString(@"mm\:ss");

        }

        private void btnStart_Click(object sender, RoutedEventArgs e)
        {

            timer.Start();

        }

        private void btnStop_Click(object sender, RoutedEventArgs e)
        {
            timer.Stop();

        } 
GizaRex
  • 1
  • 2
  • Call `timer.Stop(); timer.Start();` in btnStart_Click. Calling Start when it's already running is obviously ignored. – Clemens Feb 22 '20 at 12:36
  • Hmm, no, clicking Stop does not set the displayed time to "00:00", it merely stops the timer from firing the Tick event. I'd guess you want to add `increment = 0;` to btnStart. – Hans Passant Feb 22 '20 at 13:16

1 Answers1

0

after you stop timer, reset accumulated value to zero:

private void btnStop_Click(object sender, RoutedEventArgs e)
{
    timer.Stop();
    increment = 0;
} 
ASh
  • 34,632
  • 9
  • 60
  • 82