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

Sir Rufo
  • 18,395
  • 2
  • 39
  • 73
XxMaHdIxX
  • 3
  • 4

1 Answers1

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;
}
Stephan Schlecht
  • 26,556
  • 1
  • 33
  • 47
  • 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 – XxMaHdIxX Mar 06 '22 at 07:48
  • You could make an immediate call with `DispatcherTimer_Tick(null, EventArgs.Empty);`, just insert it directly after the line `InitializeComponent();` – Stephan Schlecht Mar 06 '22 at 08:01