1

我有一个秒表计时器,已添加到我的程序中。它在我的 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));
    }
4

1 回答 1

2

可能是旧版本的 .NET?您的 HMS() 函数严重依赖于 TimeSpan.ToString() 生成的位数。这是格式化它的更好方法:

    private static string HMS(TimeSpan tms) {
        return new DateTime(tms.Ticks).ToString("H:mm:ss");
    }
于 2010-06-02T15:39:30.240 回答