備忘録

備忘録

C++でWindowsのバージョンを取得する

Ⅰ. はじめに

タイトルの通り「C++Windowsのバージョンを取得する」方法です。

Ⅱ. サンプルプログラム

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

typedef LONG NTSTATUS, *PNTSTATUS;
#define STATUS_SUCCESS (0x00000000)
#define OS_ANYSERVER 29

typedef NTSTATUS(WINAPI* RtlGetVersionPtr)(PRTL_OSVERSIONINFOW lpVersionInformation);
typedef BOOL (WINAPI* IsOSPtr)(DWORD dwOS);

RTL_OSVERSIONINFOW GetRealOSVersion()
{
  auto versionInfo = RTL_OSVERSIONINFOW{ sizeof(RTL_OSVERSIONINFOW) };
  HMODULE hModule = GetModuleHandle(L"ntdll.dll");

  if (hModule)
  {
    auto RtlGetVersion = (RtlGetVersionPtr)GetProcAddress(hModule, "RtlGetVersion");
    if (RtlGetVersion != nullptr)
    {
      if (STATUS_SUCCESS == RtlGetVersion(&versionInfo))
      {
        return versionInfo;
      }
    }
  }

  return versionInfo;
}

BOOL IsWindowsServer()
{
  HMODULE hModule = LoadLibrary(L"Shlwapi.dll");

  if (hModule)
  {
    auto IsOS = (IsOSPtr)GetProcAddress(hModule, "IsOS");
    if (IsOS != nullptr)
    {
      return IsOS(OS_ANYSERVER);
    }
  }

  return FALSE;
}

int main()
{
  auto version = GetRealOSVersion();

  std::cout << "MajorVersion: " << version.dwMajorVersion << std::endl;
  std::cout << "BuildNumber: " << version.dwBuildNumber << std::endl;
  
  if (version.dwMajorVersion == 10 && !IsWindowsServer())
  {
    // https://en.wikipedia.org/wiki/Windows_10_version_history#Rings
    if (version.dwBuildNumber >= 16299)
    {
      std::cout << "Windows 10 1709(Fall Creators Update)" << std::endl;
    }
    else if (version.dwBuildNumber >= 15063)
    {
      std::cout << "Windows 10 1703(Creators Update)" << std::endl;
    }
    else if (version.dwBuildNumber >= 14393)
    {
      std::cout << "Windows 10 1607(Anniversary Update)" << std::endl;
    }
    else if (version.dwBuildNumber >= 10586)
    {
      std::cout << "Windows 10 1511(November Update)" << std::endl;
    }
  }
  
  return 0;
}

Ⅲ. 実行結果

f:id:kagasu:20171126142109p:plain

  • Windows 10 1709 Fall Creators Update

f:id:kagasu:20171126142041p:plain