How to determine Windows version in future-proof way

前端 未结 1 1067
耶瑟儿~
耶瑟儿~ 2020-12-03 07:08

I noticed that GetVersionEx() is declared deprecated. Worse yet, for Windows 8.1 (and presumably future releases) the version number is limited by the application manifest.

相关标签:
1条回答
  • 2020-12-03 07:59

    MSDN has an example showing how to use the (useless for your scenario) version helper functions, but in the introduction is the following:

    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\\ProductVersion subblock of the file version information.

    As of right now, neither the GetFileVersionInfo nor VerQueryValue function are deprecated.

    Example

    This will extract the product version from kernel32.dll and print it to the console:

    #pragma comment(lib, "version.lib")
    
    static const wchar_t kernel32[] = L"\\kernel32.dll";
    wchar_t *path = NULL;
    void *ver = NULL, *block;
    UINT n;
    BOOL r;
    DWORD versz, blocksz;
    VS_FIXEDFILEINFO *vinfo;
    
    path = malloc(sizeof(*path) * MAX_PATH);
    if (!path)
        abort();
    
    n = GetSystemDirectory(path, MAX_PATH);
    if (n >= MAX_PATH || n == 0 ||
        n > MAX_PATH - sizeof(kernel32) / sizeof(*kernel32))
        abort();
    memcpy(path + n, kernel32, sizeof(kernel32));
    
    versz = GetFileVersionInfoSize(path, NULL);
    if (versz == 0)
        abort();
    ver = malloc(versz);
    if (!ver)
        abort();
    r = GetFileVersionInfo(path, 0, versz, ver);
    if (!r)
        abort();
    r = VerQueryValue(ver, L"\\", &block, &blocksz);
    if (!r || blocksz < sizeof(VS_FIXEDFILEINFO))
        abort();
    vinfo = (VS_FIXEDFILEINFO *) block;
    printf(
        "Windows version: %d.%d.%d",
        (int) HIWORD(vinfo->dwProductVersionMS),
        (int) LOWORD(vinfo->dwProductVersionMS),
        (int) HIWORD(vinfo->dwProductVersionLS));
    free(path);
    free(ver);
    
    0 讨论(0)
提交回复
热议问题