Petzold Book Blog - Programming Windows 6th Edition for the C++ Programmer


Charles Petzold on writing books, reading books, and exercising the internal UTM

Recent Entries
< PreviousBrowse the ArchivesNext >
Subscribe to the RSS Feed

Programming Windows 6th Edition for the C++ Programmer

May 30, 2012
Roscoe, N.Y.

When I first announced that there would be a 6th edition of Programming Windows focusing on writing Metro style applications for Windows 8, a lively debate ensued on what language I should use, with the majority split pretty equally between C# and C++/CX (which is C++ with the Component Extensions for accessing the Windows Runtime).

I decided to use C# exclusively in the pages of the book, but to translate the sample programs in the book into C++/CX.

If you want to examine these sample programs before you buy the book, you can do so. Just go to the Programming Windows 6th edition page on the O'Reilly web site and click the Companion Content link at the right. It's a ZIP file that has all 81 sample programs from the first 7 chapters of the book in both C# and C++.

But C++ programmers might get more out of the code if they buy the book as well. One reason I chose C# is that I figured C++ programmers can successfully read C# better than C# programmers can read C++!

For the most part, Windows 8 Metro style applications written in C# and C++ are fairly similar. They both involve XAML files and access very many of the same classes and structures that comprise the Windows Runtime (WinRT). These classes are defined in the namespaces that begin with Windows and encompass all the user-interface elements, graphics, media, and so forth.

For lower-level tasks, the C# programmer uses a subset of .NET (namespaces that begin with System) while the C++ programmer uses the familiar C runtime library as well as the new Platform namespaces.

I am sorry to say that in the Windows 8 world, programming languages are not created equal. Although I haven't explored the HTML5 / JavaScript approach to programming a Windows 8 application, I have been told that there are some user-interface objects available from JavaScript but not C# and C++. C# programs can access XML files with more agility than C++. But the most serious difference (in my view) involves Win32 and COM functions, including DirectX. These are only available from C++.

In short, if you want to code some sound or 3D graphics in a Metro style application, you'll need to use C++ for that job. As a C# guy, this does not make me happy. But it also tells me that I really need to maintain a fluency in C++ so that I can use the language when I need to.

Prior to about 5 weeks ago, the last time I spent any substantial time with C++ was the late-1990s when I was working on a book about bitmap graphics programming for Windows. I had decided to structure the book around extensions to MFC for bitmap support, and I was slowly discovering how awkward it was to write extensions to MFC. (That book was never completed.)

C++ has evolved some since that time, and the Component Extensions make it so that you might not even recognize the language! Here are a few things I learned in the process of converting the code in the book. (Some of this might be incomprehensible if you have no experience with .NET or the Windows Runtime.)

Here's how to instantiate and initialize a Windows 8 TextBlock in C#:

TextBlock txtblk = new TextBlock();
txtblk.Text = "Hello, Windows 8!";
txtblk.FontFamily = new FontFamily("Times New Roman");
txtblk.FontSize = 96;
txtblk.FontStyle = FontStyle.Italic;
txtblk.Foreground = new SolidColorBrush(Colors.Yellow);
txtblk.HorizontalAlignment = HorizontalAlignment.Center;
txtblk.VerticalAlignment = VerticalAlignment.Center;

That's right out of the HelloCode sample in Chapter 1. Here's the equivalent code in C++/CX:

TextBlock^ txtblk = ref new TextBlock();
txtblk->Text = "Hello, Windows 8!"; 
txtblk->FontFamily = ref new Windows::UI::Xaml::Media::FontFamily("Times New Roman");
txtblk->FontSize = 96;
txtblk->FontStyle = Windows::UI::Text::FontStyle::Italic;
txtblk->Foreground = ref new SolidColorBrush(Colors::Yellow);
txtblk->HorizontalAlignment = Windows::UI::Xaml::HorizontalAlignment::Center;
txtblk->VerticalAlignment = Windows::UI::Xaml::VerticalAlignment::Center;

Notice that ref new is applied to TextBlock rather than just new. The customary new keyword allocates the object in the local heap and returns a pointer. The ref new instead returns a handle, which is a reference to the object rather than the pointer itself. These references are counted so that the object can be automatically deleted when there are no longer any references to it.

The ref new operator is not the same as the C++/CLI gcnew operator. The gcnew operator is for .NET managed types. The Windows Runtime types are unmanaged and your C++/CX code is also unmanaged.

Because ref new performs a reference-counted allocation and returns a handle, the returned object cannot be stored in a normal pointer variable, and that's the reason for the hat (^) on TextBlock, which indicates a handle of that type. All WinRT classes are of this nature, and you can create your own reference-counted classes with the ref keyword.

In the HelloCode sample, this code snippet is called in the constructor of a Page derivative. Notice in the C++ snippet that the FontFamily class and some enumerations (FontStyle, HorizontalAlignment, and VerticalAlignment) need to be fully qualified with the namespace name. This is because they are being referenced within an object that derives from a class that includes properties with these same names. In resolving these names, the C# compiler gives higher priority to external classes and enumerations, while the C+ compiler gives higher priority to property names, so the namespaces are required to clarify your intention.

Structures that are part of the Windows Runtime are defined as they are in C, which means they don't have non-data members. However, non-data members of WinRT structures are visible when coding in C#. For example, in C# you can use the static Color.FromArgb method to create a Color value. In C++ you use instead the static ColorHelper::FromArgb method. ColorHelper is a class and FromArgb returns a Color value.

The C# string data type is an alias for the String class in the System namespace. In C++ you use a String class defined in the Platform namespace that encapsulates an immutable Unicode string. It's basically a wrapper around a const wchar_t * object. While the C# String class has plenty of amenities for working with strings, the C++ String class does not. To perform string operations in C++, you must first extract the underlying wchar_t pointer using the Data method. For example,

String^ str = "hello";
const wchar_t* text = str->Data();

You can then use standard C string functions on text, or make a copy for manipulation. To convert back to a Windows Runtime String ^ type, use a constructor:

String^ str2 = ref new Platform::String(text);

If you need to format numbers and other objects for display purposes in C++, you'll use swprintf or swprintf_s and then create a String ^ for passing to a Windows Runtime type such as TextBlock.

In almost all cases for the sample programs in my book, the XAML files in the C# and C++ versions are identical. However, if you need to perform numeric formatting in a data binding, you'll need to write a formatted-string converter (such as the one in Chapter 4 of the book). The C# version will require .NET format specifiers for String.Format while the C++ version requires printf format specifiers. That affects the XAML file.

While I was writing the book I didn't give any consideration to the fact that I'd be translating the programs into C++ at some point. Otherwise, I probably wouldn't have used .NET reflection so much in Chapter 4. The System.Reflection namespace is not available to C++ programs.

In Chapter 4 I used reflection in two ways: to obtain all the static properties of the Colors class for displaying all the named colors, and to construct a class hierarchy starting with the DependencyObject class. In these cases, I didn't feel I was demonstrating .NET reflection so much as using reflection to demonstrate other concepts, so I didn't feel the need to perform reflection in C++. There is apparently a way to do it and there's now a CodePlex project to do it, but instead I wrote a little C# library called ReflectionHelper and then flagged this class library to create a WinMD file, which means that it can be accessed from other Windows Runtime languages. (There are restrictions on libraries of this sort, but that's a topic for another time.)

I suspect that later in the book I might find it necessary to do just the opposite: To create a WinMD library in C++ for use by a C# program.

Generally I use XML serialization to save and load program settings (as in the AppSettings class in the XamlCruncher program in Chapter 7), but the System.Xml.Serialization namespace is not available in C++ so I used ApplicationData::Current->LocalSettings instead. I'm tempted to now use this approach in the C# version of the program.

I couldn't find good examples for defining dependency properties in C++. In C#, DependencyProperty.Register is usually called in a static constructor, but C++/CX doesn't have static constructors. Moreover, in C++ each dependency property requires two TypeName values — one for the type of the class registering the dependency property and one for the type of the property itself — and a private static field for the DependencyProperty object, and a public static property to expose that DependencyProperty object.

I saw one C++ example where DependencyProperty.Register was called the first time the get accessor of the static property was called, but I'm not sure that would work right in all cases. Might not the dependency property need to be registered before the static property was accessed? Answering that question requires knowing Windows Runtime internals. Instead, I called DependencyProperty.Register in the implementation of the static field. The XamlCruncher program has several examples of the format I eventually chose.

I'd like to get some feedback from C++ programmers who buy my book. Is this the next best thing to having a book specifically targetting the C++ programmer? Or is it worthless? Or somewhere in between? (It's a non-trivial amount of work to convert these samples, so if they're worthless, I'd rather spend the time focusing on more C# content in the book.)

Programming Windows, 6th Edition

Special Price through the End of May 2012!

For just $10, you get:

(1) the Consumer Preview ebook right now
(2) the Release Preview ebook in a couple months
(3) the final ebook in November

Programming Windows 6th edition
Programming Windows 6th Edition
Consumer Preview eBook


Hat^ handles are the same syntax for ref new as for gcnew. I haven't been following the news recently so I hadn't noticed that ref new is different from gcnew. Obviously they're both different from old new, but old new wasn't much different from malloc, so that's why old new can still use * while new news need ^. But how does ^ distinguish which new new is which?

— I knew not, Wed, 30 May 2012 19:36:05 -0400

The gcnew operator is part of C++/CLI, which is a managed language in the managed environment of .NET. The ref new operator is part of C++/CX, which is an unmanaged language in the unmanaged environment of the Windows Runtime. You can't be using both gcnew and ref new in the same program, so there's no problem with using the hat symbol for both of them. — Charles


It would seem to me that you're already at a good compromise. A separate book would require that folks would need both books because (as you mentioned) it's difficult to stay in one language in all situations.

However, the C++ examples are needed for those of us who still regularly use native code but would like to pick up Win8 programming. Just my 2 cents.

— Doug Boling, Wed, 30 May 2012 19:48:31 -0400

Thanks, Doug. — Charles

Thanks for converting the samples to C++ (well, it's not really C++, it C++/CX) I know C++ since Win3, but haven't used C++/CX (yet).

This is the reason why I just bought your book. So, porting the samples to C++ make you at least earn a couple of $ ;)

I guess that "txtBlk->FontSize = 16" is in fact a COM call (is it?) Another point which makes me uncomfortable with C++/CX is that we have to use foreign data types (the Platform types). How do these types rely with standard types (C++ and STL types)? I would really like a chapter in your book about these C++/CX topics. I haven't seen anything about them on the web yet.

I'm OK with chapter 4 being only for C#. Different languages are for different purposes. You don't use C# the same way you use C++/CX (I guess). BTW your opinion about this would be invaluable too! IMHO, DirectX only available in C++ makes sense. Different languages, different purposes. C# = ease of coding. C++ = performance (is it, with WinRT?)

Pierre MF, Wed, 30 May 2012 19:59:12 -0400

The CX part of C++/CX only comes into play when you're interacting with the Windows Runtime. When you're not interacting with the API, you can be using standard C or C++ entirely. When you're ready to call the Windows Runtime, only then (for example) do you need to convert your wchar_t * to a String ^ with ref new. — Charles

OK, I see that C++/CX is a different language from C++/CLI, just as C++/CLI is different from C++. I see that ^ handles in C++/CX cannot reference managed objects the way that ^ handles in C++/CLI did. But then it seems that C++/CX can't interoperate with C# the way that C++/CLI did. I think I don't quite see sharp enough, but what am I missing?

— I knew not, Wed, 30 May 2012 20:44:57 -0400

> it seems that C++/CX can't interoperate with C# the way that C++/CLI did

That is true. In .NET, you can easily create a DLL that is fully accessible by any other .NET language. With the Windows Runtime, libraries that are usable by other languages must be of the WinMD type, and this involves some restrictions on the library's public interfaces. — Charles

So the author of a famous book that used Win32 APIs (before its 6th edition) now prefers to use C#, and the author of a famous book on the .Net Compact Framework now prefers to use C++?

— The new gifts of the magi, Wed, 30 May 2012 20:47:39 -0400

Since the turn of the century, I've written 6 books using C#. Where have you been?

At various times in my life, my preferred programming language has been (in order) Fortran, PL/I, APL, PL/I, Z-80 assembly language, 8086 assembly language, C, and C#, and I am not yet dead, so I may find another language I prefer sometime in the future. It's called "growth." — Charles

"Since the turn of the century, I've written 6 books using C#. Where have you been?"

I know. Despite the timing, Doug Boling's comment revealed the exact opposite evolution from yours, so I had to laugh.

— The ref new gift and the malloc'ed gift of the magi, Wed, 30 May 2012 21:19:58 -0400

I understand that C++ RT has handle references % as well as handle pointers ^. Would using references make your C++ code look more like the C# code?

— AJS, Wed, 30 May 2012 22:49:22 -0400

I think I read somewhere that you can write WinRT apps using "pure" C++ if you want to. Can you confirm that it is indeed possible to stay away from C++/Cx altogether?

— Jonas, Thu, 31 May 2012 02:32:54 -0400

> I think I read somewhere... Can you confirm...

No I cannot, but because WinRT is basically COM underneath, I suppose you can access WinRT with a lot of really ugly COM-based code. But I don't know. — Charles

On things not possible in C#, there will at least be the option of using a managed wrapper for DirectX. I'm pretty sure SlimDX announced their intention to port to WinRT at some point, and it looks like SharpDX already has been.

Admittedly using these wrappers doesn't feel very much like writing C# code.

— Nicholas W, Thu, 31 May 2012 03:08:30 -0400

Sure would be nice to have an XNA for Metro apps. — Charles

I think it would be interesting to discuss examples of where you would use both C# and C++ in the same project, for example if a program written in C# needs some graphic effects which can only be done in DirectX.

I noticed that this does not only apply to 3D graphics, but also to simple effects such as blur or drop shadow - which were in WPF but are missing from WinRT.

Martin Bennedik, Thu, 31 May 2012 08:35:52 -0400

I've been thinking along the same lines. I haven't seen the Release Preview yet, but the Consumer Preview doesn't even allow you to enumerate system fonts.

This morning I've been rolling around a chapter idea in my head: Something like "Breaking the Boundaries" showing how to implement specific DirectX jobs in WinMD libraries for use by a C# program. — Charles

I'd find these samples worthwhile. Your idea for a chapter on breaking boundaries is a good one.

I think there is probably space for someone to write a primer on modern C++ targeted at Windows 8 developers. There are a lot of good resources scattered over the web and in various books, but a well written resource for developers who need to work at the lower level with C++ would be useful. It is surprising how long it takes many developers to integrate 3rd party libs with VC++ projects but that is starting to get outside the realm of a Windows 8 API book.

Brian Lyttle, Thu, 31 May 2012 20:08:54 -0400

Jonas: Yes, it is possible to stay away from C++/CX altogether. But it is difficult and expensive. I think one of the Build talks mentioned this, though I can't locate which one, and Ian Griffiths wrote a couple of posts in which he dug into it at a raw COM level, from RoInitialize on up. See Real Native WinRT -- a fascinating read, and well worth it to understand what's happening under the surface, but I think you'll agree with Ian's conclusion that "nobody in their right mind is going to write applications this way!"

— Ivan, Fri, 1 Jun 2012 02:07:35 -0400

As a current C++, C++/CLI developer, I do appreciate your effort to create C++/CX versions of the samples.

I had not realized the crippled nature of Platform::String^ since I have System::String^ at my disposal now. I think a book such as Brian Lyttle describes would really help me get up to speed faster if I decide to go down the Metro road.

— John Schroedl, Fri, 1 Jun 2012 11:14:31 -0400

I'm kind of embarassed that I neglected to use std::wstring in my C++ string stuff. That's really a much better way to go, and then convert to and from Platform::String at API calls. I'll be fixing that when converting the code over to the Release Preview. — Charles

I submitted a bug for:

"Notice in the C++ snippet that the FontFamily class and some enumerations (FontStyle, HorizontalAlignment, and VerticalAlignment) need to be fully qualified with the namespace name."

I thought it was fixed in the compiler release just before the release candidate. Anyhow it is broken in the release candidate. See

— Andrew7Webb, Fri, 1 Jun 2012 23:15:15 -0400

@Ivan: Thanks for the link. Yes, it does seem making WinRT apps on pure C++ is not a realistic option. I thinks that's a shame. Hopefully, it will be possible to write WinRT apps in Qt in the future.

— Jonas, Sat, 2 Jun 2012 14:15:17 -0400

Well it seems to me is good strategy of learning: by reading book you see C# code, but by typing use C++/CX, and then confirm with code you typed in zip.

Yes, in app like StrippedDownHello is harder to try from first time coded, but sometimes your code will be more than in zip:

you forgot to include using namespace Windows::UI; that's why in C++/CX no way txtblk -> Foreground = ref new SolidColorBrush(Colors::Red); at void App::OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs ^pArgs).


Yes is that prefer who know C++.


>From time when .NET introduced was more "holly war" about cold start of managed and native app, but in Metro style app it seems to me that C++/CX is need more time to start first time than C# and VB.NET.

Who view that too?

— Guest, Sat, 2 Jun 2012 14:26:11 -0400

I'm really grateful that you have written this book. Your Programming Windows books (I have the 3rd and 4th editions) are largely responsible for my having become a windows programmer.

Having familiarity with MFC, only, I appreciate an explanation of WinRT and C# that takes the same care as you took in your earlier Programming Windows books.

I have always been biased against .NET for some reason.

Charles Cotton, Sun, 3 Jun 2012 19:23:37 -0400

Charles did you investigate in witch case you probably to use C++/COM with Windows Runtime Library (or WRL for short) (located here -> Program Files (x86)\Windows Kits\8.0\Include\winrt\wrl) not C++/CX?

Did it (library) help to develop Metro app in non support tool (in assembler for example - for academic interest only ;)?

See at "Don't care for the component extensions?"

— Guest, Mon, 4 Jun 2012 15:53:47 -0400

"the C# compiler gives higher priority to external classes and enumerations"

Nitpicking a little, but I think it's more that the C# compiler gives them equal priority, and then figures out which one you mean based on what you're trying to do with it.

— , Tue, 5 Jun 2012 00:42:26 -0400

Thanks for the clarification. — Charles

In file\ReleasePreview\CPlusPlus\Chapter02\Spiral\Spiral\MainPage.xaml.cpp

You use magic number at

double radians = 3.14159 * angle / 180;

why not using

double radians = M_PI * angel / 180;


I know that PI is a constant and not be changed, but it defined in math.h,

#define M_PI 3.14159265358979323846

why not using it from that?

— Guest, Fri, 8 Jun 2012 05:56:28 -0400

Because one line of code is better than three lines of code?

Probably the real reason is that (as I've admitted) I've been away from C++ for a long time, and I would have had to spend too much time trying to figure out where PI is defined and what it's called. Given that the number is not likely to change in the next few years, why not just use it directly? — Charles

Charles thank for your answer.

For note, I don't know how it at C++ 11, but prior to this version of standard math.h include common math constant in Visual C++ version, for example in GNU C++ there are no math constant.

That's why before using they you must #define _USE_MATH_DEFINES before #include

— Guest, Fri, 8 Jun 2012 09:00:24 -0400

Please explain the reason of pch.h and rules when you add include in it.

Is it recommended that any addition h file must be added only at this file not in file at which functionality needed (for example in MainPage.xaml.cpp at TapTheText I found time function but no way time.h at this file, only at pch.h).

— Guest, Mon, 9 Jul 2012 09:11:23 -0400

I'm glad that you are converting the code to C++. I also purchased the book. By the way, one of my favorite books ever is Windows Programming Fifth edition written by you.

Now, I can understand that besides the fact that you like C#,it will give you more potential buyers.

However, I have to agree with Sutter. Coffee Based Languages are expensive when it comes to resources. There are plenty of reasons to use C++. So, if it was my choice, I would have prefer the entire book with C++/CX (here is the link to sutter's talk: )

Anyways, I'm glad you are working so hard to bring us this book. Your style of writing is the best ever!

Francisco, Mon, 9 Jul 2012 10:50:09 -0400

Please check the success of run the C++/CX version of Chapter03 -> RoutedEvents6 (I tested in both Consumer and Release Preview), there are some exception when try to run compiled. (Direct Link)

There are no problem at RoutedEvents1-5 (checked only in Release Preview) and no problem in CSharp version of RoutedEvents6.

Thank you for future advice.

Guest, Mon, 9 Jul 2012 16:46:33 -0400

Yes, it's mentioned in the readme file. — Charles

Charles so sorry for I disturbed you, I usually use only book and Visual Studio. When my self written code don't work I load your project.... And I forgot to read disclaimer (warning about issue) in readme.

In future learning I will be read readme before post here.


Hope in RTM Windows 8 and Visual Studio 2012 that will be fixed.

— Guest, Tue, 10 Jul 2012 14:11:15 -0400

Charles so sorry for I disturbed you, I usually use only book and Visual Studio. When my self written code don't work I load your project.... And I forgot to read disclaimer (warning about issue) in readme.

In future learning I will be read readme before post here.


Hope in RTM Windows 8 and Visual Studio 2012 that will be fixed.

— Guest, Tue, 10 Jul 2012 14:11:15 -0400

> I didn't feel I was demonstrating .NET reflection so much as using reflection to demonstrate other concepts, so I didn't feel the need to perform reflection in C++.

So why in book you say "Windows 8 reflection works little differently from .NET reflection"? May be you want say ".NET reflection on WinRT works some different"?

— Guest, Fri, 20 Jul 2012 14:55:59 -0400

I'm using your Windows Programming fifth edition right now. I love this book!!!!!!!! I can't wait to your WinRT Win8 book.Even if is in c# (plus the c/c++ code you will provide)

For now, I can do with the ebook... but nothing like a real

hard copy!

Anyways, I had a nice idea to suggest. Easy for me to say since I won't have to do it... A better idea would be for me to do myself!

Here it goes: After you finish the metro book, How about a special edition of Windows Programming book. Same chapters with no change, except minus a few chapters from the advanced topics. In here, maybe you could add a few things. The chapters that I would remove from there are: Chapter 19 MDI (MDI is kind of out...) , Chapter 22:Sound and Music (while is cool, the idea is to keep some different chapters in the "special edition" and Chapter 23:"A Taste of internet"

In exchange for those, maybe just 3 new chapters... or 4...

* Ribbon Framework

* Using Metro 8 via C++/cx

* Some other new cool stuff you like.

Anyways, while this may not happen, I just wanted to say again, how great is your style of writing.

By the way, there is a good book about win32 api covering some topics which is called Introducing Windows 7 for developers. Here is what I learn how to use the multi-touch framework for my PhD thesis that I'm working on.

Finally, even I have the ebook and I will have the final release, I will also purchase the hard copy!

Thanks Charles for the amazing work!

PS: I know the special edition comment is crazy... it is just a nice wish!

Francisco, Tue, 24 Jul 2012 12:05:12 -0400

I haven't been following the development of Win8 lately, but can we NOT continute to write *any* app on windows 8 using pure Win32/64 API/SDK? (and maybe a bit of COM)

Why was this WinRT thing invented and isn't Win32/64 API + COM enough?

Programming Windows 5th edition was a great book (I last read it for a project in 2011). But this new edition sounds like a compromise to me by going down the path of C# (managed code) and C++/CX (unproven technology).

Your thoughts?

— bjorn, Wed, 15 Aug 2012 08:37:48 -0400

Windows 8 will continue to run Win32 apps on its desktop, so if you want to write Win32 apps, you can continue to do so and they will run.

For new Windows 8 apps with the new UI that will be sold through the apps store, you'll use WinRT. This is an object-oriented API and hence best suited for object-oriented languages. However, you can access WinRT entirely through COM, as Ian Griffiths demonstrated.

It is also possible to write a Windows 8 app using an extremely tiny amount of WinRT and construct your entire UI from DirectX. This is an approach that Windows 8 games developers will probably be using.

— Charles

What do you think about next note?

Alexandre Mutel - Going Native 2.0, The future of WinRT

— Guest, Mon, 20 Aug 2012 10:24:00 -0400

What is the use of C++, if you lose the platform-independence anyway by using CLR-constructs like ref new? Microsoft should build DirectX-support for C# and Windows 8 instead of trying to revive an old and (imho ugly) language.

I prefer C# very much over C++.

— AP, Fri, 24 Aug 2012 11:12:46 -0400

Recent Entries
< PreviousBrowse the ArchivesNext >
Subscribe to the RSS Feed

(c) Copyright Charles Petzold