Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timer not getting reset in C#

Tags:

c#

winforms

timer

Hi I am getting problem in resetting the Timer control in C# win form application.

I am developing a simple countdown timer.

Sample

When I click on start it starts countdown from 59 seconds. I need the timer should restart from beginning when I click on Start button.

code on timer1_tick

if (hours==0 && minutes==0 && seconds==0)
{
    hours = 0;
    minutes = 1;
    seconds = 0;
}
else
{
    if (seconds < 1)
    {
        seconds = 59;
        if (minutes == 0)
        {
            minutes = 59;
            if (hours != 0)
               hours -= 1;
        }
        else
        {
            minutes -= 1;
        }
    }
    else
        seconds -= 1;

    lblTime.Text = hours + @":" + minutes + @":" + seconds;
}

and code on btnStart_Click

timer1.Enabled = false;
timer1.Enabled = true;

Here I am trying to restart the timer1by enabling and disabling the control but it's not working. I also tried to check with

timer1.Stop();
timer1.Start();

but it starts again from where it was stooped.

How can we resolve this?

like image 262
Ashok Avatar asked Dec 20 '13 13:12

Ashok


2 Answers

I suggest you to store DateTime value which will represent target time (current time plus one minute):

// or DateTime.Now.AddMinutes(1)
targetTime = DateTime.Now.Add(TimeSpan.FromMinutes(1));

Then on each timer tick subtract current time from target time and display TimeSpan you will have:

var span = targetTime - DateTime.Now;

if (span.TotalSeconds > 0)
   lblTime.Text = span.ToString(@"hh\:mm\:ss");
else
   lblTime.Text = "Bingo!";

Thus you will not need to store and maintain three variables for hours, minutes and seconds.

like image 131
Sergey Berezovskiy Avatar answered Sep 28 '22 06:09

Sergey Berezovskiy


Use

timer1.Dispose();
timer1 = new System.Windows.Forms.Timer();

To get rid of the object and re-initialise.

I hope this helps.

like image 31
MoonKnight Avatar answered Sep 28 '22 06:09

MoonKnight