Click here to Skip to main content
Click here to Skip to main content

Use a timer to create a simple alarm application

By , 23 Mar 2003
Rate this:
Please Sign up or sign in to vote.

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 )
{
    //Your code here 
}

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
    {
        //Controls and Components
        private System.Windows.Forms.TextBox timerInput;
        private System.Windows.Forms.Button StartButton;
        private System.Windows.Forms.Button ResetButton;
        private System.ComponentModel.IContainer components;
        //Timer and associated variables
        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
        /// <SUMMARY>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </SUMMARY>
        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();
            // 
            // timerInput
            // 
            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";
            // 
            // StartButton
            // 
            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);
            // 
            // ResetButton
            // 
            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);
            // 
            // TimerForm
            // 
            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);
                }

                //Sound Alarm
                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;

                //Check for invalid input
                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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Andrew Boisen
Software Developer
Australia Australia
No Biography provided

Comments and Discussions

 
Generalshowing error Pingroupsunil subramannian7-Mar-14 17:45 
QuestionIs that code not compatible with Visual Studio 2008 Pinmemberrixan2-Nov-11 22:31 
GeneralTimer code Pinmemberbollamvenu18-Sep-10 10:13 
GeneralNull filestream Pinmemberamu_4_u_112822-Feb-10 18:13 
GeneralVery good article.But I have one doubt Pinmembersheebasharaf25-May-09 2:20 
Generalnice article PinmemberDonsw19-Apr-09 11:15 
QuestionHow to adapt this to VB ASP .NET PinmemberCliff_k1012-Feb-06 11:53 
AnswerRe: How to adapt this to VB ASP .NET PinmemberCliff_k1012-Feb-06 11:56 
GeneralCrossthread operation Pinmembernizchka15-Jan-06 14:56 
GeneralRe: Crossthread operation PinmemberZaidIT26-Feb-08 7:53 
GeneralRe: Crossthread operation Pinmemberfranks_feat22-Apr-09 6:55 
GeneralSimple yet effective PinmemberArch4ngel28-Jul-05 11:02 
GeneralAttention for alarm.wav file Pinmembermiranch20-Jul-05 1:28 
Generalvolume PinsussEdywison21-Aug-04 12:54 
QuestionHow to programing for a microphone in C# PinmemberCNWORM22-Aug-03 20:54 
AnswerRe: How to programing for a microphone in C# PinmemberAndrew Boisen23-Aug-03 1:54 
GeneralOuch PinmemberSteve McLenithan24-Mar-03 7:17 
GeneralRe: Ouch [also...] PinmemberSteve McLenithan24-Mar-03 7:25 
GeneralRe: Ouch PinmemberAndrew Boisen24-Mar-03 11:02 
GeneralRe: Ouch PinmemberSteve McLenithan24-Mar-03 11:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140415.2 | Last Updated 24 Mar 2003
Article Copyright 2003 by Andrew Boisen
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid