C# Countdown Timer

A timer in C # is an object that executes an action after a specified time interval - for example, it can call a method every 5 seconds.
The best way to understand how it works is to use it in a program.

Creating a timer

Go File -> New -> Project and select Windows Forms Application. From ToolBox choose Timer and add it in the program (with drag & drop).

Now, add a label - its value will be modified by the timer.

Click on the timer1 and look on the properties window for an option:Interval - here we set the time interval, in milliseconds. For a countdown timer, set 1000ms (= 1 second).

Making the timer do something

Double-click on the timer, which we inserted near the form - in the code window, you’ll have a new method: timer1_Tick . This function will be called every second. Here, we’ll add the code to subtract 1 from our label value - so it’ll look like the label value lowers every second.

I tried to write this code as short as possible, so it might look complicated but all it does is to convert the last value of the label into an int, subtracts 1 from that value, converts it back to string and adds it back to the label.

If you don’t understand the version above, here something easier (both versions do the same thing):

1
2
3
4
5
6

privatevoidtimer1_Tick(objectsender,EventArgse){inttimeLeft=int.Parse(label1.Text);//getting the last value (the one from the label)
timeLeft-=1;//subtracting 1
label1.Text=timeLeft.ToString();//adding it back to the label.
}

Starting/stopping it

That’s all, it remains to start our timer using timer1.Start() and provide an initial value for the label.