Building a digital clock is a simple exercise that you can do when learning how to create a Windows Form application.
It can help you understand how to add UI elements to the user interface, and how to display certain values back to the user.
The digital clock application uses a label to display the time. You can update the time every second by using the tick and load events inside the app's code behind files.
How to Create the UI for the Digital Clock
To create the UI for the application, add a label onto the canvas and design it to look like a digital clock.
- Create a new Windows Forms application.
-
Use the toolbox to drag a label UI element onto the canvas.
-
Highlight the label. Use the properties window to change some of the properties to the following new values:
Property
New Value
Name
clock
Font
Impact, 16pt
Location
90, 70
Text
00:00:00 AM
-
Highlight the form control. Use the properties window to change the size property to "500, 300".
How to Update the Clock in Real Time
You can use events in a Windows Forms app to update the clock label every second.
-
Using the toolbox, drag a timer UI element onto the canvas.
-
The timer UI element has a "Tick" event, which fires every second to represent the ticking of a clock. Highlight the timer UI element, and click on the lightning icon in the properties window.
-
Double-click on the Tick event. This will generate a new function that runs every second.
-
Inside the new function, get the current system's date and time. Update the text of the label to display the new date and time for that second:
private void timer1_Tick(object sender, EventArgs e)
{
clock.Text = DateTime.Now.ToString("hh:mm:ss tt");
} -
For the tick event to work, you will first need to start the timer. Go back to the canvas view by clicking on the Form1.cs [Design] tab at the top of the window.
-
Highlight the form control. In the properties window, click on the lightning icon to open the events list.
-
Double-click on the Load event to generate a new function. This function will run when the form loads once you start the application.
-
In the load function, start the clock timer:
private void Form1_Load(object sender, EventArgs e)
{
timer1.Start();
}
How to Run the Application to View the Digital Clock
You can view the digital clock by running the application.
-
Click on the green play button at the top of the Visual Studio window.
-
Wait for the application to load. When it starts running, you will be able to view your digital clock.
Creating Simple Applications Using Windows Forms
Building a digital clock or alarm is a great way to expand your knowledge and learn how to build a simple application. You can now try building the same type of clock in other tech stacks that you also want to learn.