Display runtime of an application [C#]

Asked

Viewed 60 times

0

I would like help with a process I need to do: The idea is to create an informative label that will contain as many hours, minutes and seconds as my application is working. Time starts to count as long as the form opens.

I don’t know exactly how to start. I was researching and got to the method Stopwatch, but I don’t know if it’s the right one. Could someone help me on how to do this?

1 answer

3


An idea would be to create a Datetime when initiating the form, and within the event Tick of a timer, for example with the Interval a 1000 (1 second), subtract this Datetime with the current Datetime (returns a Timespan).

ex:

private DateTime dataInicio = DateTime.Now;
private void timer1_Tick(object sender, EventArgs e)
{
    TimeSpan span = DateTime.Now - dataInicio;
    this.label1.Text = span.ToString(@"dd\.hh\:mm\:ss");
}

If you do not want to show the days, you can remove dd\., but after a day the hours are over 0 and not 24... will have to find a way, for example using the property TotalHours.

ex:

this.label1.Text = ((int)span.TotalHours).ToString() + ":" + span.ToString(@"mm\:ss");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.