January 4th, 2018

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

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.)

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.