Reputation: 1906
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?
Upvotes: 5
Views: 2991
Reputation: 135
if (timer1.Enabled) { timer1.Enabled = false; }
else { minutes = 1; seconds = 0; timer1.Enabled = true; }
if you want reset back to 1 minute, make this into your btnStart_Click
function
note : for your seconds
when it's become 0 it will be increase again to 59 although your minutes
0, you must validate it
if (minutes == 0 && seconds == 0)
{
timer1.Enabled = false;
//this your code to reset variable hours, minutes, and seconds
}
use this function at function timer1_tick()
Upvotes: 1
Reputation: 236328
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.
Upvotes: 4
Reputation: 66509
Where are hours
, minutes
and seconds
defined?
It looks like your btnStart_Click
simply needs to reset those values instead of resetting the timer.
I can't tell from your question what those default values should be though. You say the timer should countdown from 59 seconds, but then I see logic that's resetting minutes to 59 and other logic that decrements the hour (although the hour appears to start at 0 and never increase).
Upvotes: 2
Reputation: 13794
in your btnStart_Click
you should reset your instance variables
hours=minutes=seconds=59
Upvotes: 2
Reputation: 23831
Use
timer1.Dispose();
timer1 = new System.Windows.Forms.Timer();
To get rid of the object and re-initialise.
I hope this helps.
Upvotes: 2