這個獲取關聯圖標,能夠獲取磁盤分區的圖標,能夠獲取某個特定類型的文件的圖標,也能夠獲取某個指定文件的圖標
/// <summary>
/// 保存文件信息的結構體
/// </summary>
///
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
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;
}
class NativeMethods
{
[DllImport("Shell32.dll", EntryPoint = "SHGetFileInfo", SetLastError = true, CharSet = CharSet.Auto)]
public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbFileInfo, uint uFlags);
[DllImport("User32.dll", EntryPoint = "DestroyIcon")]
public static extern int DestroyIcon(IntPtr hIcon);
#region API 參數的常量定義
public const uint SHGFI_ICON = 0x100;
public const uint SHGFI_LARGEICON = 0x0; //大圖標 32×32
public const uint SHGFI_SMALLICON = 0x1; //小圖標 16×16
public const uint SHGFI_USEFILEATTRIBUTES = 0x10;
#endregion
}
/// <summary>
/// 獲取文件類型的關聯圖標
/// </summary>
/// <param name="fileName">文件類型的擴展名或文件的絕對路徑</param>
/// <param name="isLargeIcon">是否返回大圖標</param>
/// <returns>獲取到的圖標</returns>
static Icon GetIcon(string fileName, bool isLargeIcon)
{
SHFILEINFO shfi = new SHFILEINFO();
IntPtr hI;
if (isLargeIcon)
hI = NativeMethods.SHGetFileInfo(fileName, 0, ref shfi, (uint)Marshal.SizeOf(shfi), NativeMethods.SHGFI_ICON | NativeMethods.SHGFI_USEFILEATTRIBUTES | NativeMethods.SHGFI_LARGEICON);
else
hI = NativeMethods.SHGetFileInfo(fileName, 0, ref shfi, (uint)Marshal.SizeOf(shfi), NativeMethods.SHGFI_ICON | NativeMethods.SHGFI_USEFILEATTRIBUTES | NativeMethods.SHGFI_SMALLICON);
Icon icon = Icon.FromHandle(shfi.hIcon).Clone() as Icon;
NativeMethods.DestroyIcon(shfi.hIcon); //釋放資源
return icon;
}
private void btnGetIcon_Click(object sender, EventArgs e)
{
using (Graphics g = this.pbSmallIcon.CreateGraphics())
{
g.Clear(this.pbSmallIcon.BackColor); //清除picturebox的背景色,爲了畫透明圖標
g.DrawIcon(GetIcon(this.tbFileExt.Text, false), 1, 1); //繪製小圖標
}
using (Graphics g = this.pbLargeIcon.CreateGraphics())
{
g.Clear(this.pbLargeIcon.BackColor); //清除picturebox的背景色,爲了畫透明圖標
g.DrawIcon(GetIcon(this.tbFileExt.Text, true), 1, 1); //繪製小圖標
}
}
![](http://static.javashuo.com/static/loading.gif)