获取 Windows 操作系统当前的版本号

陪她去流浪 桃子 2016年07月24日 阅读次数:2630

(真是费解,什么时候获取一个系统的版本号竟然会变得如此费劲,我竟然还免不了单独为它写篇文章来记录之。)

以前都是用 GetVersion/GetVersionEx 来获取 Windows 操作系统的版本号,但到了 Windows 10(不知道是不是从这里发源的),在 Visual Studio 中使用这两个函数时,竟然提示已被标记为弃用。。。

我不想去了解太多原因为什么被弃用,我只想说,难道你操作系统还有多个版本号?语言不同会带来版本的不同?无聊!

既然获取版本号有如此之艰难,我还是写个代码片段期望一劳永逸吧。

代码归档了,放在:https://repo.twofei.com/get-windows-version.git

/*
 * get_windows_version
 * 
 * 获取 Windows 操作系统的版本号
 * 采用读取文件版本信息块的方式,能获取到最新操作系统的版本号
 * 
 * 函数如果失败(可能性非常低),返回 4 个 0
 * 所以,由于函数失败的可能性非常低,不用考虑检测函数调用的返回值
 *
 * ~tao @ 2016-06-15 16:36:15
 * VisualStudio 2013 (C++11)
 */

#define _CRT_NON_CONFORMING_SWPRINTFS
#define _CRT_SECURE_NO_WARNINGS

#include <string>
#include <memory>

#include <windows.h>

#pragma comment(lib, "version.lib")

static bool get_windows_version(int intver[4], std::wstring* strver) {
    static wchar_t const * module = L"kernel32.dll";

    bool ok = false;
    int v[4] = {0};

    DWORD size = GetFileVersionInfoSize(module, nullptr);
    if(size) {
        std::unique_ptr<unsigned char[]> info(new unsigned char[size]);
        if(GetFileVersionInfo(module, 0, size, info.get())) {
            VS_FIXEDFILEINFO* pFixedInfo;
            if(VerQueryValue(info.get(), L"\\", (void**)&pFixedInfo, (UINT*)&size)) {
                v[0] = HIWORD(pFixedInfo->dwFileVersionMS);
                v[1] = LOWORD(pFixedInfo->dwFileVersionMS);
                v[2] = HIWORD(pFixedInfo->dwFileVersionLS);
                v[3] = LOWORD(pFixedInfo->dwFileVersionLS);

                ok = true;
            }
        }
    }

    if(intver) {
        memcpy(intver, v, sizeof(v));
    }

    if(strver) {
        wchar_t buf[128];
        swprintf(buf, L"%u.%u.%u.%u", v[0], v[1], v[2], v[3]);
        *strver = buf;
    }

    return ok;
}

int main() {
    int v[4];
    std::wstring s;

    if (get_windows_version(&v[0], &s)) {
        wprintf(L"IntVer: %d.%d.%d.%d\n", v[0], v[1], v[2], v[3]);
        wprintf(L"StrVer: %s\n", s.c_str());
    }
    else {
        wprintf(L"failed.\n");
    }

    return 0;
}

标签:代码片段 · WinAPI