Click here to Skip to main content
Click here to Skip to main content

Extracting Icons from EXE/DLL and Icon Manipulation

By , 17 Jan 2009
 

Abstract

This article describes how to extract icons from an executable module (EXE or DLL), and also how to get the icons associated with a file.

In this article, you will find how to get the icon image that best fits the size you want to display. You can also find how to split an icon file to get its image.

Introduction

Icons are a varied lot—they come in many sizes and color depths. A single icon resource—an ICO file, or an icon resource in an EXE or DLL file—can contain multiple icon images, each with a different size and/or color depth.

Windows extracts the appropriate size/color depth image from the resource depending on the context of the icon's use. Windows also provides a collection of APIs for accessing and displaying icons and icon images.

The code I introduce will help you extract icons from executable modules (EXE, DLL) without the need to know the Windows APIs that are used in this situation.

The code will also help you in extracting specific icon images from an icon file, and will help you in extracting the icon image that best fits a supplied icon size.

Background

If you want to understand what is going on in this code, you should know how to call APIs from C# code. You also need to know the icon format, about which you will find here: MSDN.

Using the code

First, you need to add a reference to TAFactory.IconPack.dll, or add the project named IconPack to your project.

Add the following statement to your code:

using TAFactory.IconPack;

Use the IconHelper class to obtain the icons as follows:

//Get the open folder icon from shell32.dll.
Icon openFolderIcon = IconHelper.ExtractIcon(@"%SystemRoot%\system32\shell32.dll", 4);
//Get all icons contained in shell32.dll.
List<icon> shellIcons = IconHelper.ExtractAllIcons(@"%SystemRoot%\system32\shell32.dll");
//Split the openFolderIcon into its icon images.
List<icon> openFolderSet = IconHelper.SplitGroupIcon(openFolderIcon);
//Get the small open folder icon.
Icon smallFolder = IconHelper.GetBestFitIcon(openFolderIcon, 
                              SystemInformation.SmallIconSize);
//Get large icon of c drive. 
Icon largeCDriveIcon = IconHelper.GetAssociatedLargeIcon(@"C:\");
//Get small icon of c drive. 
Icon smallCDriveIcon = IconHelper.GetAssociatedSmallIcon(@"C:\");
//Merge icon images in a single icon.
Icon cDriveIcon = IconHelper.Merge(smallCDriveIcon, largeCDriveIcon);
//Save the icon to a file.
FileStream fs = File.Create(@"c:\CDrive.ico");
cDriveIcon.Save(fs);
fs.Close();

References

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Abdallah Gomah
Software Developer (Senior) NCEEE
Egypt Egypt
Member
Abdallah Gomah
Bachelor of Computers and Information in Computer Science, year 2003 - Cairo University (Egypt)
 
- Working as a developer since I graduated from the faculty.
- Like coding in C++ aloso like to code in assembly.
- Have a great experience in coding with .NET (C#/VB), but I prefer the C# notation.
- Had written a lot of applications Desktop and Web.
 
I love playing football as much as I love the programming.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionSuper Code ButmemberMember 985556517 May '13 - 6:29 
A great code, very nice
i just little change your ExtractIcon() for get icon with a negatif index :
 
public static Icon ExtractIcon(string fileName, int iconIndex)
        {
            Icon icon = null;
            //Try to load the file as icon file.
            try { icon = new Icon(Environment.ExpandEnvironmentVariables(fileName)); }
            catch { }
 
            if (icon != null) //The file was an icon file, return the icon.
                return icon;
 
            //Load the file as an executable module.
            using (IconExtractor extractor = new IconExtractor(fileName))
            {
                //old
                //return extractor.GetIconAt(iconIndex);
                //replace with :
                if (iconIndex >= 0)
                {
                    return extractor.GetIconAt(iconIndex);
                }
                else
                {
                    //if the index is negatif, is not a index but is a ID NAME  (see msdn.microsoft.com/en-us/library/ms682212(VS.85).aspx)
                    //example in registry DefaultIcon of "txtfile"  is "%SystemRoot%\system32\imageres.dll,-102" = the icon with index=97 in imageres.dll
                    iconIndex = -iconIndex;
                    int index = 0;
                    foreach (ResourceName resourceName in extractor.IconNamesList)
                    {
                        if (resourceName.Id != null)
                        {
                            if (resourceName.Id == iconIndex)
                            {
                                icon = extractor.GetIconAt(index);
                                break;
                            }
                        }
                        index++;
                    }
                }
            }
 
            return icon;
        }
()
GeneralThanks.memberFatih Nehir30 Nov '12 - 3:07 
Usefull program.Thanks.
QuestionWhere does TAFactory.IconPack.dll come frommemberJrad26 Oct '12 - 11:38 
Hi,
Please can you tell me where TAFactory.IconPack.dll comes from.
Thanks
AnswerRe: Where does TAFactory.IconPack.dll come frommemberAbdallah Gomah26 Oct '12 - 10:42 
You can find it in the attached demo.
Also source code is included in the article.
QuestionLittle help needed pleasememberMember 89109501 May '12 - 5:00 
Can someone kindly explain how I can actually use this code in C#?? *NEW to programming in C#
 
What I am trying to achieve is:
 
- Get the path where the icon image file is located for ALL .lnk files in C:\ProgramData\Microsoft\Windows\Start Menu\Programs and store that data in an array for each .lnk file.
 
- I want to be able to load an image frame with the corresponding icon image by reading the image from the path where it is stored.
 
- So for example, if you have Adobe Reader installed with .lnk file in:
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Adobe\Adobe Reader X.lnk
 
I need to get the path of the image icon file associated to the Adobe Reader Icon.
 
Will appreciate your help.
 
Thanks.
GeneralMy vote of 5memberMario Majcica19 May '11 - 22:47 
Nice one.
GeneralMy vote of 5memberAlex Essilfie30 Dec '10 - 22:59 
This article was very helpful in a project I was recently working on.
 
Thanks a lot.
GeneralMy vote of 5memberplayhere23 Aug '10 - 23:24 
Great Job!
General.Net 2.0 equivalent of icon extractionmemberoguzhanFilizlibay()29 Mar '10 - 3:22 
You can use the Icon class in System.Drawing to extract an icon and save it as a .ico file:
 
using System.Drawing;
..
 
Icon icon = Icon.ExtractAssociatedIcon("c:\executable.exe");
FileStream iconFile = new FileStream("c:\iconfile.icon", System.IO.FileMode.OpenOrCreate);
icon.Save(iconFile);
iconFile.Close();
GeneralRe: .Net 2.0 equivalent of icon extractionmemberplayhere23 Aug '10 - 21:47 
this can only extract ico files with size 32 X 32
GeneralLeakmemberDizZ23 Feb '10 - 6:01 
I think there is a leak in your code so I've modified the following code:
 
public static Icon GetAssociatedIcon(string fileName, IconFlags flags)
{
flags |= IconFlags.Icon;
SHFILEINFO fileInfo = new SHFILEINFO();
IntPtr result = Win32.SHGetFileInfo(fileName, 0, ref fileInfo, (uint)Marshal.SizeOf(fileInfo), (SHGetFileInfoFlags) flags);
 
if (fileInfo.hIcon == IntPtr.Zero)
return null;
 
Icon ico = (Icon)Icon.FromHandle(fileInfo.hIcon).Clone();
 
Win32.DestroyIcon(fileInfo.hIcon);
 
return ico;
}

 
Thank to Paul Ingles for this trick : Obtaining (and managing) file and folder icons using SHGetFileInfo in C#[^]
GeneralThanksmemberlewebus21 Jan '10 - 5:22 
Your article was of great help ... Thanks ...
GeneralNice article, but got errormemberRick Hansen21 Jan '09 - 4:23 
Hi,
 
Using the demo program I tried opening a .ico file that I know is a valid file and got the following error:
 

 
See the end of this message for details on invoking
just-in-time (JIT) debugging instead of this dialog box.
 
************** Exception Text **************
System.ComponentModel.Win32Exception: The operation completed successfully
at System.Drawing.Icon.Initialize(Int32 width, Int32 height)
at System.Drawing.Icon..ctor(Stream stream, Int32 width, Int32 height)
at System.Drawing.Icon..ctor(Stream stream)
at TAFactory.IconPack.IconInfo.LoadIconInfo(Icon icon) in C:\Hansen\Download\IconExtraction\IconPack_Src\IconPackSln\IconPack\IconInfo.cs:line 320
at TAFactory.IconPack.IconInfo..ctor(Icon icon) in C:\Hansen\Download\IconExtraction\IconPack_Src\IconPackSln\IconPack\IconInfo.cs:line 211
at TAFactory.IconPack.IconHelper.GetBestFitIcon(Icon icon, Size desiredSize) in C:\Hansen\Download\IconExtraction\IconPack_Src\IconPackSln\IconPack\IconHelper.cs:line 136
at IconPackDemo.frmIconList.LoadIconFromLibrary(String fileName) in C:\Hansen\Download\IconExtraction\IconPack_Src\IconPackSln\IconPackDemo\frmIconList.cs:line 124
at IconPackDemo.frmIconList.tlbarMainOpen_Click(Object sender, EventArgs e) in C:\Hansen\Download\IconExtraction\IconPack_Src\IconPackSln\IconPackDemo\frmIconList.cs:line 69
at System.Windows.Forms.ToolStripItem.RaiseEvent(Object key, EventArgs e)
at System.Windows.Forms.ToolStripButton.OnClick(EventArgs e)
at System.Windows.Forms.ToolStripItem.HandleClick(EventArgs e)
at System.Windows.Forms.ToolStripItem.HandleMouseUp(MouseEventArgs e)
at System.Windows.Forms.ToolStripItem.FireEventInteractive(EventArgs e, ToolStripItemEventType met)
at System.Windows.Forms.ToolStripItem.FireEvent(EventArgs e, ToolStripItemEventType met)
at System.Windows.Forms.ToolStrip.OnMouseUp(MouseEventArgs mea)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
at System.Windows.Forms.ToolStrip.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
 

************** Loaded Assemblies **************
mscorlib
Assembly Version: 2.0.0.0
Win32 Version: 2.0.50727.1433 (REDBITS.050727-1400)
CodeBase: file:///c:/WINDOWS/Microsoft.NET/Framework/v2.0.50727/mscorlib.dll
----------------------------------------
IconPackDemo
Assembly Version: 1.0.0.0
Win32 Version: 1.0.0.0
CodeBase: file:///C:/Hansen/Download/IconExtraction/IconPack_Src/IconPackSln/IconPackDemo/bin/Debug/IconPackDemo.exe
----------------------------------------
System.Windows.Forms
Assembly Version: 2.0.0.0
Win32 Version: 2.0.50727.1433 (REDBITS.050727-1400)
CodeBase: file:///C:/WINDOWS/assembly/GAC_MSIL/System.Windows.Forms/2.0.0.0__b77a5c561934e089/System.Windows.Forms.dll
----------------------------------------
System
Assembly Version: 2.0.0.0
Win32 Version: 2.0.50727.1433 (REDBITS.050727-1400)
CodeBase: file:///C:/WINDOWS/assembly/GAC_MSIL/System/2.0.0.0__b77a5c561934e089/System.dll
----------------------------------------
System.Drawing
Assembly Version: 2.0.0.0
Win32 Version: 2.0.50727.1433 (REDBITS.050727-1400)
CodeBase: file:///C:/WINDOWS/assembly/GAC_MSIL/System.Drawing/2.0.0.0__b03f5f7f11d50a3a/System.Drawing.dll
----------------------------------------
System.Configuration
Assembly Version: 2.0.0.0
Win32 Version: 2.0.50727.1433 (REDBITS.050727-1400)
CodeBase: file:///C:/WINDOWS/assembly/GAC_MSIL/System.Configuration/2.0.0.0__b03f5f7f11d50a3a/System.Configuration.dll
----------------------------------------
System.Xml
Assembly Version: 2.0.0.0
Win32 Version: 2.0.50727.1433 (REDBITS.050727-1400)
CodeBase: file:///C:/WINDOWS/assembly/GAC_MSIL/System.Xml/2.0.0.0__b77a5c561934e089/System.Xml.dll
----------------------------------------
TAFactory.IconPack
Assembly Version: 1.0.0.0
Win32 Version: 1.0.0.0
CodeBase: file:///C:/Hansen/Download/IconExtraction/IconPack_Src/IconPackSln/IconPackDemo/bin/Debug/TAFactory.IconPack.DLL
----------------------------------------
 
************** JIT Debugging **************
To enable just-in-time (JIT) debugging, the .config file for this
application or computer (machine.config) must have the
jitDebugging value set in the system.windows.forms section.
The application must also be compiled with debugging
enabled.
 
For example:
 
<configuration>
<system.windows.forms jitDebugging="true" />
</configuration>
 
When JIT debugging is enabled, any unhandled exception
will be sent to the JIT debugger registered on the computer
rather than be handled by this dialog box.
GeneralRe: Nice article, but got errormemberAbdallah Gomah22 Jan '09 - 5:45 
Please, send me the icon so I can correct this bug.
GeneralRe: Nice article, but got errormemberFrozenCow_13 Feb '09 - 5:54 
Hi, I also noticed this exception being raised for a few of the applications I tried. You can try to open:
C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\devenv.exe
 
It seems like a bug in the Icon constructor :S. I've used the following workaround:
try
{
    icon = TAFactory.IconPack.IconHelper.GetBestFitIcon(icon, new System.Drawing.Size(64, 64));
}
catch (System.ComponentModel.Win32Exception e)
{
    if (e.NativeErrorCode != 0)
        throw;
}

GeneralRe: Nice article, but got error [modified]memberplayhere23 Aug '10 - 23:08 
it happens when the file contains icons that size are 0X0 or larger than 96X96
 
here is a walk around.
 
Icon newIcon = null;
try
{
	newIcon = new Icon(outputStream);
}
catch (Exception)
{
	// use a dummy ico file
	newIcon = new Icon(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"Empty.ico"));
}

modified on Tuesday, August 24, 2010 5:20 AM

GeneralGreat ArticlememberSwapnil Shah18 Jan '09 - 20:57 
My Vote of 5
GeneralVista IconsmemberFrozenCow_17 Jan '09 - 11:55 
What about Vista's 256x256 icons? Are these also supported?
 
modified on Sunday, January 18, 2009 11:02 AM

GeneralRe: Vista IconsmemberAbdallah Gomah18 Jan '09 - 8:25 
I didn't test it on vista icons, I'll try it then if it needs to be updated I'll do the required updates.
Thanks for this point.
AnswerRe: Vista IconsmemberAlex Essilfie30 Dec '10 - 22:55 
I tried the code on Vista/Win7 icons and it worked without modifications to the code.
GeneralVery Good Abdallah You are the bestmembernonoee201017 Jan '09 - 10:38 
a very good article and very benefical , الله ينور بصراحة
Generalgood job!memberSouthmountain17 Jan '09 - 6:41 
thanks for sharing

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 17 Jan 2009
Article Copyright 2009 by Abdallah Gomah
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid