C++/CLI Snippet #1
I’ve been programming in C++/CLI at work recently, and I thought I’d share a snippet/trick or two that I’ve learnt.
When working with the .Net framework in C++ you can come across places where it’s easier to use the Win32 functions to do a particular task rather than the .Net ones (or there’s no direct .Net version of it available). In those cases you may need to get Win32 handles from some .Net classes, or extract primitive types from a handle to an Object instance.
To get the window handle (HWND) of a .Net Form:
HWND form_handle = reinterpret_cast<HWND>(form.Handle.ToPointer());
This also works for other handle types used in Windows, such as HDC.
Effectively this is just unboxing the variable from the .Net type. However the Handle property returns a type of IntPtr and therefore it needs the ToPointer() call to work properly.
Another trick to proper unboxing is when trying to convert from an Object^ to a primitive type, say UINT, or LONG. I discovered that using a safe_cast directly to the primitive type did not work, instead it just raised an exception. So to correctly unbox primitive variables you need to unbox them to a primitive, non-typedef’d type, something like:
int a = 10; Object^ a_obj = gcnew Object(a); // Automatic boxing UINT new_a = safe_cast<int>(a_obj); // Unboxes
Also don’t forget to wrap this unboxing code in a try – catch block as it might still throw exceptions.