我正在尝试检查操作系统是否是域 Controller (VER_NT_DOMAIN_CONTROLLER)。使用 GetVersionEx 使用OSVERSIONINFOEX函数很容易做到这一点。但是GetVersionEx的MSDN页面建议不要使用此功能,并且我们在Visual Studio 2015中看到警告。

是否有任何较新的API可以提供此信息?我知道有更新的Version Helper functions可以告诉它是哪种操作系统,但是我没有看到任何有关获取产品类型的信息。

最佳答案

我查看了NodeJS / libuv solved the OS version number的方式,以便自己弄清楚该如何做。他们会使用RtlGetVersion()(如果可用),否则会退回到GetVersionEx()

我想出的解决方案是:

// Windows10SCheck.cpp : This file contains the 'main' function. Program execution begins and ends there.
//

#include "pch.h"
#include <iostream>
#include <Windows.h>

// Function to get the OS version number
//
// Uses RtlGetVersion() is available, otherwise falls back to GetVersionEx()
bool getosversion(OSVERSIONINFOEX* osversion) {
    NTSTATUS(WINAPI *RtlGetVersion)(LPOSVERSIONINFOEX);
    *(FARPROC*)&RtlGetVersion = GetProcAddress(GetModuleHandleA("ntdll"), "RtlGetVersion");

    if (RtlGetVersion != NULL)
    {
        // RtlGetVersion uses 0 (STATUS_SUCCESS)
        // as return value when succeeding
        return RtlGetVersion(osversion) == 0;
    }
    else {
        // GetVersionEx was deprecated in Windows 10
        // Only use it as fallback
        #pragma warning(suppress : 4996)
        return GetVersionEx((LPOSVERSIONINFO)osversion);
    }
}

int main()
{
    OSVERSIONINFOEX osinfo;
    osinfo.dwOSVersionInfoSize = sizeof(osinfo);
    osinfo.szCSDVersion[0] = L'\0';

    if (!getosversion(&osinfo)) {
        std::cout << "Failed to get OS version\n";
    }

    std::cout << osinfo.dwMajorVersion << "." << osinfo.dwMinorVersion << "." << osinfo.dwBuildNumber << "\n";

    DWORD dwReturnedProductType = 0;

    if (!GetProductInfo(osinfo.dwMajorVersion, osinfo.dwMinorVersion, 0, 0, &dwReturnedProductType)) {
        std::cout << "Failed to get product info\n";
    }

    std::cout << "Product type: " << std::hex << dwReturnedProductType;

}

我的机器上的输出:
10.0.15063
Product type: 1b

产品类型的含义可以在以下位置找到:GetProductInfo function | Microsoft Docs

10-08 03:55