Introduction
Some may have heard about a Unix command that would display the time the server has been running. Windows won't give you such a command but you can easily put together an application that does just that. Sometimes you might be in situation when your application relies on some resources like services or other apps that are slow to start and can't be synchronized against easily. The uptime might be the last resort in implementing a delay under such conditions, to allow your application to wait until all resources are properly initialized.
Background
Windows allows a wide range of queries to be performed on the machine and processes. This functionality is found in pdh.dll, and we are going to use it to retrieve the UpTime.
Using the code
We will add a counter, will collect the data, format it and close the query.
The code is self-explanatory:
PDH_STATUS status;
HQUERY perfQuery = NULL;
HCOUNTER uptimeCounter;
char uptimeCounterPath[] = "\\\\.\\System\\System Up Time";
PDH_FMT_COUNTERVALUE uptimeValue;
seconds = 0;
if( PdhOpenQuery(NULL, 0, perfQuery ) != ERROR_SUCCESS )
return FALSE;
status = PdhAddCounter(perfQuery, uptimeCounterPath,
0, &uptimeCounter );
if( status != ERROR_SUCCESS )
return FALSE;
status = <CODE>PdhCollectQueryData( perfQuery );
if( status != ERROR_SUCCESS )
return FALSE;
status = PdhGetFormattedCounterValue
( uptimeCounter,
PDH_FMT_LARGE , NULL, &uptimeValue );
if( status != ERROR_SUCCESS )
return FALSE;
PdhCloseQuery
( &perfQuery );
seconds = (DWORD) (uptimeValue.largeValue);
Points of Interest
As an example of this functionality, I've decided to enhance an existing tool submitted by T.Yogaramanan on this site. I've added the ability to select the Time Origin for performing an action. You should be able to choose from the current moment and the UpTime (that's the BOOT radio button). For Windows NT, you might have to drop a pdh.dll file from Windows 2000 OS into the search path of the executable.