Professional Documents
Culture Documents
The following example uses the RegQueryInfoKey, RegEnumKeyEx, and RegEnumValue functions to
enumerate the subkeys of the specified key. The hKey parameter passed to each function is a handle to an open
key. This key must be opened before the function call and closed afterward.
Copy Code
// QueryKey - Enumerates the subkeys of key and its associated values.
// hKey - Key whose subkeys and values are to be enumerated.
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
DWORD i, retCode;
TCHAR achValue[MAX_VALUE_NAME];
DWORD cchValue = MAX_VALUE_NAME;
if (cSubKeys)
{
printf( "\nNumber of subkeys: %d\n", cSubKeys);
if (cValues)
{
printf( "\nNumber of values: %d\n", cValues);
if (retCode == ERROR_SUCCESS )
{
_tprintf(TEXT("(%d) %s\n"), i+1, achValue);
}
}
}
}
void _tmain(void)
{
HKEY hTestKey;
RegCloseKey(hTestKey);
}
To test this example, create the following registry key by using Regedt32.exe, and then add a few values and
subkeys:
HKEY_CURRENT_USER\Software\TestDir
After running the code, use the F5 key to refresh the registry data, and notice that the TestDir key is deleted.
Copy Code
#include <windows.h>
#include <stdio.h>
#include <strsafe.h>
//*************************************************************
//
// RegDelnodeRecurse()
//
// Purpose: Deletes a registry key and all it's subkeys / values.
//
// Parameters: hKeyRoot - Root key
// lpSubKey - SubKey to delete
//
// Return: TRUE if successful.
// FALSE if an error occurs.
//
//*************************************************************
if (lResult == ERROR_SUCCESS)
return TRUE;
lResult = RegOpenKeyEx (hKeyRoot, lpSubKey, 0, KEY_READ, &hKey);
if (lResult != ERROR_SUCCESS)
{
if (lResult == ERROR_FILE_NOT_FOUND) {
printf("Key not found.\n");
return TRUE;
}
else {
printf("Error opening key.\n");
return FALSE;
}
}
if (*(lpEnd - 1) != TEXT('\\'))
{
*lpEnd = TEXT('\\');
lpEnd++;
*lpEnd = TEXT('\0');
}
dwSize = MAX_PATH;
lResult = RegEnumKeyEx(hKey, 0, szName, &dwSize, NULL,
NULL, NULL, &ftWrite);
if (lResult == ERROR_SUCCESS)
{
do {
if (!RegDelnodeRecurse(hKeyRoot, lpSubKey)) {
break;
}
dwSize = MAX_PATH;
lpEnd--;
*lpEnd = TEXT('\0');
RegCloseKey (hKey);
return FALSE;
}
//*************************************************************
//
// RegDelnode()
//
// Purpose: Deletes a registry key and all it's subkeys / values.
//
// Parameters: hKeyRoot - Root key
// lpSubKey - SubKey to delete
//
// Return: TRUE if successful.
// FALSE if an error occurs.
//
//*************************************************************
void main()
{
BOOL bSuccess;
if(bSuccess)
printf("Success!\n");
else printf("Failure.\n");
}
The following sample uses performance data helper (PDH) to obtain the counter value; it must be linked with
Pdh.lib. PDH is a high-level set of APIs used to obtain performance data.
Note It is not necessary to implement this registry size-check on Windows Server 2003 or Windows XP because
they do not have a registry quota limit.
Copy Code
//*******************************************************************
//
// Determines the current and maximum registry size.
//
//*******************************************************************
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <pdh.h>
//*******************************************************************
//
// Entry point for the program. This function demonstrates how to
// use the GetRegistrySize function implemented below.
//
// It will use the first argument, if present, as the name of the
// computer whose registry you wish to determine. If unspecified,
// it will use the local computer.
//*******************************************************************
}
else
{
// If the operation failed, print the PDH error message.
LPTSTR szMessage = NULL;
FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_HMODULE,
GetModuleHandle( TEXT("PDH.DLL") ), pdhStatus,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
szMessage, 0, NULL );
_tprintf( TEXT("GetRegistrySize failed: %s"), szMessage );
LocalFree( szMessage );
}
return 0;
}
//*******************************************************************
//
// Retrieves the current and maximum registry size. It gets this
// information from the raw counter values for the "% Registry Quota
// In Use" performance counter within the System object.
//
// PARAMETERS:
// szMachineName - Null-terminated string that specifies the
// name of the computer whose registry you wish to query.
// If this parameter is NULL, the local computer is used.
//
// lpdwCurrentSize - Receives the current registry size.
//
// lpdwMaximumSize - Receives the maximum registry size.
//
// RETURN VALUE:
// ERROR_SUCCESS if successful. Otherwise, the function
// returns a PDH error code. These error codes can be
// found in PDHMSG.H. A textual error message can be
// retrieved from PDH.DLL using the FormatMessage function.
//
//******************************************************************
__try
{
// Create counter path
pe.szMachineName = szMachineName;
pe.szObjectName = TEXT("System");
pe.szInstanceName = NULL;
pe.szParentInstance = NULL;
pe.dwInstanceIndex = 1;
pe.szCounterName = TEXT("% Registry Quota In Use");
pdhResult = PdhMakeCounterPath( &pe, szCounterPath,
&dwPathSize, 0 );
if ( pdhResult != ERROR_SUCCESS )
__leave;
if ( lpdwMaximumSize )
*lpdwMaximumSize = (DWORD) pdhRawValues.SecondValue;
}
__finally
{
// Close the query
PdhCloseQuery( hQuery );
}
return 0;
}
Copy Code
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
TCHAR* envVarStrings[] =
{
TEXT("OS = %OS%"),
TEXT("PATH = %PATH%"),
TEXT("HOMEPATH = %HOMEPATH%"),
TEXT("TEMP = %TEMP%")
};
#define ENV_VAR_STRING_COUNT (sizeof(envVarStrings)/sizeof(TCHAR*))
#define INFO_BUFFER_SIZE 32767
void printError( TCHAR* msg );
void main( )
{
DWORD i;
TCHAR infoBuf[INFO_BUFFER_SIZE];
DWORD bufCharCount = INFO_BUFFER_SIZE;
eNum = GetLastError( );
FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, eNum,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
sysMsg, 256, NULL );
Getting the System Version
The following example uses the GetVersionEx, GetSystemMetrics, GetProductInfo, and
GetNativeSystemInfo functions to determine the version information of the currently running operating system.
If compatibility mode is in effect, the example displays the operating system selected for application compatibility.
The example displays the information to the console.
To obtain the full version number for the operating system, call the GetFileVersionInfo function on one of the
system DLLs, such as Kernel32.dll, then call VerQueryValue to obtain the
\\StringFileInfo\\<lang><codepage>\\ProductVersion subblock of the file version information.
Relying on version information is not the best way to test for a feature. Instead, refer to the documentation for the
feature of interest. For more information on common techniques for feature detection, see Operating System
Version.
If you must require a particular operating system, be sure to use it as a minimum supported version, rather than
design the test for the one operating system. This way, your detection code will continue to work on future
versions of Windows.
Copy Code
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <strsafe.h>
ZeroMemory(&si, sizeof(SYSTEM_INFO));
ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
if ( VER_PLATFORM_WIN32_NT==osvi.dwPlatformId &&
osvi.dwMajorVersion > 4 )
{
StringCchCopy(pszOS, BUFSIZE, TEXT("Microsoft "));
if ( osvi.dwMajorVersion == 6 )
{
if( osvi.dwMinorVersion == 0 )
{
if( osvi.wProductType == VER_NT_WORKSTATION )
StringCchCat(pszOS, BUFSIZE, TEXT("Windows Vista "));
else StringCchCat(pszOS, BUFSIZE, TEXT("Windows Server 2008 " ));
}
if ( osvi.dwMinorVersion == 1 )
{
if( osvi.wProductType == VER_NT_WORKSTATION )
StringCchCat(pszOS, BUFSIZE, TEXT("Windows 7 "));
else StringCchCat(pszOS, BUFSIZE, TEXT("Windows Server 2008 R2
" ));
}
switch( dwType )
{
case PRODUCT_ULTIMATE:
StringCchCat(pszOS, BUFSIZE, TEXT("Ultimate Edition" ));
break;
case PRODUCT_PROFESSIONAL:
StringCchCat(pszOS, BUFSIZE, TEXT("Professional" ));
break;
case PRODUCT_HOME_PREMIUM:
StringCchCat(pszOS, BUFSIZE, TEXT("Home Premium Edition" ));
break;
case PRODUCT_HOME_BASIC:
StringCchCat(pszOS, BUFSIZE, TEXT("Home Basic Edition" ));
break;
case PRODUCT_ENTERPRISE:
StringCchCat(pszOS, BUFSIZE, TEXT("Enterprise Edition" ));
break;
case PRODUCT_BUSINESS:
StringCchCat(pszOS, BUFSIZE, TEXT("Business Edition" ));
break;
case PRODUCT_STARTER:
StringCchCat(pszOS, BUFSIZE, TEXT("Starter Edition" ));
break;
case PRODUCT_CLUSTER_SERVER:
StringCchCat(pszOS, BUFSIZE, TEXT("Cluster Server Edition" ));
break;
case PRODUCT_DATACENTER_SERVER:
StringCchCat(pszOS, BUFSIZE, TEXT("Datacenter Edition" ));
break;
case PRODUCT_DATACENTER_SERVER_CORE:
StringCchCat(pszOS, BUFSIZE, TEXT("Datacenter Edition (core
installation)" ));
break;
case PRODUCT_ENTERPRISE_SERVER:
StringCchCat(pszOS, BUFSIZE, TEXT("Enterprise Edition" ));
break;
case PRODUCT_ENTERPRISE_SERVER_CORE:
StringCchCat(pszOS, BUFSIZE, TEXT("Enterprise Edition (core
installation)" ));
break;
case PRODUCT_ENTERPRISE_SERVER_IA64:
StringCchCat(pszOS, BUFSIZE, TEXT("Enterprise Edition for
Itanium-based Systems" ));
break;
case PRODUCT_SMALLBUSINESS_SERVER:
StringCchCat(pszOS, BUFSIZE, TEXT("Small Business Server" ));
break;
case PRODUCT_SMALLBUSINESS_SERVER_PREMIUM:
StringCchCat(pszOS, BUFSIZE, TEXT("Small Business Server
Premium Edition" ));
break;
case PRODUCT_STANDARD_SERVER:
StringCchCat(pszOS, BUFSIZE, TEXT("Standard Edition" ));
break;
case PRODUCT_STANDARD_SERVER_CORE:
StringCchCat(pszOS, BUFSIZE, TEXT("Standard Edition (core
installation)" ));
break;
case PRODUCT_WEB_SERVER:
StringCchCat(pszOS, BUFSIZE, TEXT("Web Server Edition" ));
break;
}
}
else if
( si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_AMD64 )
{
if( osvi.wSuiteMask & VER_SUITE_DATACENTER )
StringCchCat(pszOS, BUFSIZE, TEXT( "Datacenter x64 Edition"
));
else if( osvi.wSuiteMask & VER_SUITE_ENTERPRISE )
StringCchCat(pszOS, BUFSIZE, TEXT( "Enterprise x64 Edition"
));
else StringCchCat(pszOS, BUFSIZE, TEXT( "Standard x64 Edition"
));
}
else
{
if ( osvi.wSuiteMask & VER_SUITE_COMPUTE_SERVER )
StringCchCat(pszOS, BUFSIZE, TEXT( "Compute Cluster
Edition" ));
else if( osvi.wSuiteMask & VER_SUITE_DATACENTER )
StringCchCat(pszOS, BUFSIZE, TEXT( "Datacenter Edition" ));
else if( osvi.wSuiteMask & VER_SUITE_ENTERPRISE )
StringCchCat(pszOS, BUFSIZE, TEXT( "Enterprise Edition" ));
else if ( osvi.wSuiteMask & VER_SUITE_BLADE )
StringCchCat(pszOS, BUFSIZE, TEXT( "Web Edition" ));
else StringCchCat(pszOS, BUFSIZE, TEXT( "Standard Edition" ));
}
}
}
if ( osvi.wProductType == VER_NT_WORKSTATION )
{
StringCchCat(pszOS, BUFSIZE, TEXT( "Professional" ));
}
else
{
if( osvi.wSuiteMask & VER_SUITE_DATACENTER )
StringCchCat(pszOS, BUFSIZE, TEXT( "Datacenter Server" ));
else if( osvi.wSuiteMask & VER_SUITE_ENTERPRISE )
StringCchCat(pszOS, BUFSIZE, TEXT( "Advanced Server" ));
else StringCchCat(pszOS, BUFSIZE, TEXT( "Server" ));
}
}
TCHAR buf[80];
if ( osvi.dwMajorVersion >= 6 )
{
if ( si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_AMD64 )
StringCchCat(pszOS, BUFSIZE, TEXT( ", 64-bit" ));
else if (si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_INTEL )
StringCchCat(pszOS, BUFSIZE, TEXT(", 32-bit"));
}
return TRUE;
}
else
{
printf( "This sample does not support this version of Windows.\n");
return FALSE;
}
}
Example 1
The following example determines whether the application is running on Windows XP with Service Pack 2 (SP2) or
a later version of Windows, such as Windows Server 2003 or Windows Vista.
Copy Code
#include <windows.h>
#include <stdio.h>
BOOL Is_WinXP_SP2_or_Later ()
{
OSVERSIONINFOEX osvi;
DWORDLONG dwlConditionMask = 0;
int op=VER_GREATER_EQUAL;
ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
osvi.dwMajorVersion = 5;
osvi.dwMinorVersion = 1;
osvi.wServicePackMajor = 2;
osvi.wServicePackMinor = 0;
return VerifyVersionInfo(
&osvi,
VER_MAJORVERSION | VER_MINORVERSION |
VER_SERVICEPACKMAJOR | VER_SERVICEPACKMINOR,
dwlConditionMask);
}
void main()
{
if(Is_WinXP_SP2_or_Later())
printf("The system meets the requirements.\n");
else printf("The system does not meet the requirements.\n");
}
Example 2
The following code verifies that the application is running on Windows 2000 Server or a later server, such as
Windows Server 2003 or Windows Server 2008.
Copy Code
#include <windows.h>
#include <stdio.h>
BOOL Is_Win_Server()
{
OSVERSIONINFOEX osvi;
DWORDLONG dwlConditionMask = 0;
int op=VER_GREATER_EQUAL;
ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
osvi.dwMajorVersion = 5;
osvi.dwMinorVersion = 0;
osvi.wServicePackMajor = 0;
osvi.wServicePackMinor = 0;
osvi.wProductType = VER_NT_SERVER;
return VerifyVersionInfo(
&osvi,
VER_MAJORVERSION | VER_MINORVERSION |
VER_SERVICEPACKMAJOR | VER_SERVICEPACKMINOR |
VER_PRODUCT_TYPE,
dwlConditionMask);
}
void main()
{
if(Is_Win_Server())
printf("The system meets the requirements.\n");
else printf("The system does not meet the requirements.\n");
}
Verifying the System Version
This contains examples that use the VerifyVersionInfo function to determine whether the application is running
on a specific operating system.
Example 1
The following example determines whether the application is running on Windows XP with Service Pack 2 (SP2) or
a later version of Windows, such as Windows Server 2003 or Windows Vista.
Copy Code
#include <windows.h>
#include <stdio.h>
BOOL Is_WinXP_SP2_or_Later ()
{
OSVERSIONINFOEX osvi;
DWORDLONG dwlConditionMask = 0;
int op=VER_GREATER_EQUAL;
ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
osvi.dwMajorVersion = 5;
osvi.dwMinorVersion = 1;
osvi.wServicePackMajor = 2;
osvi.wServicePackMinor = 0;
return VerifyVersionInfo(
&osvi,
VER_MAJORVERSION | VER_MINORVERSION |
VER_SERVICEPACKMAJOR | VER_SERVICEPACKMINOR,
dwlConditionMask);
}
void main()
{
if(Is_WinXP_SP2_or_Later())
printf("The system meets the requirements.\n");
else printf("The system does not meet the requirements.\n");
}
Example 2
The following code verifies that the application is running on Windows 2000 Server or a later server, such as
Windows Server 2003 or Windows Server 2008.
Copy Code
#include <windows.h>
#include <stdio.h>
BOOL Is_Win_Server()
{
OSVERSIONINFOEX osvi;
DWORDLONG dwlConditionMask = 0;
int op=VER_GREATER_EQUAL;
ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
osvi.dwMajorVersion = 5;
osvi.dwMinorVersion = 0;
osvi.wServicePackMajor = 0;
osvi.wServicePackMinor = 0;
osvi.wProductType = VER_NT_SERVER;
return VerifyVersionInfo(
&osvi,
VER_MAJORVERSION | VER_MINORVERSION |
VER_SERVICEPACKMAJOR | VER_SERVICEPACKMINOR |
VER_PRODUCT_TYPE,
dwlConditionMask);
}
void main()
{
if(Is_Win_Server())
printf("The system meets the requirements.\n");
else printf("The system does not meet the requirements.\n");
}
Example 1
The following example uses the GetSystemInfo function to obtain hardware information such as the OEM
identifier, processor type, page size, and so on. The example displays the information in the console.
Copy Code
#include <windows.h>
#include <stdio.h>
#pragma comment(lib, "user32.lib")
void main()
{
SYSTEM_INFO siSysInfo;
GetSystemInfo(&siSysInfo);
Example 2
The following example uses the GetSystemMetrics function to determine whether a mouse is installed and
whether the mouse buttons are swapped. The example also uses the SystemParametersInfo function to retrieve
the mouse threshold and speed. It displays the information in the console.
Copy Code
#include <windows.h>
#include <stdio.h>
#pragma comment(lib, "user32.lib")
void main()
{
BOOL fResult;
int aMouseInfo[3];
fResult = GetSystemMetrics(SM_MOUSEPRESENT);
if (fResult == 0)
printf("No mouse installed.\n");
else
{
printf("Mouse installed.\n");
fResult = GetSystemMetrics(SM_SWAPBUTTON);
if (fResult == 0)
printf("Buttons not swapped.\n");
else printf("Buttons swapped.\n");
fResult = SystemParametersInfo(
SPI_GETMOUSE, // get mouse information
0, // not used
&aMouseInfo, // holds mouse information
0); // not used
if( fResult )
{
printf("Speed: %d\n", aMouseInfo[2]);
printf("Threshold (x,y): %d,%d\n",
aMouseInfo[0], aMouseInfo[1]);
}
}
}
Example 3
Copy Code
#include <windows.h>
#include <stdio.h>
#pragma comment(lib, "user32.lib")
void main()
{
BOOL fResult;
int aMouseInfo[3]; // array for mouse information
fResult = SystemParametersInfo(
SPI_GETMOUSE, // get mouse information
0, // not used
&aMouseInfo, // holds mouse information
0); // not used
// Double it.
if( fResult )
{
aMouseInfo[2] = 2 * aMouseInfo[2];
SystemParametersInfo(
SPI_SETMOUSE, // set mouse information
0, // not used
aMouseInfo, // mouse information
SPIF_SENDCHANGE); // update win.ini
}
}
Copy Code
#include <windows.h>
#include <stdio.h>
#pragma comment(lib, "user32.lib")
void main()
{
int aElements[2] = {COLOR_WINDOW, COLOR_ACTIVECAPTION};
DWORD aOldColors[2];
DWORD aNewColors[2];
aOldColors[0] = GetSysColor(aElements[0]);
printf("Current window color: {0x%x, 0x%x, 0x%x}\n",
GetRValue(aOldColors[0]),
GetGValue(aOldColors[0]),
GetBValue(aOldColors[0]));
aOldColors[1] = GetSysColor(aElements[1]);
Sleep(10000);
Copy Code
#include <windows.h>
#include <tchar.h>
#include <strsafe.h>
if( argc != 2 )
{
printf("This sample takes a file name as a parameter\n");
return 0;
}
hFile = CreateFile(argv[1], GENERIC_READ, FILE_SHARE_READ, NULL,
OPEN_EXISTING, 0, NULL);
if(hFile == INVALID_HANDLE_VALUE)
{
printf("CreateFile failed with %d\n", GetLastError());
return 0;
}
if(GetLastWriteTime( hFile, szBuf, MAX_PATH ))
_tprintf(TEXT("Last write time is: %s\n"), szBuf);
CloseHandle(hFile);
}
Changing a File Time to the Current Time
The following example sets the last-write time for a file to the current system time using the SetFileTime function.
The NTFS file system stores time values in UTC format, so they are not affected by changes in time zone or
daylight saving time. The FAT file system stores time values based on the local time of the computer.
The file must be opened with the CreateFile function using FILE_WRITE_ATTRIBUTES access.
Copy Code
#include <windows.h>
return f;
}
Copy Code
#include <windows.h>
#include <time.h>
#include <windows.h>
#include "timeprov.h"
// Global variables.
TimeProvSysCallbacks sc;
WCHAR ProviderName1[] = L"MyCompanyMyAppProvider1";
WCHAR ProviderName2[] = L"MyCompanyMyAppProvider2";
const TimeProvHandle htp1 = (TimeProvHandle)1;
const TimeProvHandle htp2 = (TimeProvHandle)2;
return S_OK;
}
return S_OK;
}