我的倒计时使用了this question第二个答案中建议的方法(减去当前时间的开始时间)。
麻烦的是,当我暂停它然后几秒钟后恢复它,虽然显示器冻结,倒计时间隔继续。我知道这是因为开始时间和当前时间没有改变(!)但是我无法从逻辑上思考如何补救它。
选定代码:
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;
}
}
答案 0 :(得分:1)
在每次停顿时,都要将运行时间缩短。然后在计算中添加:
private TimeSpan _runningTime = new TimeSpan();
private void pause_Click()
{
if (!paused) {
_runningTime = _runningTime.Add(DateTime.Now - startTime);
cdTimer.Stop();
paused = true;
} else {
startTime = DateTime.Now;
cdTimer.Start();
paused = false;
}
}
void cdTime_Tick()
{
// ...
TimeSpan difference = DateTime.Now - startTime;
difference = difference.Add(_runningTime);
TimeSpan countdown = countdownFrom - difference;
// ...
}
编辑:更新了运行时逻辑