Creating a simple Stopwatch/Timer application with C# and Windows Forms
While working on a project today, I came across the need for a simple stopwatch/timer which would keep track of the total elapsed time until it was reset. It turned out to be a little trickier than I first assumed, so I’ve posted my code here for the convenience of anyone else who needs to do the same thing.
Because I wasn’t interested in sub-second accuracy, I’ve used System.Windows.Forms.Timer for simplicity, but the principle is the same whichever timer class you use.
If you want to find out more about the differences between System.Threading.Timer , System.Windows.Forms.Timer and System.Timers.Timer , it’s definitely worth reading this article comparing the Timer classes in the .NET Framework class library.
Questions or comments? Get in touch @markeebee, or email [Turn On Javascript To View Email Address] .
How To Make a StopWatch With C#
I just want to ask that if I can make a stopwatch with C# I tried:
this but it didn’t worked. My timer is setted up and the interval of the timer is 1000ms. Can someone help me?
![]()
1 Answer 1
It looks to me, that you are more likly to make a watch rather than a stopwatch?
If you’re making a stopwatch, I think you need a field/property in your class that holds the starting time:
and then in timer1_Tick you can do:
It seems that your current code in timer1_Tick only has local variables and therefore always will produce the same time? 🙂
Пишем Секундомер
Привет. необходимо сделать такую штуку.
По нажатию клавиши старт должен включиться секундомер( который показывает минуты и секунды MM:SS)
И по нажатию на клавишу стоп остановиться.
Как такое сделать? заранее спасибо
Добавлено через 34 минуты
P.S. и это должно отображатьса в лейбле к примеру. чтобы человек видел сколько время уже прошло
Пишем англо-русский словарь с нуля
Привет всем, кто сюда будет заглядывать. Предлагаю совместными усилиями разработать простенький.
Секундомер на C#
Здравствуйте. Можете кинуть список разделов, где уже поднимался данный вопрос.
Секундомер
Привет всем, делаю программу, которая засекает время (секудомер) , но почему-то, когда минуты.
Секундомер на форме
Здравствуйте! Хочу сделать секундомер на C# формах, не могу понять как сделать?
Сообщение было отмечено как решение
Решение
AlexDios, тот код что ты дал, он при старте показывает 1 сек и все. отсчет дальше не идет
Design a Stopwatch in C#
![]()
Welcome to another blog. This time I am here with a C# tutorial.In this tutorial I am going to present you with the solution of first exercise problem in C# intermediate level course by Mosh (Moshfegh) Hamedani in Udemy. For those of you who are unware of this course I have given the question below.
For those, who can’t wait for the code I have given link to files here.
Based on the exercise, we are supposed to write a program which allows users to start and stop the stopwatch and print the time span to the console. So, let’s think about a way of organizing the code based on the responsibilities. The features such as starting the stopwatch, stopping the stopwatch and noting the time span should be placed in one class say Stopwatch. The main class will be given the responsibilities of taking the customer input and printing out the time span.
Before starting the coding, below is the losely written algorithm for this task.
i) Read the input from the user.
ii) If the input is start -> start the stopwatch
If the input is stop -> throw an InvalidOperation exception
iii) Read another input from the user
iv) If the input is stop -> stop the stopwatch and print the time span
If the input is start -> throw an InvalidOperation exception
v) Repeat from step (i).
Now first let us build the main class.
Main Class:
The process starts with prompting user to enter S to start the stopwatch and Q to quit as shown in the code block below. The condition in the while is used to check if the input is null or empty. If the input is null or empty then,
will become true but since we used! before the expression it will evluate to false if the input is null, otherwise it will be true.Whenever, the user input is null we consider it as exit clause and the program stops executing as there is no code after the while block.
In the while block we check whether the user entered S (to start) or Q (to stop). Since, we want the program to execute irrespective of the case of the user input I am comparing the input with both small s and captial S. There are multiple ways of acheiving this. You can just convert the user input into lower case or upper case before checking. This way you can get the things done by just one boolean expression. But, I just went in my way to show two possible ways.
The third argument in the string.Equal( ) method in else block tells how to comapre the Strings. There are total 5 options that you can pass to this method as third argument. The option that I used here tells the C# runtime to ignore case. (If you want to know more about “StringComparison.CurrentCultureIgnoreCase” goto official documentation on MSDN.) So, if the input is “S” or “s” we call Start( ) method on Timer which starts the stopwatch and prints a note on the console asking user to press Q to quit. Stopping the stopwatch works in similar manner but it has one extra message which prints the time span.
After performing start and stop operations once, the user should be able to start and stop the stopwatch again any number of times without restarting the program. For this reason, we read input from the user before exiting the while block and repeat the above process.
Stopwatch Class:
Let’s talk about the stopwatch class where all the code related to the core funcitons (basically start and stop) of the stopwatch are placed.It has two methods Start( ) and Stop( ) and four fields as given below.
Since, it is a boolean property it can exist in two states or we consider as stopwatch in running state, as stopwatch in stopped state.
Whenever the start method is called, we should first check whether the stopwatch is already started. This can be acheived by checking _isStart flag. If the _isStart flag is then we throw an InvalidOperationException as it means that stopwatch is already running and you can not perform multiple starts or stops consecutively. If the _startTime is false then we proceed further to record current time and set the _isStart flag to true indicating that stopwatch is now started.
Next the last thing to do is implement the Stop( ) method. Here also, we check the stopwatch running status using _isStart. We should try to stop the
stopwatch only if it is already up and running. If _isStart is false we should throw the InvalidOperationException and exit. If _isStart is true we should record the stop time usind DateTime.now and check the time span by subtracting _startTime from _stopTime. Then, set the _isStart flag to flase and return the _timeSpan to the main class.
So, we are done with the implementation of the stopwatch. If you have followed the exact implementation you should be noticing that your application crashes when you perform ivalid operations that is because I did not handle the exception. If you feel like handling the exception just put the Start( ) and Stop( ) methods in try catch block and your application will not crash anymore.