Loading an Icon in C++/CLI

This turned out to be a tricky job, because the icons are stored in the resource as an unmanaged item.image  So the icon has to be loaded unmanaged, and then converted into the managed realm.  The icon was loaded by opening the Resource View, and right-clicking on the Icon folder to insert a new icon.

The following code snippet then loads the Icon from the resources into a managed object:

#include <windows.h>
#include "resource.h"
using namespace System::Reflection::Assembly;
using namespace System::Runtime::InteropServices;
using namespace System::Drawing;

// Get the primary module
Module ^ mod = GetExecutingAssembly()->GetModules()[0];

// Get the instance handle 
IntPtr hinst = Marshal::GetHINSTANCE(mod);

// Get the icon as unmanaged
HICON hic = LoadIcon((HINSTANCE) hinst.ToPointer(), MAKEINTRESOURCE(IDI_ICON1)); 

// import the unmanaged icon into the managed side 
Icon^ ic = Icon->FromHandle(IntPtr(hic));

// destroy the unmanaged icon 
DestroyIcon(static_cast<HICON>(ic->Handle.ToPointer() ));
Print | posted on Monday, March 17, 2008 8:36 AM


# re: Loading an Icon in C++/CLI

left by TonyM at 5/4/2009 12:31 AM Gravatar
Thank You! I did not figure I would have to bounce back to unmanaged to get this to work...

# re: Loading an Icon in C++/CLI

left by Claro at 2/4/2011 5:54 PM Gravatar
great share

# google authorship check

left by google authorship check at 9/21/2014 7:51 PM Gravatar
Loading an Icon in C++/CLI

# re: Loading an Icon in C++/CLI

left by passing by at 9/10/2016 8:14 AM Gravatar
thank you very much, searched half the internet to find this.

one remark, though: Icon->FromHandle should be Icon::FromHandle :)
Email (never displayed)
Please add 2 and 8 and type the answer here: