Home > Software engineering >  View Windows UpTime dynamically in WPF
View Windows UpTime dynamically in WPF

Time:03-06

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

CodePudding user response:

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://docs.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;
}
  • Related