Extracting a Specific Size Icon From a .ico File

Here’s something that I recently discovered after a lot of searching and some experimenting.  In my add-ins I prefer to use .ico files for my button icons.  Icons have some advantages over .bmp files in that you can define a transparent background and you can save multiple images within a single .ico file.  This is convenient because to fully support Inventor’s interface you should have three icon sizes, as listed below.

16×16 pixels – Used for small icons in both Classic and Ribbon interfaces.
24×24 pixels – Used for large icons in Class interface.
32×32 pixels – Used for large icons in Ribbon interface.

Using an icon editor it’s fairly easy to create the icons of the various sizes and then use that .ico file in my program.  What I couldn’t figure out was how to extract an icon of a specific size from the .ico file.  My searches just lead to postings from other who had the same question but no answers.  I finally began experimenting and found something that works.

In my add-in project I add each of the .ico files as a resource to my project.  In VB.Net you can access any item in your resources by name.  The name of my icon in the example below is “MyCommand1”.  The code below reads the icon of the specified size from the resource and ends up holding a reference to an Icon object. 

Dim smallIcon As System.Drawing.Icon
smallIcon = New System.Drawing.Icon(My.Resources.MyCommand1, 16, 16)

The code below reads in the large icon file from the same icon resource. 

Dim largeIcon as Sytem.Drawing.Icon
largeIcon = New System.Drawing.Icon(My.Resources.MyCommand1, 32, 32)

You can’t directly use an Icon object with Inventor’s API since it is expecting an IPictureDisp object.  The code below demonstrates how to convert an Icon to an IPictureDisp.  You’ll need to reference the Microsoft.VisualBasic.Compatibility and stdole libraries into the project first.

Dim smallPic As stdole.IPictureDisp
smallPic = Microsoft.VisualBasic.Compatibility.VB6.IconToIPicture( _
                                                          smallIcon)


Comments

2 responses to “Extracting a Specific Size Icon From a .ico File”

  1. Unfortunately, IconToIPicture() doesn’t preserve the alpha channel in 32-bit icons; this results in a poor image when compared to other built-in Inventor images.
    There is at least one work-around, but it involves using undocumented stuff.

  2. My searches just lead to postings from other who had the same question but no answers. I finally began experimenting and found something that works.

Leave a Reply to J. Daniel SmithCancel reply

Discover more from Autodesk Developer Blog

Subscribe now to keep reading and get access to the full archive.

Continue reading