How to make a Countdown Timer in C#
By FoxLearn 12/1/2024 3:15:53 AM 16.06K
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
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 Print Text in a Windows Form Application Using C#
- How to fill ComboBox and DataGridView automatically in C#
- How to Read text file and Sort list in C#
- How to pass ListView row data into another Form in C#
- How to read and write to text file in C#
- How to Display selected Row from DataGridView to TextBox in C#
- How to Get all Forms and Open Form with Form Name in C#
- How to Get Checked Items In a CheckedListBox in C#