2014年5月22日 星期四

[C#] 取得執行檔 (*.exe) 的圖標 (.ico) 【Get executable file's icon】

筆者最近最常開發的功能即為獲取執行檔的圖標,在此紀錄兩種不同的做法。

方法一:使用 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;
}

沒有留言:

張貼留言