andrew4582

FileIconUtility

Jul 28th, 2012
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.92 KB | None | 0 0
  1. using System.Runtime.InteropServices;
  2.  
  3. namespace System.Drawing
  4. {
  5.     /// <summary>
  6.     /// Utility to get the default icon from files
  7.     /// </summary>
  8.     public class FileIconUtility
  9.     {
  10.         const uint SHGFI_SYSICONINDEX = 0x4000;
  11.         const uint SHGFI_ICON = 0x100;
  12.         const uint SHGFI_LARGEICON = 0x0;
  13.         const uint SHGFI_SMALLICON = 0x1;
  14.  
  15.         [StructLayout(LayoutKind.Sequential)]
  16.         struct SHFILEINFO
  17.         {
  18.             public IntPtr hIcon;
  19.             public int iIcon;
  20.             public int dwAttributes;
  21.             public string szDisplayName;
  22.             public string szTypeName;
  23.         }
  24.  
  25.         [DllImport("Shell32.dll")]
  26.         static extern int SHGetFileInfo(string path,uint fileAttributes,out SHFILEINFO psfi,uint fileInfo,uint flags);
  27.  
  28.         [DllImport("kernel32.dll",SetLastError = true)]
  29.         [return: MarshalAs(UnmanagedType.Bool)]
  30.         static extern bool CloseHandle(IntPtr hObject);
  31.  
  32.        
  33.         public static Icon GetIcon(string path)
  34.         {
  35.             return GetIcon(path,IconSize.Small);
  36.         }
  37.  
  38.         public static Icon GetIcon(string path,IconSize iconSize)
  39.         {
  40.             SHFILEINFO info = new SHFILEINFO();
  41.            
  42.             uint size = iconSize == IconSize.Large ? SHGFI_LARGEICON : SHGFI_SMALLICON;
  43.            
  44.             uint flags = SHGFI_SYSICONINDEX | size | SHGFI_ICON;
  45.             int hTcdf = SHGetFileInfo(path,0,out info,(uint)Marshal.SizeOf(typeof(SHFILEINFO)),flags);
  46.            
  47.             IntPtr handleIcon = info.hIcon;
  48.             try
  49.             {
  50.                 Icon ico = Icon.FromHandle(handleIcon);
  51.                 return ico;
  52.             }
  53.             finally
  54.             {
  55.                 if(handleIcon != IntPtr.Zero)
  56.                     CloseHandle(handleIcon);
  57.             }
  58.         }
  59.     }
  60.  
  61.     public enum IconSize
  62.     {
  63.         Large,
  64.         Small
  65.     }
  66.  
  67. }
Advertisement
Add Comment
Please, Sign In to add comment