本文通过多种方法获取、判断操作系统版本
获取系统版本号的有个GetVersion()、GetVersionEx()函数,判断操作系统版本有VerifyVersionInfo()
以上三种函数在Win7以上的系统变得不灵了,获取到的都是:6.2。
对于使用VC、VS版本比较低的用户,可能并不支持 versionhelpers.h,即并不支持以下等函数直接来判断。
IsWindows7SP1OrGreater
IsWindows10OrGreater
详细请参考:https://docs.microsoft/zh-cn/windows/win32/sysinfo/version-helper-apis
一、GetVersion()、GetVersionEx()函数获取操作系统版本
#include <stdio.h>
#include <windows.h>
int main(void)
{
DWORD dwVersion = 0;
DWORD dwMajorVersion = 0;
DWORD dwMinorVersion = 0;
DWORD dwBuild = 0;
dwVersion = GetVersion();
// Get the Windows version.
dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
// Get the build number.
if (dwVersion < 0x80000000)
dwBuild = (DWORD)(HIWORD(dwVersion));
printf("GetVersion() : %d.%d (%d)\n",
dwMajorVersion,
dwMinorVersion,
dwBuild);
// GetVersionEx()
OSVERSIONINFOEX os;
os.dwOSVersionInfoSize=sizeof(OSVERSIONINFOEX);
if(GetVersionEx((OSVERSIONINFO *)&os))
printf("GetVersionEx() : %d.%d\n",os.dwMajorVersion,os.dwMinorVersion);
return 0;
}
二、VerifyVersionInfo判断操作系统版本
//VS2008 编译测试通过
#include "stdafx.h"
#include <stdio.h>
#include <windows.h>
/*
对Win7以上的系统不大管用
*/
int main(void)
{
OSVERSIONINFOEXW osvi = {0};
DWORDLONG dwlConditionMask = 0;
ZeroMemory(&osvi, sizeof(osvi));
osvi.dwOSVersionInfoSize = sizeof(osvi);
osvi.dwMajorVersion = 6; //Win主版本号
osvi.dwMinorVersion = 1; //次版本号
VER_SET_CONDITION(dwlConditionMask, VER_MAJORVERSION, VER_EQUAL);
VER_SET_CONDITION(dwlConditionMask, VER_MINORVERSION, VER_EQUAL);
//判断返回值是否为win7,返回真为win7,否则返回0
if( VerifyVersionInfo(&osvi, VER_MAJORVERSION | VER_MINORVERSION, dwlConditionMask) )
printf("Win7\n");
else
printf("不是Win7\n");
return 0;
}
三、通过 GetProcAddress 来获取操作系统版本号(推荐)
#include <stdio.h>
#include <windows.h>
/*
本例代码经过VC6.0下编译通过,并在XP、Win7、Win10上运行成功并获取到正确的系统版本号
*/
int main(void)
{
typedef void(__stdcall*NTPROC)(DWORD*, DWORD*, DWORD*);
HINSTANCE hinst = LoadLibrary(TEXT("ntdll.dll"));//加载DLL
NTPROC GetNtVersionNumbers = (NTPROC)GetProcAddress(hinst, "RtlGetNtVersionNumbers");//获取函数地址
DWORD dwMajor, dwMinor, dwBuildNumber;
GetNtVersionNumbers(&dwMajor, &dwMinor, &dwBuildNumber);
printf("Windows版本 : %d.%d\n",dwMajor,dwMinor);
if (dwMajor == 10 && dwMinor == 0)
{
printf("Win10\n");
}
if (dwMajor == 6 && dwMinor == 1)
{
printf("Win7\n");
}
return 0;
}
四、Windows各系统版本列表
操作系统 | 版本号 |
---|---|
Windows 10 | 10.0 * |
Windows Server 2019 | 10.0 * |
Windows Server 2016 | 10.0 * |
Windows 8.1 | 6.3 * |
Windows Server 2012 R2 | 6.3 * |
Windows 8 | 6.2 |
Windows Server 2012 | 6.2 |
Windows 7 | 6.1 |
Windows Server 2008 R2 | 6.1 |
Windows Server 2008 | 6.0 |
Windows Vista | 6.0 |
Windows Server 2003 R2 | 5.2 |
Windows Server 2003 | 5.2 |
Windows XP 64位版本 | 5.2 |
Windows XP | 5.1 |
Windows 2000 | 5.0 |
详细请参考:https://docs.microsoft/zh-cn/windows/win32/sysinfo/operating-system-version