Windows: Get Version Resource

To get version string from current module’s version resource I wrote the following function.

// "true" for full version like "1.2.3.4", otherwise "1.2"
std::wstring load_version(bool full = true);

And implementation is below. Note that you need to link with Version.lib which can be specified using this nice pragma.

// Version.lib is required to call ::GetFileVersionInfoSize etc.
#pragma comment(lib, "Version.lib")

std::wstring load_version(bool full)
{
    wstring r;

    // get current module's filename
    TCHAR szVersionFile[MAX_PATH];
    ::GetModuleFileName(nullptr, szVersionFile, MAX_PATH);

    DWORD hVer = 0;
    DWORD verSize = ::GetFileVersionInfoSize(szVersionFile, &hVer);
    LPSTR verData = new char[verSize];

    if (::GetFileVersionInfo(szVersionFile, hVer, verSize, verData))
    {
        LPBYTE lpBuffer = 0;
        UINT size = 0;
        if (VerQueryValue(verData, L"\\", (VOID FAR * FAR*) & lpBuffer, &size))
        {
            if (size)
            {
                VS_FIXEDFILEINFO* verInfo = (VS_FIXEDFILEINFO*)lpBuffer;
                if (verInfo->dwSignature == 0xfeef04bd)
                {
                    // Doesn't matter if you are on 32 bit or 64 bit,
                    // DWORD is always 32 bits, so first two revision numbers
                    // come from dwFileVersionMS, last two come from dwFileVersionLS

                    r = to_wstring((verInfo->dwFileVersionMS >> 16) & 0xffff) + L"." +
                        to_wstring((verInfo->dwFileVersionMS >> 0) & 0xffff);

                    if (full)
                    {
                        r += L"." +
                            to_wstring((verInfo->dwFileVersionLS >> 16) & 0xffff) + L"." +
                            to_wstring((verInfo->dwFileVersionLS >> 0) & 0xffff);
                    }
                }
            }
        }

        delete[] verData;
    }

    return r;
}

Have a question⁉ Contact me.


cpp

203 Words

2021-07-18