方法一:使用 SHGetFileInfo
using System.Runtime.InteropServices;
[DllImport("shell32.dll", CharSet=CharSet.Auto)]
public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbFileInfo, uint uFlags);
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
public struct SHFILEINFO
{
public IntPtr hIcon;
public int iIcon;
public uint dwAttributes;
[MarshalAs(UnmanagedType.ByvalTStr, SizeConst = 260)]
public string szDisplayName;
[MarshalAs(UnmanagedType.ByvalTStr, SizeConst = 80)]
public string szTypeName;
};
public const uint SHGFI_ICON = 0x100;
public const uint SHGFI_LARGEICON = 0x0; // Large icon
public const uint SHGFI_SMALLICON = 0x1; // Small icon
IntPtr hImgSmall;
IntPtr hImgLarge;
SHFILEINFO shinfo = new SHFILEINFO();
public System.Drawing.Icon GetExeFileIcon(string exeFilePath)
{
// Use this to get small icon
hImgSmall = SHGetFileInfo(exeFilePath, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), SHGFI_ICON | SHGFI_SMALLICON);
// Use this to get large icon
hImgLarge = SHGetFileInfo(exeFilePath, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), SHGFI_ICON | SHGFI_LARGEICON);
System.Drawing.Icon myIcon = System.Drawing.Icon.FromHandle(shinfo.hIcon);
return myIcon;
}
方法二:使用 Icon 類別 (System.Drawing)
using System.Drawing;
Icon myIcon = null;
public Icon GetExeFileIcon(string exeFilePath)
{
myIcon = Icon.ExetractAssociatedIcon(exeFilePath);
return myIcon;
}