Building a Stopwatch with C#

Another C# project suitable for beginners. This time our C# project is building a simple stopwatch.

Step 1: Adding a Label

Open a forms application project and access the Toolbox. Select a Label and place it inside the form. This is the place where the time will be displayed, so the size of the label should be large enough.

Go to Appearance and change the Text inside the labels to hours, minutes, seconds and miniseconds. Also go to Font and increase the size of the font.

Step 2: Adding the Buttons and a Timer

Next you should add the buttons under the label. Select Button from the Toolbox and add a button to start, pause and reset the stopwatch. Change the text of the buttons. You can also change the shape, color and font of the buttons if you want.

You also need to add a Timer. Go to Toolbox and select it. Click once on the form to add it. The Timer doesn’t have graphical properties, so you only see a banner below the form.

Step 4: Adding the Code for the Buttons

Double click every added component (including the timer) to initiate its code. Then add the following (namespace) to the upper part of the code:

using System.Diagnostics;

Go a little bit down and add the code below under public partial class, between the brackets.

private Stopwatch stopWatch1;

Also add the code below under Form1_Load:

Stopwatch stopWatch1 = new Stopwatch();

The code for the three buttons to start, pause and reset the stopwatch is very simple.

The code to start the stopwatch is:

stopWatch1.Start();

To pause the stopwatch:

stopWatch1.Stop();

And the code to reset the stopwatch is as follows:

stopWatch.Reset();

Step 5: Adding the Code to Display Time

The code above is not enough display the time running on the label. When you click any of the three buttons the label won’t change. To display the time running on the label you have to add the following code:

label1.Text = string.Format("{0:hh\\mm\\:ss\\:ff}", stopwatch.Elapsed);

Add the code above between the brackets of the code that handles the timer.

Pay attention to this line of code, because making a small mistake in it can result in the stopwatch displaying a weird set of numbers.

You can experiment with different colors and shapes for the background and the buttons.

If you found this guide helpful, here is another guide to build a notepad.