
Introduction
When I work on the computer, I often get so absorbed that I glance up a minute later to find
that three hours have passed without my even noticing it. So I've pulled together some
C# skills I've learnt from some of the articles here at Code Project, to create a simple
little application that uses a Timer object to
count down the seconds towards a time set by a user, and then plays a looping wave
sound file until the timer is reset.
I've tried to keep it simple, but I've added some extra functionality for a notify icon
to appear in the status bar. I mainly added this functionality because I hate the idea of
a simple application like this taking up space in the taskbar.
Basics of the Timer Object
The very first thing you need, is to access the necessary namespaces to use a Timer object.
using System.Threading;
using System.Timers;
Now I'll give you the basics for creating the Timer and setting an event delegate for the
Timer object's public Elapsed event.
The creation of the Timer object comes first, I called
my timer timerClock. Next I set
the Elapsed event delegate, by specifying a delegate to be called when the event fires.
I called my delegate OnTimer().
Next I set the Interval property, to the time in milliseconds that I wish the
Elapsed event to be fired, which means that my delegate OnTimer()will be called every 1000
milliseconds, or every 1 second, if I set the Interval
property to 1000 milliseconds.
Finally, I set the Enabled property to true so that the timer is active. Then it's just a
simple matter of creating a delegate to be called when the Elapsed event is fired by the
Timerobject. If you haven't used delegates before, then don't worry, they are very easy to use. Just
create a method that receives the appropriate variables for the event you are capturing.
In the case of the
Elapsed event, my delegate needs to receive a plain
Object, and an
ElapsedEventArgs object.
private System.Timers.Timer timerClock = new System.Timers.Timer();
timerClock.Elapsed += new ElapsedEventHandler(OnTimer);
timerClock.Interval = 1000;
timerClock.Enabled = true;
public void OnTimer( Object source, ElapsedEventArgs e )
{
}
Using the Timer in an Alarm Application
Okay, with the basics out of the way I can show you the code for the actual application. Note
that I haven't included the code to play wave sounds or the code for displaying a notify icon,
in the interests of keeping this simple. The full code is available in the demo project where you
will see that, I have pretty much just cut and pasted the wave player functions straight from the
article by jow Blow on "Low level audio players".
In the code below you will see that I have separated the instantiation of the
Timer object into it's own initialization method named
InitializeTimer() which is called from the class' constructor. I've also
created two methods named inputToSeconds() and
secondsToTime() which just process the time value from a
string
to an integer, and vice versa. These methods are just used to help display the time in the
application's TextBox control and aren't actually very important in the big scheme of things.
The rest of the code you will recognize as the standard Visual Studio.NET
Boilerplate code for a
Win Form.
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Threading;
using System.Timers;
using System.IO;
using System.Reflection;
namespace timerAlarm
{
public class TimerForm : System.Windows.Forms.Form
{
private System.Windows.Forms.TextBox timerInput;
private System.Windows.Forms.Button StartButton;
private System.Windows.Forms.Button ResetButton;
private System.ComponentModel.IContainer components;
private System.Timers.Timer timerClock = new System.Timers.Timer();
private int clockTime = 0;
private int alarmTime = 0;
public TimerForm()
{
InitializeComponent();
InitializeTimer();
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Resources.ResourceManager resources = new System.
Resources.ResourceManager(typeof(TimerForm));
this.timerInput = new System.Windows.Forms.TextBox();
this.StartButton = new System.Windows.Forms.Button();
this.ResetButton = new System.Windows.Forms.Button();
this.SuspendLayout();
this.timerInput.Location = new System.Drawing.Point(12, 13);
this.timerInput.Name = "timerInput";
this.timerInput.Size = new System.Drawing.Size(50, 20);
this.timerInput.TabIndex = 0;
this.timerInput.Text = "00:00:00";
this.StartButton.FlatStyle = System.Windows.Forms.
FlatStyle.System;
this.StartButton.Location = new System.Drawing.Point(75, 11);
this.StartButton.Name = "StartButton";
this.StartButton.TabIndex = 1;
this.StartButton.Text = "Start";
this.StartButton.Click += new System.EventHandler
(this.StartButton_Click);
this.ResetButton.FlatStyle = System.Windows.Forms.
FlatStyle.System;
this.ResetButton.Location = new System.Drawing.Point(161, 11);
this.ResetButton.Name = "ResetButton";
this.ResetButton.TabIndex = 2;
this.ResetButton.Text = "Reset";
this.ResetButton.Click += new
System.EventHandler(this.ResetButton_Click);
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(247, 46);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.ResetButton,
this.StartButton,
this.timerInput});
this.FormBorderStyle = System.Windows.Forms.
FormBorderStyle.FixedSingle;
this.Icon = ((System.Drawing.Icon)(resources.
GetObject("$this.Icon")));
this.MaximizeBox = false;
this.Name = "TimerForm";
this.StartPosition = System.Windows.Forms.
FormStartPosition.CenterScreen;
this.Text = "Alarm Timer";
this.Resize += new System.EventHandler(this.
TimerForm_Resized);
this.ResumeLayout(false);
}
#endregion
public void InitializeTimer()
{
this.timerClock.Elapsed += new ElapsedEventHandler(OnTimer);
this.timerClock.Interval = 1000;
this.timerClock.Enabled = true;
}
[STAThread]
static void Main()
{
Application.Run(new TimerForm());
}
private void TimerForm_Resized(object sender, System.EventArgs e)
{
if( this.WindowState == FormWindowState.Minimized )
{
this.Hide();
}
}
private void StartButton_Click(object sender, System.EventArgs e)
{
this.clockTime = 0;
inputToSeconds( this.timerInput.Text );
}
private void ResetButton_Click(object sender, System.EventArgs e)
{
try
{
this.clockTime = 0;
this.alarmTime = 0;
this.timerInput.Text = "00:00:00";
}
catch( Exception ex )
{
MessageBox.Show("ResetButton_Click(): " + ex.Message );
}
}
public void OnTimer(Object source, ElapsedEventArgs e)
{
try
{
this.clockTime++;
int countdown = this.alarmTime - this.clockTime ;
if( this.alarmTime != 0 )
{
this.timerInput.Text = secondsToTime(countdown);
}
if( this.clockTime == this.alarmTime )
{
MessageBox.Show("Play Sound");
}
}
catch( Exception ex )
{
MessageBox.Show("OnTimer(): " + ex.Message );
}
}
private void inputToSeconds( string timerInput )
{
try
{
string[] timeArray = new string[3];
int minutes = 0;
int hours = 0;
int seconds = 0;
int occurence = 0;
int length = 0;
occurence = timerInput.LastIndexOf(":");
length = timerInput.Length;
if( occurence == -1 || length != 8 )
{
MessageBox.Show("Invalid Time Format.");
ResetButton_Click( null, null );
}
else
{
timeArray = timerInput.Split(':');
seconds = Convert.ToInt32( timeArray[2] );
minutes = Convert.ToInt32( timeArray[1] );
hours = Convert.ToInt32( timeArray[0] );
this.alarmTime += seconds;
this.alarmTime += minutes*60;
this.alarmTime += (hours*60)*60;
}
}
catch( Exception e )
{
MessageBox.Show("inputToSeconds(): " + e.Message );
}
}
public string secondsToTime( int seconds )
{
int minutes = 0;
int hours = 0;
while( seconds >= 60 )
{
minutes += 1;
seconds -= 60;
}
while( minutes >= 60 )
{
hours += 1;
minutes -= 60;
}
string strHours = hours.ToString();
string strMinutes = minutes.ToString();
string strSeconds = seconds.ToString();
if( strHours.Length < 2 )
strHours = "0" + strHours;
if( strMinutes.Length < 2 )
strMinutes = "0" + strMinutes;
if( strSeconds.Length < 2 )
strSeconds = "0" + strSeconds;
return strHours + ":" + strMinutes + ":" + strSeconds;
}
}
}
Code References
The implementation for the timer is home grown, but the demo project code
for playing the wave sound files is taken from the article
A low-level audio player in C#
by Ianier Munoz. Complements to Ianier Munoz, as the classes he developed for playing wave
files were exceptionally easy to apply and reuse.
Conclusion
This application demonstrates a simple use of the Timer object in a real world example,
at its core combining simple elements to create a quick little application that I hope someone
besides me can get some use out of.