find icon for .exe
Question
I have the path name to a .exe file.
How do I find the path to the icon that windows would use if this file were dropped on the desktop? (I want to display this icon in my own program.)
I need to be able to find the icon via my C# program at runtime.
Using C# in Visual Studio 2008.
Solution
If found this code online a while ago to do that:
class Win32
{
public const uint SHGFI_ICON = 0x100;
public const uint SHGFI_LARGEICON = 0x0; // 'Large icon
public const uint SHGFI_SMALLICON = 0x1; // 'Small icon
[DllImport("shell32.dll")]
public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags);
public static Bitmap GetFileIcon(string fName)
{
IntPtr hImgSmall; //the handle to the system image list
SHFILEINFO shinfo = new SHFILEINFO();
hImgSmall = Win32.SHGetFileInfo(fName, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), Win32.SHGFI_ICON | Win32.SHGFI_SMALLICON);
return Icon.FromHandle(shinfo.hIcon).ToBitmap();
}
}
[StructLayout(LayoutKind.Sequential)]
public struct SHFILEINFO
{
public IntPtr hIcon;
public IntPtr iIcon;
public uint dwAttributes;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szDisplayName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
public string szTypeName;
};
you also need
using System.Drawing;
using System.Runtime.InteropServices;
to reference all the appropriate classes
OTHER TIPS
The default icon would be the one embedded in the exe at index 0.
Look at: Project properties > application tab > Icon.
This CodeProject article seems to do the job pretty well. It provides an IconExtractor
class that encapsulates all the Win32 API stuff for you into a nice managed interface.
You can use it as such:
using TKageyu.Utils;
...
using (IconExtractor ie = new IconExtractor(@"D:\sample.exe"))
{
Icon icon0 = ie.GetIcon(0);
Icon icon1 = ie.GetIcon(1);
...
Icon[] splitIcons = IconExtractor.SplitIcon(icon0);
...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow