Make a countdown timer that displays the number of days, minutes, hours, and seconds until an event in C#

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 = new DateTime(2012, 12, 21, 12, 12, 12);
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.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.