a rough idea of how long a computer has been on:
Windows 以多种方式报告该值:作为kernel32 中的GetTickCount64,它是PerformanceCounter,它位于WMI。它仅报告自上次重新启动以来的系统运行时间。如果上一次重启是一周前,如果净睡 2 天,它可能只报告 5 天,所以它是近似值。
这是有道理的,因为在睡眠/休眠/待机时不能说系统处于“启动”状态。 TaskManager 性能选项卡:
Friend Shared Function GetWMIItem(wmiclass As String, qItem As String) As String
Dim retVal As String = ""
Dim query = String.Format("SELECT {0} FROM {1}", qItem, wmiclass)
Using searcher As New ManagementObjectSearcher(query)
For Each item As ManagementObject In searcher.Get
Dim p = item.Properties(qItem)
If (p IsNot Nothing) AndAlso (p.Value IsNot Nothing) Then
retVal = p.Value.ToString
' should be nothing else
Exit For
End If
Next
End Using
Return retVal
End Function
使用它:
Dim uptime = WMI.GetWMIItem("Win32_PerfFormattedData_PerfOS_System",
"SystemUpTime")
Dim tsUp = TimeSpan.FromSeconds(Convert.ToInt32(uptime))
返回是秒,而不是毫秒。如果您需要上次启动时间:
Dim lastBootStrVal = WMI.GetWMIItem("Win32_OperatingSystem", "LastBootUpTime")
为了阅读它,有一个特殊的转换器,因为它是一种特殊的格式:
dtLastBoot = Management.ManagementDateTimeConverter.ToDateTime(LastBootTimeString)
使用PerformanceCounter 的代码更少(见评论中的链接),但同样慢:
Using uptime As New PerformanceCounter("System", "System Up Time")
' need to call NextValue once before using a PerformanceCounter
uptime.NextValue
ts = TimeSpan.FromSeconds(Convert.ToDouble(uptime.NextValue))
End Using
否则它们都是一样的,GetTickCount64() 提供更好的分辨率,但它仍然是近似值,具体取决于睡眠时间。