Find out if computer rebooted since the last time my program ran?
How can my program know if windows rebooted 开发者_JS百科since the last time it ran? All versions of windows XP and on.
This can be accomplished trivially using the global atom table. Just make sure your atom name is unlikely to conflict with another atom.
if (GlobalFindAtom ("MySecretName") == 0)
{
// First time run since reboot
GlobalAddAtom ("MySecretName");
}
There's a Windows API call you can make called GetTickCount...
http://msdn.microsoft.com/en-us/library/ms724408%28VS.85%29.aspx
Edit: The idea is that when your program starts, you make a call to GetTickCount (which returns how many milliseconds Windows has been running), and then calculate an exact start date (right now minus the number of milliseconds). Store that date, and then the next time your program starts, calculate the date again and compare it to the previously stored date. If the dates are different, Windows has rebooted. Use GetTickCount64 if possible (but don't code your solution solely using this function.
You can use WMI:
strComputer = "."
Set objWMIService = GetObject _
("winmgmts:\\" & strComputer & "\root\cimv2")
Set colOperatingSystems = objWMIService.ExecQuery _
("Select * from Win32_OperatingSystem")
For Each objOS in colOperatingSystems
dtmBootup = objOS.LastBootUpTime
dtmLastBootupTime = WMIDateStringToDate(dtmBootup)
dtmSystemUptime = DateDiff("h", dtmLastBootUpTime, Now)
Wscript.Echo dtmSystemUptime
Next
Function WMIDateStringToDate(dtmBootup)
WMIDateStringToDate = CDate(Mid(dtmBootup, 5, 2) & "/" & _
Mid(dtmBootup, 7, 2) & "/" & Left(dtmBootup, 4) _
& " " & Mid (dtmBootup, 9, 2) & ":" & _
Mid(dtmBootup, 11, 2) & ":" & Mid(dtmBootup, _
13, 2))
End Function
net statistics workstation|find "Statistics since"
The Microsoft utility uptime.exe "processes the machine's event log to determine system availability and current uptime".
Simple, but ugly solution : just launch a never-ending dummy process :-)
If it's still here, you didn't reboot. If it's not, chances are that you have just rebooted.
In the vein of ugly hacks ... stick something in one of the RunOnce registry keys
How about adding a file to %TMP% and check if it's still there (%TMP% should be cleared at each reboot by Windows)
or
more robust way, create a file somewhere and mark it for deletion on next reboot (see MoveFileEx API) and check that file
精彩评论