获取操作系统的名称和版本

时间:2018-08-12 10:33:14

标签: c windows operating-system version

如果在cmd中键入ver,则会得到类似以下内容的信息:

Microsoft Windows [Version 10.0.17192.162]

无论如何,我是否可以访问此信息以在我的C程序中使用?我需要找到一个人正在运行的Windows版本。我已签出SYSTEM_INFO:

typedef struct _SYSTEM_INFO {
  union {
    DWORD  dwOemId;
    struct {
      WORD wProcessorArchitecture;
      WORD wReserved;
    };
  };
  DWORD     dwPageSize;
  LPVOID    lpMinimumApplicationAddress;
  LPVOID    lpMaximumApplicationAddress;
  DWORD_PTR dwActiveProcessorMask;
  DWORD     dwNumberOfProcessors;
  DWORD     dwProcessorType;
  DWORD     dwAllocationGranularity;
  WORD      wProcessorLevel;
  WORD      wProcessorRevision;
} SYSTEM_INFO;

和OSVERSIONINFO

typedef struct _OSVERSIONINFOA {
  DWORD dwOSVersionInfoSize;
  DWORD dwMajorVersion;
  DWORD dwMinorVersion;
  DWORD dwBuildNumber;
  DWORD dwPlatformId;
  CHAR  szCSDVersion[128];
} OSVERSIONINFOA, *POSVERSIONINFOA, *LPOSVERSIONINFOA;

但都不包含完整的版本信息。

此外,要检索操作系统的名称,除了进行#ifdef __WIN32检查以外,还有其他方法吗?

2 个答案:

答案 0 :(得分:0)

对于<= Windows 8.1,可能要使用API​​函数WinVersionWinVersionEx

对于较新的Windows版本,请使用Version Helper functions

答案 1 :(得分:0)

如果要获得与cmd相同的结果,可以运行下一个代码:

ULONG GetVersionRevision(PULONG Ubr)
{
    HKEY hKey;
    ULONG dwError = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", 0, KEY_READ|KEY_WOW64_64KEY, &hKey);
    if (dwError == NOERROR)
    {
        ULONG Type;
        ULONG cb = sizeof(ULONG);
        dwError = RegQueryValueExW(hKey, L"UBR", 0, &Type, (PBYTE)Ubr, &cb);

        if (dwError == NOERROR)
        {
            if (Type != REG_DWORD || cb != sizeof(ULONG))
            {
                dwError = ERROR_GEN_FAILURE;
            }
        }
        RegCloseKey(hKey);
    }

    return dwError;
}

    ULONG M, m, b, Ubr;
    RtlGetNtVersionNumbers(&M, &m, &b);

    if (GetVersionRevision(&Ubr) == NOERROR)
    {
        DbgPrint("[Version %u.%u.%u.%u]\n", M, m, b & 0xffff, Ubr);
    }
    else
    {
        DbgPrint("[Version %u.%u.%u]\n", M, m, b & 0xffff);
    }