January 8th, 2018

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

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:

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments

Discussion are closed.