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

Raymond Chen

Raymond

Getting the computer’s serial number used to be an arduous task of getting the system firmware table, and then manually parsing the SMBIOS information looking for the serial number.

Windows 8 introduced the Windows.System.Profile.System­Manufacturers.SmbiosInformation runtime class which parses out the serial number for you.

We can do this the easy way or the hard way. Let’s do it the hard way.

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

#include <windows.h>
#include <wrl/client.h>
#include <wrl/wrappers/corewrappers.h>
#include <windows.system.profile.systemmanufacturers.h>
#include <roapi.h>
#include <stdio.h> // Horrors! Mixing C and C++!

namespace WRL = Microsoft::WRL;
namespace spsm = ABI::Windows::System::Profile::SystemManufacturers;

using Microsoft::WRL::Wrappers::HString;
using Microsoft::WRL::Wrappers::HStringReference;

int __cdecl wmain(int, wchar_t**)
{
    CCoInitialize init;

    WRL::ComPtr<spsm::ISmbiosInformationStatics> statics;
    HString serialNumber;
    RoGetActivationFactory(HStringReference(
        RuntimeClass_Windows_System_Profile_SystemManufacturers_SmbiosInformation)
                             .Get(), IID_PPV_ARGS(&statics));
    statics->get_SerialNumber(serialNumber.GetAddressOf());
    wprintf(L"Serial number = %ls\n", serialNumber.GetRawBuffer(nullptr));

    return 0;
}

Before building, right-click the Project in Visual Studio and select Properties. From the dialog, make the following change:

  • Configuration Properties, Linker, Inputs, Additional Dependencies: add windowsapp.lib.

Okay, now you can build and run the program, and it’ll tell you your system’s serial number as recorded in the SMBIOS.

And fortunately you didn’t have to go parsing the system firmware table yourself.

This series repeats the above exercise in desktop apps in various languages, each one getting easier than the previous one. Next up is C++/CX.

(The secret goal of this series is to capture how you need to configure your project to get it to build.)

Raymond Chen
Raymond Chen

Follow Raymond   

0 comments

Comments are closed.