Show elapsed time on a Windows form in C#

We are going to use the Stopwatch class and a Timer.

First of all we have to add two buttons, a label, named mylabel, to show elapsed time and a Timer component, named mytimer, in our form and set Timer’s interval value to 1000 milliseconds (1 second).

private Stopwatch stopWatch;

One button will start the stopwatch and we put the following code in click event:

stopWatch = new Stopwatch();
mytimer.Enabled = true;
stopWatch.Start();

The other button will stop the stopwatch so we have to put these lines of code in click event:

stopWatch.Stop();
mytimer.Enabled = false;

In Timer’s tick event add the following code:

mylabel.Text =
        stopWatch.Elapsed.Hours.ToString("00") + ":" +
        stopWatch.Elapsed.Minutes.ToString("00") + ":" +
        stopWatch.Elapsed.Seconds.ToString("00");
1 comment Categories: C# Tags: , , , ,
%d bloggers like this: