Make a countdown timer in C#

[countdown timer]

When the program starts, it sets the event name and time. It then enables the Timer control.

// Initialize information about the event.
private const string EventName = "End of the World";
private DateTime EventDate = DateTime.Now +
    new TimeSpan(1, 13, 42, 59);
private void Form1_Load(object sender, EventArgs e)
{
    lblEvent.Text = EventName;
    this.Text = EventName + " at " + EventDate.ToString();
    this.ClientSize = new Size(
        lblEvent.Bounds.Right,
        lblEvent.Bounds.Bottom);
    tmrCheckTime.Enabled = true;
}

The following code shows the Timer‘s Tick event handler.

// Update the countdown.
private void tmrCheckTime_Tick(object sender, EventArgs e)
{
    TimeSpan remaining = EventDate - DateTime.Now;
    if (remaining.TotalSeconds < 1)
    {
        tmrCheckTime.Enabled = false;
        this.WindowState = FormWindowState.Maximized;
        this.TopMost = true;

        foreach (Control ctl in this.Controls)
        {
            if (ctl == lblEvent)
            {
                ctl.Location = new Point(
                    (this.ClientSize.Width - ctl.Width) / 2,
                    (this.ClientSize.Height - ctl.Height) / 2);
            }
            else
            {
                ctl.Visible = false;
            }
        }

        using (SoundPlayer player = new SoundPlayer(
            Properties.Resources.tada))
        {
            player.Play();
        }
    }
    else 
    {
        lblDays.Text = remaining.Days + " days";
        lblHours.Text = remaining.Hours + " hours";
        lblMinutes.Text = remaining.Minutes + " minutes";
        lblSeconds.Text = remaining.Seconds + " seconds";
    }
}

When the Tick event fires, the program calculates the time remaining until the event. If the event time has arrived, the program disables the Timer, maximizes the form, and makes the form topmost. It hides all controls except the one that displays the event name, which it centers. Finally it uses a SoundPlayer object to play the sound resource named tada.

If the event’s time has not arrived, the program displays the number of days, hours, minutes, and seconds remaining.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in miscellany and tagged , , , , , , , , . Bookmark the permalink.

6 Responses to Make a countdown timer in C#

  1. Ousrhire Abdellah says:

    Thanks a lot <3

  2. Mohan Ali says:

    I created Countdown Timer , Can you please guide me to create real timer Example on Threading Timer in c# ?

  3. Which is the best book to learn MVC.net from scratch ?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.