LECHIP
LECHIP

Reputation: 81

Making a Chronometer c#

I'm trying to make a chronometer forms application that works both as a stopwatch and a countdown with ticking an option. Problem is that I can't seem to be able to draw the miliseconds. Right now, without the miliseconds the Tick method looks like this:

    private void timer_Tick(object sender, EventArgs e)
    {
        if (timespan.TotalSeconds > 0)
        {
            timespan = timespan.Add(new TimeSpan(0, 0, -1));
            updateNumericUpDowns();
        }
        else
        {
            timerCountown.Stop();
        }
    }

The method for updating the UI:

    private void updateNumericUpDowns()
    {
        numericUpDownSeconds.Value = Convert.ToInt32(timespan.Seconds);
        numericUpDownMinutes.Value = Convert.ToInt32(timespan.Minutes);
        numericUpDownHours.Value = Convert.ToInt32(timespan.Hours);
    }

Help is appreciated, tnx everyone!

Upvotes: 1

Views: 5772

Answers (2)

EthanB
EthanB

Reputation: 4289

I don't think I would trust "timer_Tick" for the millisecond resolution: If the system is under heavy load, will a tick be slower or faster than 1 second? (Will that affect the number of elapsed millis?) Try comparing the current time to a known starting time.

private DateTime startTime;

void StartTimer() {
    startTime = DateTime.Now;
    //start timer
}

private void timer_Tick(object sender, EventArgs e)
{
    var currentTime = DateTime.Now;
    timespan = currentTime - startTime; //positive
    bool hasCountdownTerminated = ... //maybe something like timespan < duration + timerResolution
    if (hasCountdownTerminated)
    {
        timerCountown.Stop();
    }
    else
    {
        updateNumericUpDowns();
    }
}    

void updateNumericUpDowns() {
    //use timespan.Milliseconds;
}

Upvotes: 2

Jonathan Wood
Jonathan Wood

Reputation: 67175

Not sure I'm following. Why not just use timespan.Milliseconds?

As it is, you're using hours, minutes, and seconds. If you want to show the milliseconds, then add that.

Upvotes: 2

Related Questions