C# Create Countdown with Timer – Programming, Pseudocode Example, C# Programming Example
Windows Form

C# Create Countdown with Timer

I’ll show you how to make a countdown with C# and using the timer control.
To do this, we create a new Windows Forms project and switch to the code view of the form.
For this example, we need some global variables. You could also create it later, but we want to program memory conserving.

Global variables

countDownString: Contains the current value of the countdown for display.
countDownStringFont: Contains the font to be used for the countdown display.
countDownBrush: Contains the brush (color) of the countdown display.
endTime: Contains the value when the countdown must be at 0.
timer: The timer instance to update the countdown display.

In the next step, the variables are initialized in the Form Load event, the required events are registered and properties are set for correct display. At the end the timer is started.

Form Load Event

endTime: We add 7200 seconds at the moment. This gives a countdown value of 2 hours.
DoubleBuffered Property: This is set to true to prevent possible flickering of the form or countdown.
ResizeRedraw Property: This tells the form that if the user changes the shape size, the Form – Paint Event will automatically be called because we want to place the countdown centered on the shape.
Timer Interval Property: Indicates how often the tick event should occur (value 50 for every 50 milliseconds)

Let us now come to the interesting part. The timer tick event.
Timer Tick Event

First, we find out how much time is left by subtracting the time from the end time.
Then we check if the countdown is over or not. When it is over, the countdown string is set to a “null string” and the brush is given the color red to make the ending more visible. Then we call Refresh to force a redraw.
Since the countdown is ready, we can stop the timer.
Finally, we give a message that the countdown is finished.
If the countdown is not over, we’ll add the remaining time to the global countDownString. With the ToString method we make sure that always 2 digits are displayed (eg 08).
Again, we call the refresh method to force redrawing.

When you start the project, not much is happening. It lacks the paint event in which the actual countdown is drawn.

Form Paint Event

Here we first calculate how big the string in pixels should be drawn. We need this because we want to show the countdown in the middle of the form.
Then the actual countdown is drawn by Graphics.DrawString.Now you can test your personal countdown:

1. Start the countdown

2. Resized From

 

Alternative Example:

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.