Label displaying Timespan disappearing in XP but n

2019-07-25 08:58发布

I have a stopwatch timer that I've added to my program. It's working fine on my Win 7 machine, and on the Vista machines I've tried, but in XP, the hrs and mins zeros disappear when the timer starts, but will come back if I reset the timer. Here's all of my code that I have for the timer. I've removed everything that didn't seem necessary to diagnose the problem:

  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));
    }

1条回答
SAY GOODBYE
2楼-- · 2019-07-25 09:20

Older version of .NET, maybe? Your HMS() function critically depends on the number of digits generated by TimeSpan.ToString(). Here's a better way to format it:

    private static string HMS(TimeSpan tms) {
        return new DateTime(tms.Ticks).ToString("H:mm:ss");
    }
查看更多
登录 后发表回答