Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stopwatch that counts down in C#

Tags:

c#

I've seen variations of this by googling it but I have a windows form with a timer control, three textboxes (hour, minute, second) and based on a button being clicked, I want to count down from 2 hours. So right after clicking textbox1 (hour) will be 1, textBox2 (minute) will be 59, textBox3 (second) will be 59 and they will all continue to count down until all read 0.

Does anyone have some code to share for that?

Many thanks.

like image 903
Josh Avatar asked Aug 05 '10 16:08

Josh


2 Answers

Extract the components from a TimeSpan. Record the current time and date as soon as the button is clicked, and store that in a variable. Then, every second your timer should calculate the duration since the start time.

IE: DateTime result = DateTime.Now.Subtract(StartingTime);

Then, use the parts of the resulting TimeSpan to populate the fields.

IE: int Hour = result.Hour; (or something like that).

Addendum: Don't count down manually every second, because this is likely to cause the countdown to be inaccurate.

like image 41
Nicholas Hill Avatar answered Nov 11 '22 09:11

Nicholas Hill


You can use the TimeSpan class. Initialize of to 2 hours. If you start the Timer get the current timer. Then with a Timer object refresh your display every second. Simply get the current Time. So the remaining time is:

TimeSpan remaining = twoHoursTimespan - (CurrentTime - StartTime);

like image 118
codymanix Avatar answered Nov 11 '22 07:11

codymanix