Introduction
I was once in need of a timer that will only run a specified number of times. I also wanted to know when the timer was done/stopped. Than I started to write a new class inherited from the existing System.Windows.Forms.Timer
.
I have added an example application that utilizes the CountDownTimer
. Initially it runs with 20 times. But you can change the value with the NumericUpDown
control on top, in the middle. The reason why I have 2 Start/Stop buttons is, I used different methods for Start()
/Stop()
and Enabled=true
/false
before. But now it's actually the same thing. It is also possible to set the timer to sleep by pushing the Sleep button, just push it again to wake the timer up again.
Timer class basics
I defined 2 new events Started
and Stopped
. Especially Stopped
is quite useful. To be able to count down, we have to subscribe to the Tick
event from the Timer
base class in the constructor. Every time the event will be fired, I call the function countdown and it will decrement the currentDownCounter
variable until it reaches 0. Then the timer will stop, that's it. I also introduced a new property Sleep
, which actually stop the base Timer
if set to TRUE
and starts it again if set to FALSE
. But only if the Timer
is not already stopped.
The code
public class CountDownTimer : System.Windows.Forms.Timer
{
public event EventHandler Started;
public event EventHandler Stopped;
private int downCounter = -1;
private int currentDownCounter = 0;
private bool stopped = false;
public int _countDown
{
get
{
return this.downCounter;
}
set
{
this.downCounter = value;
}
}
public int _currentCountDown
{
get
{
return this.currentDownCounter;
}
set
{
this.currentDownCounter = value;
}
}
public CountDownTimer()
{
}
public CountDownTimer(int countDown)
{
this.downCounter = countDown;
this.currentDownCounter = countDown;
base.Tick += new System.EventHandler(this.countdown);
}
protected virtual void OnStarted(EventArgs e)
{
if (Started != null)
{
Started(this, e);
}
}
protected virtual void OnStopped(EventArgs e)
{
if (Stopped != null)
{
Stopped(this, e);
}
}
public new void Start()
{
this.Enabled = true;
}
public new void Stop()
{
this.Enabled = false;
}
public bool Sleep
{
set
{
if (!this.stopped) base.Enabled = !value;
}
get
{
return !base.Enabled;
}
}
public override bool Enabled
{
get
{
return base.Enabled;
}
set
{
base.Enabled = value;
if (value)
{
this.stopped = false;
this.currentDownCounter = this.downCounter;
OnStarted(new System.EventArgs());
}
else
{
this.stopped = true;
OnStopped(new System.EventArgs());
}
}
}
private void countdown(object sender, System.EventArgs e)
{
if (this.downCounter == -1)
{
return;
}
else if (this.currentDownCounter > 0)
{
this.currentDownCounter--;
}
if (this.currentDownCounter == 0)
{
this.Enabled = false;
}
}
}