C#获取文件(磁盘驱动器)的关联图标(使用API SHGetFileInfo)
生活随笔
收集整理的這篇文章主要介紹了
C#获取文件(磁盘驱动器)的关联图标(使用API SHGetFileInfo)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
這是一個C#調用系統API SHGetFileInfo 的一個演示例子,也是給一位網友的答復,先看效果圖:
SHGetFileInfo 這個API, 可以獲取指定對象的非常詳細的相關信息,具體的內容,大家可以MSDN上關于此API的說明。
這個獲取關聯圖標,可以獲取磁盤分區的圖標,可以獲取某個特定類型的文件的圖標,也可以獲取某個指定文件的圖標,下面給出實現的全部代碼:
/// <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×32public const uint SHGFI_SMALLICON = 0x1; //小圖標 16×16public 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);elsehI = 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 linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {Help.ShowHelp(this, "http://www.zu14.cn"); }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.cnblogs.com/sjcatsoft/archive/2009/04/04/1429479.html
總結
以上是生活随笔為你收集整理的C#获取文件(磁盘驱动器)的关联图标(使用API SHGetFileInfo)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 不使用第三个变量交换两个变量
- 下一篇: 利用Attribute扩展MVC的Tit