/// <summary> /// 获取文件类型的关联图标 /// </summary> /// <param name="fileName">文件类型的扩展名或文件的绝对路径</param> /// <param name="isLargeIcon">是否返回大图标</param> /// <returns>获取到的图标</returns> public static Icon GetIcon(string fileName, bool isLargeIcon) { SHFILEINFO shfi = new SHFILEINFO(); IntPtr hI; if (isLargeIcon) { hI = APIs.SHGetFileInfo(fileName, 0, ref shfi, (uint)Marshal.SizeOf(shfi), (uint)FileInfoFlags.SHGFI_ICON | (uint)FileInfoFlags.SHGFI_USEFILEATTRIBUTES | (uint)FileInfoFlags.SHGFI_LARGEICON); } else { hI = APIs.SHGetFileInfo(fileName, 0, ref shfi, (uint)Marshal.SizeOf(shfi), (uint)FileInfoFlags.SHGFI_ICON | (uint)FileInfoFlags.SHGFI_USEFILEATTRIBUTES | (uint)FileInfoFlags.SHGFI_SMALLICON); } Icon icon = Icon.FromHandle(shfi.hIcon).Clone() as Icon; APIs.DestroyIcon(shfi.hIcon); //释放资源 return(icon); }
/// <summary> /// 获取文件夹图标 /// </summary> /// <returns>图标</returns> public static Icon GetDirectoryIcon(bool isLargeIcon) { SHFILEINFO _SHFILEINFO = new SHFILEINFO(); IntPtr _IconIntPtr; if (isLargeIcon) { _IconIntPtr = APIs.SHGetFileInfo(@"", 0, ref _SHFILEINFO, (uint)Marshal.SizeOf(_SHFILEINFO), ((uint)FileInfoFlags.SHGFI_ICON | (uint)FileInfoFlags.SHGFI_LARGEICON)); } else { _IconIntPtr = APIs.SHGetFileInfo(@"", 0, ref _SHFILEINFO, (uint)Marshal.SizeOf(_SHFILEINFO), ((uint)FileInfoFlags.SHGFI_ICON | (uint)FileInfoFlags.SHGFI_SMALLICON)); } if (_IconIntPtr.Equals(IntPtr.Zero)) { return(null); } Icon _Icon = System.Drawing.Icon.FromHandle(_SHFILEINFO.hIcon); return(_Icon); }