I found this code somewhere on the web two years ago. It basically gets the large (32 x 32 pixels) and small (16 x 16 pixels) icons of an executable. The function returns an Icon object that can be displayed on a form’s icon area or used as a bitmap on a picture box or any other control that accepts bitmaps. For the code to work, create a windows application, drag a picture box control to the form area and leave it with its default name (PictureBox1).
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace WindowsFormsApplication1
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}
private void Form3_Load(object sender, EventArgs e)
{
//the path to an executable file, i chose windows media player
string wmp = @"C:\Program Files\Windows Media Player\wmplayer.exe";
//set the forms icon to the icon of the windows media player
this.Icon = IconRipper.GetIcon(wmp, IconSize.Small);
//display the larger icon (32 x 32) on the picturebox
pictureBox1.Image =
IconRipper.GetIcon(wmp, IconSize.Large).ToBitmap();
}
}
[StructLayout(LayoutKind.Sequential)]
public struct SHFILEINFO
{
public IntPtr hIcon;
public int iIcon;
public int dwAttributes;
public string szDisplayName;
public string szTypeName;
}
public enum IconSize
{
Large, //32 x 32
Small //16 x 16
}
public class IconRipper
{
private const uint SHGFI_SYSICONINDEX = 0x4000;
private const uint SHGFI_ICON = 0x100;
private const uint SHGFI_LARGEICON = 0x0;
private const uint SHGFI_SMALLICON = 0x1;
[DllImport("Shell32.dll")]
public static extern int SHGetFileInfo(string path, uint fileAttributes,
out SHFILEINFO psfi, uint fileInfo, uint flags);
public static Icon GetIcon(string path, IconSize iconSize)
{
SHFILEINFO info = new SHFILEINFO();
uint size = iconSize == IconSize.Large ?
SHGFI_LARGEICON : SHGFI_SMALLICON;
uint flags = SHGFI_SYSICONINDEX | size | SHGFI_ICON;
int hTcdf = SHGetFileInfo(path, 0, out info,
(uint)Marshal.SizeOf(typeof(SHFILEINFO)), flags);
IntPtr handleIcon = info.hIcon;
return Icon.FromHandle(handleIcon);
}
}
}