這個獲取關聯圖示,可以獲取磁盤磁區的圖示,可以獲取某個特定型別的檔案的圖示,也可以獲取某個指定檔案的圖示
/// <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); //繪制小圖示
}
}

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/238848.html
標籤:.NET技术
上一篇:[C#] (原創)一步一步教你自定義控制元件——05,Label(原生控制元件)
下一篇:LightningChart解決方案:XY和3D圖表(Polymer Char GPC-IR®-工程案例)
