How to make a Countdown Timer in C#
By FoxLearn 12/1/2024 3:15:53 AM 16.58K
In this article, we’ll walk through the creation of a countdown timer using a Windows Forms Application in C#. The application will include a graphical user interface (GUI) that displays the timer and buttons to start and stop it.
How to make a Countdown Timer in C#?
Open Visual Studio, then click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "Countdown" and then click OK
Design your form as shown below.
Add code to handle your form as below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Countdown { public partial class Form1 : Form { System.Timers.Timer t; int h, m, s; public Form1() { InitializeComponent(); } // Initialize the timer when the form loads private void Form1_Load( object sender, EventArgs e) { t = new System.Timers.Timer(); t.Interval = 1000; // 1 second // Attach the event handler t.Elapsed += OnTimeEvent; } // Timer Elapsed Event private void OnTimeEvent( object sender, System.Timers.ElapsedEventArgs e) { // Use Invoke to update UI from a non-UI thread Invoke( new Action(() => { s += 1; if (s == 60) { s = 0; m += 1; } if (m == 60) { m = 0; h += 1; } // Display time in hh:mm:ss format txtResult.Text = string .Format( "{0}:{1}:{2}" , h.ToString().PadLeft(2, '0' ), m.ToString().PadLeft(2, '0' ), s.ToString().PadLeft(2, '0' )); })); } // Start the timer private void btnStart_Click( object sender, EventArgs e) { t.Start(); } // Stop the timer private void btnStop_Click( object sender, EventArgs e) { t.Stop(); } // Stop the timer when the form is closing private void Form1_FormClosing( object sender, FormClosingEventArgs e) { //Stop timer t.Stop(); Application.DoEvents(); } } } |
Since the timer runs on a separate thread, updating the UI requires marshaling the call to the UI thread. The Invoke
method ensures that the UI is updated safely.
The timer is stopped in the FormClosing
event to prevent it from continuing in the background after the form is closed.
VIDEO TUTORIAL
- How to Create a custom Progress Bar with Percentage in C#
- How to update UI from another thread in C#
- How to Create a Wait Form Dialog in C#
- How to Get all Forms and Open Form with Form Name in C#
- How to use Advanced Filter DataGridView in C#
- How to Print DataGridView with Header & Footer with Landscape in C#
- How to Add Combobox to DataGridView in C#
- How to Hide a WinForm in C#