C++ Snippets for the MS Windows platform

A collection of code snippets, small pearls of wisdom and bits of knowledge, that may come handy at times.

This is a specialized page for things related to the Windows operating system, the Windows API (Win32) or the Visual Studio IDE/Microsoft Compiler (and maybe later also other compilers that can be used to generate executables for Windows); the more generic page is C++ Snippets.

Don’t expect well thought out descriptions or highly structured content here; these are snippets. (But there are some links spread around for further reading.)


On catching exceptions

The attempt to catch all exceptions by (try {} catch (...) {}) on Windows will by default not catch “platform level” exceptions like access violations or divide by zero errors.
Those are thrown on Windows as SEH (Structured Exception Handling) exceptions; one could enable to catch them via the /EHa compile option:

But even Microsoft discourages that:

Specifying /EHa and trying to handle all exceptions by using catch(...) can be dangerous.

In most cases, asynchronous exceptions are unrecoverable and should be considered fatal. Catching them and proceeding can cause process corruption and lead to bugs that are hard to find and fix.

Even though Windows and Visual C++ support SEH, we strongly recommend that you use ISO-standard C++ exception handling (/EHsc or /EHs). It makes your code more portable and flexible. There may still be times you have to use SEH in legacy code or for particular kinds of programs. […]

Also, this may have an impact on performance and size (read on a few StackOverflow comments), but I guess the compiler optimization improves over time; so, that’s maybe not the important point here…


Windows OS identification preprocessor macro

After I’ve read up on this a bit, it seems that _WIN32 is preferred to WIN32 and should be used as the primary identifier:

#ifdef _WIN32
//...
#endif

… or alternatively:

#if defined(_WIN32)
//...
#endif

Unfortunately, the official statement on Microsoft’s Docs page on Predefined Macros reads a bit vague, I think:
(On the other hand: WIN32 is not even mentioned there, only _WIN32 is — that should tell you something…)

_WIN32 Defined as 1 when the compilation target is 32-bit ARM, 64-bit ARM, x86, or x64. Otherwise, undefined.

Plus some (more or less convincing) arguments from other places:

Why not to rely on WIN32:

Distinction between 32-bit and 64-bit

The symbol _WIN64 is defined by the compiler to indicate that this is a 64-bit Windows compilation (Microsoft’s Docs page on Predefined Macros):

_WIN64 Defined as 1 when the compilation target is 64-bit ARM or x64. Otherwise, undefined.

Some sources: