我有一个秒表计时器,我已添加到我的程序中。它在我的Win 7机器上运行良好,在我试过的Vista机器上工作正常,但在XP中,当定时器启动时,小时和分钟零消失,但如果我重置定时器,它将返回。这是我为计时器提供的所有代码。我删除了诊断问题似乎没有必要的所有内容:
DateTime startTime, stopTime;
TimeSpan stoppedTime;
bool reset;
private void btnStopwatchStart_Click(object sender, EventArgs e)
{
// Start timer and get starting time
if (reset)
{
reset = false;
startTime = DateTime.Now;
stoppedTime = new TimeSpan(0);
}
else
{
stoppedTime += DateTime.Now - stopTime;
}
stopwatchTimer.Enabled = true;
}
private void btnStopwatchReset_Click(object sender, EventArgs e)
{
// Reset displays to zero
reset = true;
lblElapsed.Text = "00:00:00";
}
private void btnStopwatchPause_Click(object sender, EventArgs e)
{
// Stop timer
stopTime = DateTime.Now;
stopwatchTimer.Enabled = false;
}
private void stopwatchTimer_Tick(object sender, EventArgs e)
{
DateTime currentTime;
// Determine elapsed and total times
currentTime = DateTime.Now;
// Display times
lblElapsed.Text = HMS(currentTime - startTime - stoppedTime);
}
private string HMS(TimeSpan tms)
{
// Format time as string, leaving off last six decimal places
string s = tms.ToString();
return (s.Substring(0, s.Length - 6));
}
答案 0 :(得分:2)
可能是旧版本的.NET?您的HMS()函数关键取决于TimeSpan.ToString()生成的位数。这是一种更好的格式化方法:
private static string HMS(TimeSpan tms) {
return new DateTime(tms.Ticks).ToString("H:mm:ss");
}