[C# Helper]
Index Books FAQ Contact About Rod
[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Make a countdown timer in C#

[Make a countdown timer 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 = 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 the example to experiment with it and to see additional details.

© 2009-2022 Rocky Mountain Computer Consulting, Inc. All rights reserved.