January 5th, 2018

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

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

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

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

[Platform::STAThread]
int __cdecl wmain(int, wchar_t**)
{
  CCoInitialize init;

  auto serialNumber = Windows::System::Profile::SystemManufacturers::
                       SmbiosInformation::SerialNumber;
  wprintf(L"Serial number = %ls\n", serialNumber->Data());

  return 0;
}

Before building, right-click the Project in Visual Studio and select Properties, and then make these changes:

  • Configuration Properties, C/C++, General, Additional #using Directories: Add these two directories, adjusting as appropriate for where you installed Visual Studio and the Windows SDK.
    • C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcpackages (so the compiler can find platform.winmd)
    • C:\Program Files (x86)\Windows Kits\10\UnionMetadata\10.0.16299.0 (so the compiler can find windows.winmd
  • Configuration Properties, C/C++, General, Consume Windows Runtime Extension: Set to Yes (/ZW).
  • Configuration Properties, C/C++, Code Generation, Enable Minimal Rebuild: Set to No (/Gm-).
  • Configuration Properties, Linker, Inputs, Additional Dependencies: add windowsapp.lib.

Okay, now you can build and run the program.

Consuming Windows Runtime objects in C++/CX is more convenient than accessing them raw, but it is a nonstandard Microsoft extension.

You don’t have to build your entire application in C++/CX. You can write part of it in plain C++, and part of it in C++/CX, and the link the two pieces together. The Casting page on MSDN explains how to convert between a hat-pointer and a regular pointer.

Okay, so setting up the project was kind of ugly, but that’s okay, because things will get better before they get better. Up next is C++/WinRT.

¹ There are two copies of windows.winmd, a good one in the directory I gave above, and a bad one in the directory Union­Metadata\Facade. If you use the bad one, you get an internal compiler error. Larry Osterman tried to explain to me what the bad copy in Facade was for, but all I heard was the wah-wah of Charlie Brown’s teacher.

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.