Glitchezz
Glitchezz

Reputation: 363

Showing A Timer Result

I have instantiated a timer like so:

System.Timers.Timer seconds = new System.Timers.Timer();
seconds.Elapsed += new ElapsedEventHandler(seconds_Tick);
seconds.Interval = 1;
seconds.Enabled = true; //start timer 

I have created the tick event like so:

private void seconds_Tick(object sender, EventArgs e)//source
{
    time++;
}//end clock_Tick()

time is an integer variable declared in the code.

I try to display the results like so (within a method):

txtProcessTime.Text = TimeSpan.FromSeconds(time).ToString();

This works great up until the timer runs longer than an hour so I then tried:

txtProcessTime.Text = TimeSpan.FromHours(time).ToString();

This shows an even more unusual/unexpected result.

I tried a few others but I reckon I'm using the wrong section..

I would like to code a timer that counts taking into consideration, milliseconds, seconds and hours and have the result displayed in a textbox. Can you help?

The timer is displayed in the format 00:00:00 The TimeSpan.FromHours issue displayed something along the lines of: 7070:xx:xx (I can't remember what the x's values were). The TimeSpan.FromSeconds once the program has been running longer than an hour showed: 2:xx:xx (I can't remember what the x's values were).

The format is being displayed as mm:ss:milliseconds - Could it be that the minutes converted to single numbers once the 60 minutes has passed?

Upvotes: 1

Views: 746

Answers (2)

Sayse
Sayse

Reputation: 43330

Instead of your current approach you may find this more usable, and easily modified for your requirements

using System.Diagnostics

    Stopwatch sw;
    public Form1()
    {
        InitializeComponent();
        sw = new Stopwatch();
        sw.Start();

    }

    private void button1_Click(object sender, EventArgs e)
    {
        textBox1.Text = sw.Elapsed.ToString();
    }

Upvotes: 2

Julián Urbano
Julián Urbano

Reputation: 8488

There is something apparently wrong here: Interval is specified in milliseconds, but you set it to 1. Then, you create the TimeSpan using FromSeconds.

So if you want an event every second, set it like this:

seconds.Interval = 1000;

If you still want it every millisecond, then change your TimeSpan:

txtProcessTime.Text = TimeSpan.FromMilliSeconds(time).ToString()

Upvotes: 2

Related Questions