0

I want to get Windows UpTime like the picture below

enter image description here

I am using NetFrameWork 3 I use this code to display UpTime for Windows

PerformanceCounter upTime = new PerformanceCounter("System", "System Up Time");
upTime.NextValue();
TimeSpan ts = TimeSpan.FromSeconds(upTime.NextValue());
UpTime.Text = "UpTime: " + ts.Days + ":" + ts.Hours + ":" + ts.Minutes + ":" + ts.Seconds;

But what I receive is fixed and does not update itself I want to change the uptime of Windows here at the same time please guide me

2
  • You could use a DispatcherTimer to periodically call this code. Commented Mar 6, 2022 at 7:33
  • Can you explain in full? Commented Mar 6, 2022 at 7:35

1 Answer 1

1

Your code looks good. The only thing missing is that you should call it periodically to update the UI.

Take a look at the example: https://learn.microsoft.com/en-us/dotnet/api/system.windows.threading.dispatchertimer?view=windowsdesktop-6.0

Important to note, since you want to update UI:

In order to access objects on the user interface (UI) thread, it is necessary to post the operation onto the Dispatcher of the user interface (UI) thread using Invoke or BeginInvoke. Reasons for using a DispatcherTimer as opposed to a System.Timers.Timer are that the DispatcherTimer runs on the same thread as the Dispatcher

Your only slightly modified code might then look something like this:

DispatcherTimer dispatcherTimer;

public MainWindow()
{
    InitializeComponent();
    DispatcherTimer_Tick(null, EventArgs.Empty);
    dispatcherTimer = new DispatcherTimer();
    dispatcherTimer.Interval = TimeSpan.FromSeconds(1);
    dispatcherTimer.Tick += DispatcherTimer_Tick;
    dispatcherTimer.Start();
}

private void DispatcherTimer_Tick(object? sender, EventArgs e)
{
    PerformanceCounter upTime = new PerformanceCounter("System", "System Up Time");
    upTime.NextValue();
    TimeSpan ts = TimeSpan.FromSeconds(upTime.NextValue());
    UpTime.Text = "UpTime: " + ts.Days + ":" + ts.Hours + ":" + ts.Minutes + ":" + ts.Seconds;
}
2
  • Thanks This method answered but there is a way to show the result sooner It takes a few seconds for it to update itself when I open the app Commented Mar 6, 2022 at 7:48
  • You could make an immediate call with DispatcherTimer_Tick(null, EventArgs.Empty);, just insert it directly after the line InitializeComponent(); Commented Mar 6, 2022 at 8:01

Not the answer you're looking for? Browse other questions tagged or ask your own question.