Hi I am getting problem in resetting the Timer control in C# win form application.
I am developing a simple countdown timer.
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 timer1
by 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?
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.
Use
timer1.Dispose();
timer1 = new System.Windows.Forms.Timer();
To get rid of the object and re-initialise.
I hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With