How do I get the computer’s serial number? Consuming Windows Runtime classes in desktop apps, part 3: C++/WinRT

Raymond Chen

Continuing our series on getting the computer’s serial number in desktop apps in various languages, next up is C++/WinRT.

From Visual Studio, create a new C++ Console Application that goes like this:

#include <windows.h>
#include <stdio.h> // Horrors! Mixing C and C++!

#include "winrt/Windows.System.Profile.SystemManufacturers.h"

int __cdecl wmain(int, char**)
{
  winrt::init_apartment();
  {
    auto serialNumber = winrt::Windows::System::Profile::
         SystemManufacturers::SmbiosInformation::SerialNumber();
    wprintf(L"Serial number = %ls\n", serialNumber.c_str());
  }

  // The last thread cleans up before uninitializing for good.
  winrt::clear_factory_cache();
  winrt::uninit_apartment();

  return 0;
}

Before building, prepare the project as follows:

  • Right-click the Project in Visual Studio and select Manage NuGet packages. Click the Browse tab and search for “cppwinrt”, then click Install.
  • Right-click the Project in Visual Studio and select Properties. Configure the project as follows:
    • Configuration Properties, C/C++ Language C++ Language Standard: Set to ISO C++17 Standard (/std:c++17).
    • Configuration Properties, Linker, Inputs, Additional Dependencies: add windowsapp.lib.

Okay, now you can build and run the program.

C++/WinRT lets you consume Windows Runtime objects without requiring any nonstandard language extensions. It’s all standard C++17.

So that’s native code. Next up is C#.

Bonus chatter:

0 comments

Discussion is closed.

Feedback usabilla icon