NativeMethods.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Drawing;
  4. using System.Linq;
  5. using System.Runtime.InteropServices;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using System.Windows.Forms;
  9. namespace GeekDesk.Util
  10. {
  11. /// <summary>
  12. /// 保存文件信息的结构体
  13. /// </summary>
  14. ///
  15. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
  16. struct SHFILEINFO
  17. {
  18. public IntPtr hIcon;
  19. public int iIcon;
  20. public uint dwAttributes;
  21. [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
  22. public string szDisplayName;
  23. [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
  24. public string szTypeName;
  25. }
  26. class NativeMethods
  27. {
  28. [DllImport("Shell32.dll", EntryPoint = "SHGetFileInfo", SetLastError = true, CharSet = CharSet.Auto)]
  29. public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbFileInfo, uint uFlags);
  30. [DllImport("User32.dll", EntryPoint = "DestroyIcon")]
  31. public static extern int DestroyIcon(IntPtr hIcon);
  32. #region API 参数的常量定义
  33. public const uint SHGFI_ICON = 0x100;
  34. public const uint SHGFI_LARGEICON = 0x0; //大图标 32×32
  35. public const uint SHGFI_SMALLICON = 0x1; //小图标 16×16
  36. public const uint SHGFI_USEFILEATTRIBUTES = 0x10;
  37. #endregion
  38. /// <summary>
  39. /// 获取文件类型的关联图标
  40. /// </summary>
  41. /// <param name="fileName">文件类型的扩展名或文件的绝对路径</param>
  42. /// <param name="isLargeIcon">是否返回大图标</param>
  43. /// <returns>获取到的图标</returns>
  44. static Icon GetIcon(string fileName, bool isLargeIcon)
  45. {
  46. SHFILEINFO shfi = new SHFILEINFO();
  47. IntPtr hI;
  48. if (isLargeIcon)
  49. hI = NativeMethods.SHGetFileInfo(fileName, 0, ref shfi, (uint)Marshal.SizeOf(shfi), NativeMethods.SHGFI_ICON | NativeMethods.SHGFI_USEFILEATTRIBUTES | NativeMethods.SHGFI_LARGEICON);
  50. else
  51. hI = NativeMethods.SHGetFileInfo(fileName, 0, ref shfi, (uint)Marshal.SizeOf(shfi), NativeMethods.SHGFI_ICON | NativeMethods.SHGFI_USEFILEATTRIBUTES | NativeMethods.SHGFI_SMALLICON);
  52. Icon icon = Icon.FromHandle(shfi.hIcon).Clone() as Icon;
  53. NativeMethods.DestroyIcon(shfi.hIcon); //释放资源
  54. return icon;
  55. }
  56. }
  57. }