I have a countdown which uses the method recommended in the second answer to this question (substracting the start time from the current time).
The trouble is, when I pause it and then resume it a few seconds later, although the display freezes, the countdown has in the interval continued. I know this is because the start time and the current time haven't changed (!) but I can't think how logically to remedy it.
Selected Code:
private DispatcherTimer cdTimer;
private DateTime startTime;
private TimeSpan countdownFrom = new TimeSpan(0, 30, 0);
cdTimer= new DispatcherTimer();
cdTimer.Interval = new TimeSpan(0, 0, 0, 0, 1);
showTime.Text = countdownFrom .Minutes.ToString("D2") + ':' + countdownFrom .Seconds.ToString("D2");
void cdTimer_Tick(object sender, EventArgs e)
{
TimeSpan difference = DateTime.Now - startTime;
TimeSpan countdown = countdownFrom - difference;
showTime.Text = countdown.Minutes.ToString("D2") + ':' + countdown.Seconds.ToString("D2");
if (countdown.Hours == 0 && countdown.Minutes == 0 && countdown.Seconds == 0 && countdown.Milliseconds <= 100)
{
cdTimer.Stop();
cdTimer.Tick -= new EventHandler(cdTimer_Tick);
}
}
private void start_Click(object sender, RoutedEventArgs e)
{
startTime = DateTime.Now;
cdTimer.Tick += new EventHandler(cdTimer_Tick);
cdTimer.Start();
}
private void pause_Click(object sender, RoutedEventArgs e)
{
if (!paused) {
cdTimer.Stop();
paused = true;
} else {
cdTimer.Start();
paused = false;
}
}