Getting the System Version

来源:互联网 发布:淘宝客服介入流程 编辑:程序博客网 时间:2024/04/30 00:18

ms-help://MS.MSDNQTR.v90.chs/sysinfo/base/getting_the_system_version.htm

 

Getting the System Version

The followingexample uses the GetVersionEx,GetSystemMetrics, andGetNativeSystemInfo functions todetermine the version information of the currently running operating system.The code outputs the information to the console.

Relying on versioninformation is not the best way to test for a feature. Instead, refer to thedocumentation for the feature of interest. For more information on commontechniques for feature detection, seeOperating System Version.

If you mustrequire a particular operating system, be sure to use it as a minimum supportedversion, rather than design the test for the one operating system. This way,your detection code will continue to work on future versions of Windows.

#include <windows.h>

#include <tchar.h>

#include <stdio.h>

 

#define BUFSIZE 80

 

typedef void (WINAPI *PGNSI)(LPSYSTEM_INFO);

 

int __cdecl _tmain()

{

   OSVERSIONINFOEX osvi;

   SYSTEM_INFO si;

   PGNSI pGNSI;

   BOOL bOsVersionInfoEx;

 

   ZeroMemory(&si,sizeof(SYSTEM_INFO));

   ZeroMemory(&osvi,sizeof(OSVERSIONINFOEX));

 

   // Try calling GetVersionEx usingthe OSVERSIONINFOEX structure.

   // If that fails, try using theOSVERSIONINFO structure.

 

   osvi.dwOSVersionInfoSize =sizeof(OSVERSIONINFOEX);

 

   if( !(bOsVersionInfoEx =GetVersionEx ((OSVERSIONINFO *) &osvi)) )

   {

      osvi.dwOSVersionInfoSize =sizeof (OSVERSIONINFO);

      if (! GetVersionEx ((OSVERSIONINFO *) &osvi) )

         return FALSE;

   }

 

   // Call GetNativeSystemInfo ifsupported

   // or GetSystemInfo otherwise.

 

   pGNSI = (PGNSI) GetProcAddress(

     GetModuleHandle(TEXT("kernel32.dll")),

     "GetNativeSystemInfo");

   if(NULL != pGNSI)

      pGNSI(&si);

   else GetSystemInfo(&si);

 

   switch (osvi.dwPlatformId)

   {

      // Test for the Windows NTproduct family.

 

      case VER_PLATFORM_WIN32_NT:

 

      // Test for the specificproduct.

 

      if ( osvi.dwMajorVersion == 6&& osvi.dwMinorVersion == 0 )

      {

         if( osvi.wProductType ==VER_NT_WORKSTATION )

             printf ("WindowsVista ");

         else printf ("Windows Server\"Longhorn\" " );

      }

 

      if ( osvi.dwMajorVersion == 5&& osvi.dwMinorVersion == 2 )

      {

         if(GetSystemMetrics(SM_SERVERR2) )

            printf( "MicrosoftWindows Server 2003 \"R2\" ");

         else if( osvi.wProductType== VER_NT_WORKSTATION &&

           si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_AMD64)

         {

            printf( "MicrosoftWindows XP Professional x64 Edition ");

         }

         else printf("Microsoft Windows Server 2003, ");

      }

 

      if ( osvi.dwMajorVersion == 5&& osvi.dwMinorVersion == 1 )

         printf ("MicrosoftWindows XP ");

 

      if ( osvi.dwMajorVersion == 5&& osvi.dwMinorVersion == 0 )

         printf ("MicrosoftWindows 2000 ");

 

      if ( osvi.dwMajorVersion <=4 )

         printf ("MicrosoftWindows NT ");

 

      // Test for specific producton Windows NT 4.0 SP6 and later.

      if( bOsVersionInfoEx )

      {

         // Test for the workstationtype.

         if ( osvi.wProductType ==VER_NT_WORKSTATION &&

             si.wProcessorArchitecture!=PROCESSOR_ARCHITECTURE_AMD64)

         {

            if( osvi.dwMajorVersion== 4 )

               printf ("Workstation 4.0 " );

            else if( osvi.wSuiteMask& VER_SUITE_PERSONAL )

               printf ( "HomeEdition " );

            else printf ("Professional " );

         }

           

         // Test for the servertype.

         else if ( osvi.wProductType== VER_NT_SERVER ||

                   osvi.wProductType ==VER_NT_DOMAIN_CONTROLLER )

         {

           if(osvi.dwMajorVersion==5 && osvi.dwMinorVersion==2)

            {

               if (si.wProcessorArchitecture ==

                   PROCESSOR_ARCHITECTURE_IA64 )

               {

                   if(osvi.wSuiteMask & VER_SUITE_DATACENTER )

                      printf ("Datacenter Edition "

                              "for Itanium-based Systems" );

                   else if(osvi.wSuiteMask & VER_SUITE_ENTERPRISE )

                      printf ( "EnterpriseEdition "

                              "for Itanium-based Systems" );

               }

 

               else if (si.wProcessorArchitecture ==

                        PROCESSOR_ARCHITECTURE_AMD64 )

               {

                   if(osvi.wSuiteMask & VER_SUITE_DATACENTER )

                      printf ("Datacenter x64 Edition " );

                   else if(osvi.wSuiteMask & VER_SUITE_ENTERPRISE )

                      printf ("Enterprise x64 Edition " );

                   else printf( "Standard x64Edition " );

               }

 

               else

               {

                   if(osvi.wSuiteMask & VER_SUITE_DATACENTER )

                      printf ("Datacenter Edition " );

                   else if(osvi.wSuiteMask & VER_SUITE_ENTERPRISE )

                      printf ("Enterprise Edition " );

                   else if (osvi.wSuiteMask & VER_SUITE_BLADE )

                      printf ("Web Edition " );

                   else printf ("Standard Edition " );

               }

            }

            elseif(osvi.dwMajorVersion==5 && osvi.dwMinorVersion==0)

            {

               if( osvi.wSuiteMask& VER_SUITE_DATACENTER )

                  printf ("Datacenter Server " );

               else if(osvi.wSuiteMask & VER_SUITE_ENTERPRISE )

                  printf ("Advanced Server " );

               else printf ("Server " );

            }

            else  // Windows NT 4.0

            {

               if( osvi.wSuiteMask &VER_SUITE_ENTERPRISE )

                  printf("Server 4.0, Enterprise Edition " );

               else printf ("Server 4.0 " );

            }

         }

      }

      // Test for specific producton Windows NT 4.0 SP5 and earlier

      else 

      {

         HKEY hKey;

         TCHARszProductType[BUFSIZE];

         DWORDdwBufLen=BUFSIZE*sizeof(TCHAR);

         LONG lRet;

 

         lRet = RegOpenKeyEx(HKEY_LOCAL_MACHINE,

           TEXT("SYSTEM\\CurrentControlSet\\Control\\"

                "ProductOptions"), 0, KEY_QUERY_VALUE, &hKey );

         if( lRet != ERROR_SUCCESS )

            return FALSE;

 

         lRet = RegQueryValueEx(hKey, TEXT("ProductType"),

            NULL, NULL, (LPBYTE)szProductType, &dwBufLen);

         RegCloseKey( hKey );

 

         if( (lRet != ERROR_SUCCESS)||

             (dwBufLen >BUFSIZE*sizeof(TCHAR)) )

            return FALSE;

 

         if ( lstrcmpi(TEXT("WINNT"), szProductType) == 0 )

            printf("Workstation " );

         if ( lstrcmpi(TEXT("LANMANNT"), szProductType) == 0 )

            printf( "Server" );

         if ( lstrcmpi(TEXT("SERVERNT"), szProductType) == 0 )

            printf( "AdvancedServer " );

         printf( "%d.%d ",osvi.dwMajorVersion, osvi.dwMinorVersion );

      }

 

      // Display service pack (ifany) and build number.

 

      if( osvi.dwMajorVersion == 4&&

          lstrcmpi(osvi.szCSDVersion, TEXT("Service Pack 6") ) == 0 )

      {

         HKEY hKey;

         LONG lRet;

 

         // Test for SP6 versusSP6a.

         lRet = RegOpenKeyEx(HKEY_LOCAL_MACHINE,

           TEXT("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\"

                "Hotfix\\Q246009"), 0, KEY_QUERY_VALUE, &hKey );

         if( lRet == ERROR_SUCCESS )

            printf( "ServicePack 6a (Build %d)\n",

            osvi.dwBuildNumber &0xFFFF );        

         else // Windows NT 4.0prior to SP6a

         {

            _tprintf( TEXT("%s(Build %d)\n"),

               osvi.szCSDVersion,

               osvi.dwBuildNumber & 0xFFFF);

         }

 

         RegCloseKey( hKey );

      }

      else // not Windows NT 4.0

      {

         _tprintf( TEXT("%s(Build %d)\n"),

            osvi.szCSDVersion,

            osvi.dwBuildNumber &0xFFFF);

      }

 

      break;

 

      // Test for the WindowsMe/98/95.

      caseVER_PLATFORM_WIN32_WINDOWS:

 

      if (osvi.dwMajorVersion == 4&& osvi.dwMinorVersion == 0)

      {

          printf ("MicrosoftWindows 95 ");

          if(osvi.szCSDVersion[1]=='C' || osvi.szCSDVersion[1]=='B')

             printf("OSR2" );

      }

 

      if (osvi.dwMajorVersion == 4&& osvi.dwMinorVersion == 10)

      {

          printf ("MicrosoftWindows 98 ");

          if (osvi.szCSDVersion[1]=='A' || osvi.szCSDVersion[1]=='B')

             printf("SE " );

      }

 

      if (osvi.dwMajorVersion == 4&& osvi.dwMinorVersion == 90)

      {

          printf ("MicrosoftWindows Millennium Edition\n");

      }

      break;

 

      case VER_PLATFORM_WIN32s:

 

      printf ("MicrosoftWin32s\n");

      break;

   }

   return TRUE;

}

 

Send commentsabout this topic to Microsoft

Build date:8/15/2007

 =============================================================

Getting System Information

The following example uses the GetComputerNameGetUserNameGetSystemDirectoryGetWindowsDirectory, andExpandEnvironmentStrings functions to get information that describes the system configuration.

C++
#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 32767void printError( TCHAR* msg );void main( ){  DWORD i;  TCHAR  infoBuf[INFO_BUFFER_SIZE];  DWORD  bufCharCount = INFO_BUFFER_SIZE;   // Get and display the name of the computer.   bufCharCount = INFO_BUFFER_SIZE;  if( !GetComputerName( infoBuf, &bufCharCount ) )    printError( TEXT("GetComputerName") );   _tprintf( TEXT("\nComputer name:      %s"), infoBuf );    // Get and display the user name.   bufCharCount = INFO_BUFFER_SIZE;  if( !GetUserName( infoBuf, &bufCharCount ) )    printError( TEXT("GetUserName") );   _tprintf( TEXT("\nUser name:          %s"), infoBuf );    // Get and display the system directory.   if( !GetSystemDirectory( infoBuf, INFO_BUFFER_SIZE ) )    printError( TEXT("GetSystemDirectory") );   _tprintf( TEXT("\nSystem Directory:   %s"), infoBuf );    // Get and display the Windows directory.   if( !GetWindowsDirectory( infoBuf, INFO_BUFFER_SIZE ) )    printError( TEXT("GetWindowsDirectory") );   _tprintf( TEXT("\nWindows Directory:  %s"), infoBuf );    // Expand and display a few environment variables.   _tprintf( TEXT("\n\nSmall selection of Environment Variables:") );   for( i = 0; i < ENV_VAR_STRING_COUNT; ++i )  {    bufCharCount = ExpandEnvironmentStrings(envVarStrings[i], infoBuf,        INFO_BUFFER_SIZE );     if( bufCharCount > INFO_BUFFER_SIZE )      _tprintf( TEXT("\n\t(Buffer too small to expand: \"%s\")"),               envVarStrings[i] );    else if( !bufCharCount )      printError( TEXT("ExpandEnvironmentStrings") );    else      _tprintf( TEXT("\n   %s"), infoBuf );  }  _tprintf( TEXT("\n\n"));}void printError( TCHAR* msg ){  DWORD eNum;  TCHAR sysMsg[256];  TCHAR* p;  eNum = GetLastError( );  FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM |          FORMAT_MESSAGE_IGNORE_INSERTS,         NULL, eNum,         MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),         sysMsg, 256, NULL );  // Trim the end of the line and terminate it with a null  p = sysMsg;  while( ( *p > 31 ) || ( *p == 9 ) )    ++p;  do { *p-- = 0; } while( ( p >= sysMsg ) &&                          ( ( *p == '.' ) || ( *p < 33 ) ) );  // Display the message  _tprintf( TEXT("\n\t%s failed with error %d (%s)"), msg, eNum, sysMsg );}

 

 https://msdn.microsoft.com/en-us/library/windows/desktop/ms724426(v=vs.85).aspx

=============================================


Getting the System Version

The following example uses the Version API Helper functions to determine the version of the current operating system, if it is a Server or Client release, and then displays this information to the console. If compatibility mode is in effect, the example displays the operating system selected for application compatibility.

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.

C++
#include <windows.h>#include <stdio.h>#include <VersionHelpers.h>int __cdeclwmain(    __in int argc,     __in_ecount(argc) PCWSTR argv[]    ){    UNREFERENCED_PARAMETER(argc);    UNREFERENCED_PARAMETER(argv);    if (IsWindowsXPOrGreater())    {        printf("XPOrGreater\n");    }    if (IsWindowsXPSP1OrGreater())    {        printf("XPSP1OrGreater\n");    }    if (IsWindowsXPSP2OrGreater())    {        printf("XPSP2OrGreater\n");    }    if (IsWindowsXPSP3OrGreater())    {        printf("XPSP3OrGreater\n");    }    if (IsWindowsVistaOrGreater())    {        printf("VistaOrGreater\n");    }    if (IsWindowsVistaSP1OrGreater())    {        printf("VistaSP1OrGreater\n");    }    if (IsWindowsVistaSP2OrGreater())    {        printf("VistaSP2OrGreater\n");    }    if (IsWindows7OrGreater())    {        printf("Windows7OrGreater\n");    }    if (IsWindows7SP1OrGreater())    {        printf("Windows7SP1OrGreater\n");    }    if (IsWindows8OrGreater())    {        printf("Windows8OrGreater\n");    }    if (IsWindows8Point1OrGreater())    {        printf("Windows8Point1OrGreater\n");    }    if (IsWindows10OrGreater())    {        printf("Windows10OrGreater\n");    }    if (IsWindowsServer())    {        printf("Server\n");    }    else    {        printf("Client\n");    }}

 

 

Updated version

I've included fixes for all the bugs found here in the comments. Also removed the use of the antiquated function tcslen and the Strsafe function StringCchCat which is only supported in XP SP2 and later. This function should work for Windows 2000 through Windows 7.

#include <windows.h>#include <string>#include <sstream>

typedef void (WINAPI *PGNSI)(LPSYSTEM_INFO);typedef BOOL (WINAPI *PGPI)(DWORD, DWORD, DWORD, DWORD, PDWORD);#define PRODUCT_PROFESSIONAL0x00000030#define VER_SUITE_WH_SERVER0x00008000

bool windowsVersionName(wchar_t* str, int bufferSize){ OSVERSIONINFOEX osvi; SYSTEM_INFO si; BOOL bOsVersionInfoEx; DWORD dwType; ZeroMemory(&si, sizeof(SYSTEM_INFO)); ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX)); osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); bOsVersionInfoEx = GetVersionEx((OSVERSIONINFO*) &osvi); if(bOsVersionInfoEx == 0)  return false; // Call GetNativeSystemInfo if supported or GetSystemInfo otherwise. PGNSI pGNSI = (PGNSI) GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "GetNativeSystemInfo"); if(NULL != pGNSI)  pGNSI(&si); else GetSystemInfo(&si); // Check for unsupported OS if (VER_PLATFORM_WIN32_NT != osvi.dwPlatformId || osvi.dwMajorVersion <= 4 ) {  return false; } std::wstringstream os; os << L"Microsoft "; // Test for the specific product. if ( osvi.dwMajorVersion == 6 ) {  if( osvi.dwMinorVersion == 0 )  {   if( osvi.wProductType == VER_NT_WORKSTATION )    os << "Windows Vista ";   else os << "Windows Server 2008 ";  }  if ( osvi.dwMinorVersion == 1 )  {   if( osvi.wProductType == VER_NT_WORKSTATION )    os << "Windows 7 ";   else os << "Windows Server 2008 R2 ";  }  PGPI pGPI = (PGPI) GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "GetProductInfo");  pGPI( osvi.dwMajorVersion, osvi.dwMinorVersion, 0, 0, &dwType);  switch( dwType )  {  case PRODUCT_ULTIMATE:   os << "Ultimate Edition";   break;  case PRODUCT_PROFESSIONAL:   os << "Professional";   break;  case PRODUCT_HOME_PREMIUM:   os << "Home Premium Edition";   break;  case PRODUCT_HOME_BASIC:   os << "Home Basic Edition";   break;  case PRODUCT_ENTERPRISE:   os << "Enterprise Edition";   break;  case PRODUCT_BUSINESS:   os << "Business Edition";   break;  case PRODUCT_STARTER:   os << "Starter Edition";   break;  case PRODUCT_CLUSTER_SERVER:   os << "Cluster Server Edition";   break;  case PRODUCT_DATACENTER_SERVER:   os << "Datacenter Edition";   break;  case PRODUCT_DATACENTER_SERVER_CORE:   os << "Datacenter Edition (core installation)";   break;  case PRODUCT_ENTERPRISE_SERVER:   os << "Enterprise Edition";   break;  case PRODUCT_ENTERPRISE_SERVER_CORE:   os << "Enterprise Edition (core installation)";   break;  case PRODUCT_ENTERPRISE_SERVER_IA64:   os << "Enterprise Edition for Itanium-based Systems";   break;  case PRODUCT_SMALLBUSINESS_SERVER:   os << "Small Business Server";   break;  case PRODUCT_SMALLBUSINESS_SERVER_PREMIUM:   os << "Small Business Server Premium Edition";   break;  case PRODUCT_STANDARD_SERVER:   os << "Standard Edition";   break;  case PRODUCT_STANDARD_SERVER_CORE:   os << "Standard Edition (core installation)";   break;  case PRODUCT_WEB_SERVER:   os << "Web Server Edition";   break;  } } if ( osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2 ) {  if( GetSystemMetrics(SM_SERVERR2) )   os <<  "Windows Server 2003 R2, ";  else if ( osvi.wSuiteMask & VER_SUITE_STORAGE_SERVER )   os <<  "Windows Storage Server 2003";  else if ( osvi.wSuiteMask & VER_SUITE_WH_SERVER )   os <<  "Windows Home Server";  else if( osvi.wProductType == VER_NT_WORKSTATION &&   si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_AMD64)  {   os <<  "Windows XP Professional x64 Edition";  }  else os << "Windows Server 2003, ";  // Test for the server type.  if ( osvi.wProductType != VER_NT_WORKSTATION )  {   if ( si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_IA64 )   {    if( osvi.wSuiteMask & VER_SUITE_DATACENTER )     os <<  "Datacenter Edition for Itanium-based Systems";    else if( osvi.wSuiteMask & VER_SUITE_ENTERPRISE )     os <<  "Enterprise Edition for Itanium-based Systems";   }   else if ( si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_AMD64 )   {    if( osvi.wSuiteMask & VER_SUITE_DATACENTER )     os <<  "Datacenter x64 Edition";    else if( osvi.wSuiteMask & VER_SUITE_ENTERPRISE )     os <<  "Enterprise x64 Edition";    else os <<  "Standard x64 Edition";   }   else   {    if ( osvi.wSuiteMask & VER_SUITE_COMPUTE_SERVER )     os <<  "Compute Cluster Edition";    else if( osvi.wSuiteMask & VER_SUITE_DATACENTER )     os <<  "Datacenter Edition";    else if( osvi.wSuiteMask & VER_SUITE_ENTERPRISE )     os <<  "Enterprise Edition";    else if ( osvi.wSuiteMask & VER_SUITE_BLADE )     os <<  "Web Edition";    else os <<  "Standard Edition";   }  } } if ( osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1 ) {  os << "Windows XP ";  if( osvi.wSuiteMask & VER_SUITE_PERSONAL )   os <<  "Home Edition";  else os <<  "Professional"; } if ( osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0 ) {  os << "Windows 2000 ";  if ( osvi.wProductType == VER_NT_WORKSTATION )  {   os <<  "Professional";  }  else   {   if( osvi.wSuiteMask & VER_SUITE_DATACENTER )    os <<  "Datacenter Server";   else if( osvi.wSuiteMask & VER_SUITE_ENTERPRISE )    os <<  "Advanced Server";   else os <<  "Server";  } } // Include service pack (if any) and build number. if(wcslen(osvi.szCSDVersion) > 0) {  os << " " << osvi.szCSDVersion; } os << L" (build " << osvi.dwBuildNumber << L")"; if ( osvi.dwMajorVersion >= 6 ) {  if ( si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_AMD64 )   os <<  ", 64-bit";  else if (si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_INTEL )   os << ", 32-bit"; } wcscpy_s(str, bufferSize, os.str().c_str()); return true; }
oon77777
10/27/2011

Error in code


if(bOsVersionInfoEx != NULL ) return 1;



must be



if(bOsVersionInfoEx != TRUE) return FALSE;

"Updated version" pure C note

This "Updated version" will not work for pure C mode compile.
(Original also does not compile, but all you need is just move line TCHAR buf[80]; to the top of function body)

You do not need to use C++ *streams to get it work on Windows XP < SP2 and Windows 2000.

Just replace StringCchCat with _tcscat_s and StringCchPrintf with _stprintf_s. Keep tchar.h included and remove include to Strsafe.h.



Thats all.
https://msdn.microsoft.com/en-us/library/windows/desktop/ms724429(v=vs.85).aspx


0 0