Browsing Performance Counters
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
#include <pdh.h>
#define SAMPLE_INTERVAL_MS 1000
#define MAXPATH 80
int __cdecl _tmain (int argc, TCHAR **argv)
{
HQUERY hQuery;
HCOUNTER *pCounterHandle;
PDH_STATUS pdhStatus;
PDH_FMT_COUNTERVALUE fmtValue;
DWORD ctrType;
SYSTEMTIME stSampleTime;
PDH_BROWSE_DLG_CONFIG BrowseDlgData;
CHAR szPathBuffer[MAXPATH];
int nRetCode = 0;
// Open the query object.
pdhStatus = PdhOpenQuery (0, 0, &hQuery);
// Allocate the counter handle array. Allocate room for
// one handle per command line arg, not including the
// executable file name.
pCounterHandle = (HCOUNTER *)GlobalAlloc(GPTR, sizeof(HCOUNTER));
// Zero the contents of the structure.
memset (&BrowseDlgData, 0, sizeof(PDH_BROWSE_DLG_CONFIG));
// Initialize the browser dialog window settings.
BrowseDlgData.bIncludeInstanceIndex = FALSE;
BrowseDlgData.bSingleCounterPerAdd = TRUE;
BrowseDlgData.bSingleCounterPerDialog = TRUE;
BrowseDlgData.bLocalCountersOnly = FALSE;
BrowseDlgData.bWildCardInstances = TRUE;
BrowseDlgData.bHideDetailBox = TRUE;
BrowseDlgData.bInitializePath = FALSE;
BrowseDlgData.bDisableMachineSelection = FALSE;
BrowseDlgData.bIncludeCostlyObjects = FALSE;
BrowseDlgData.bReserved = TRUE;
BrowseDlgData.hWndOwner = NULL;
BrowseDlgData.bReserved = FALSE;
BrowseDlgData.szReturnPathBuffer = szPathBuffer;
BrowseDlgData.cchReturnPathLength = MAXPATH;;
BrowseDlgData.pCallBack = NULL;
BrowseDlgData.dwCallBackArg = 0;
BrowseDlgData.CallBackStatus = ERROR_SUCCESS;
BrowseDlgData.dwDefaultDetailLevel = PERF_DETAIL_WIZARD;
BrowseDlgData.szDialogBoxCaption = "Select a counter to monitor.";
// Display the counter browser window.
pdhStatus = PdhBrowseCounters (&BrowseDlgData);
pdhStatus = PdhAddCounter (hQuery,
szPathBuffer,
0,
pCounterHandle);
// "Prime" counters that need two values to display a
// formatted value.
pdhStatus = PdhCollectQueryData (hQuery);
// Print counter values until a key is pressed.
while (!_kbhit()) {
// Wait one interval.
Sleep(SAMPLE_INTERVAL_MS);
// Get the sample time.
GetLocalTime (&stSampleTime);
// Get the current data values.
pdhStatus = PdhCollectQueryData (hQuery);
// Print the time stamp for the sample.
_tprintf (TEXT("\n
\"%2.2d/%2.2d/%4.4d %2.2d:%2.2d:%2.2d.%3.3d\""),
stSampleTime.wMonth,
stSampleTime.wDay,
stSampleTime.wYear,
stSampleTime.wHour,
stSampleTime.wMinute,
stSampleTime.wSecond,
stSampleTime.wMilliseconds);
// Get the current value of this counter.
pdhStatus = PdhGetFormattedCounterValue (*pCounterHandle,
PDH_FMT_DOUBLE,
&ctrType,
&fmtValue);
if (pdhStatus == ERROR_SUCCESS) {
_tprintf (TEXT(",\"%.20g\""), fmtValue.doubleValue);
} else {
// Print the error value.
_tprintf (TEXT(".\"-1\""));
}
}
// Close the query.
pdhStatus = PdhCloseQuery (hQuery);
return nRetCode;
}