在 WPF 中动态查看 Windows 正常运行时间
View Windows UpTime dynamically in WPF
我想要Windows UpTime 如下图
我正在使用 NetFrameWork 3
我使用此代码显示 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;
但我收到的是固定的,不会自行更新
我想同时在这里更改 Windows 的正常运行时间
请指导我
你的代码看起来不错。唯一缺少的是您应该定期调用它来更新 UI.
重要提示,因为你想更新 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
您只需稍加修改的代码就可能如下所示:
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;
}
我想要Windows UpTime 如下图
我正在使用 NetFrameWork 3 我使用此代码显示 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;
但我收到的是固定的,不会自行更新 我想同时在这里更改 Windows 的正常运行时间 请指导我
你的代码看起来不错。唯一缺少的是您应该定期调用它来更新 UI.
重要提示,因为你想更新 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
您只需稍加修改的代码就可能如下所示:
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;
}