private static FileInfo InternalGetFileInfo(string name, bool linkOverlay, IconSize size) { NativeMethods.Shell32.SHFILEINFO shfi = new NativeMethods.Shell32.SHFILEINFO(); NativeMethods.Shell32.SHGFI flags = NativeMethods.Shell32.SHGFI.Icon | NativeMethods.Shell32.SHGFI.UseFileAttributes | NativeMethods.Shell32.SHGFI.DisplayName | NativeMethods.Shell32.SHGFI.TypeName; if (linkOverlay) { flags |= NativeMethods.Shell32.SHGFI.LinkOverlay; } /* Check the size specified for return. */ if (IconSize.Small == size) { flags |= NativeMethods.Shell32.SHGFI.SmallIcon; // include the small icon flag } else { flags |= NativeMethods.Shell32.SHGFI.LargeIcon; // include the large icon flag } NativeMethods.Shell32.SHGetFileInfo( name, NativeMethods.Shell32.FILE_ATTRIBUTE_NORMAL, ref shfi, (uint)System.Runtime.InteropServices.Marshal.SizeOf(shfi), flags); // Copy (clone) the returned icon to a new object, thus allowing us // to call DestroyIcon immediately System.Drawing.Icon icon = (System.Drawing.Icon) System.Drawing.Icon.FromHandle(shfi.hIcon).Clone(); NativeMethods.User32.DestroyIcon(shfi.hIcon); // Cleanup FileInfo fileInfo = new FileInfo { DisplayName = shfi.szDisplayName, TypeName = shfi.szTypeName }; if (IconSize.Small == size) { fileInfo.SmallIcon = icon.ToImageSource(); } else { fileInfo.LargeIcon = icon.ToImageSource(); } return(fileInfo); }
private static FileInfo GetFolderIconInternal(IconSize size, FolderType folderType) { // Need to add size check, although errors generated at present! NativeMethods.Shell32.SHGFI flags = NativeMethods.Shell32.SHGFI.Icon | NativeMethods.Shell32.SHGFI.UseFileAttributes; if (FolderType.Open == folderType) { flags |= NativeMethods.Shell32.SHGFI.OpenIcon; } if (IconSize.Small == size) { flags |= NativeMethods.Shell32.SHGFI.SmallIcon; } else { flags |= NativeMethods.Shell32.SHGFI.LargeIcon; } NativeMethods.Shell32.SHFILEINFO shfi; shfi.hIcon = IntPtr.Zero; System.Drawing.Icon icon; try { // Get the folder icon shfi = new NativeMethods.Shell32.SHFILEINFO(); int ret = NativeMethods.Shell32.SHGetFileInfo( "empty", NativeMethods.Shell32.FILE_ATTRIBUTE_DIRECTORY, ref shfi, (uint)System.Runtime.InteropServices.Marshal.SizeOf(shfi), flags); System.Drawing.Icon.FromHandle(shfi.hIcon); // Load the icon from an HICON handle // Now clone the icon, so that it can be successfully stored in an ImageList icon = (System.Drawing.Icon)System.Drawing.Icon.FromHandle(shfi.hIcon).Clone(); } finally { if (shfi.hIcon != IntPtr.Zero) { NativeMethods.User32.DestroyIcon(shfi.hIcon); // Cleanup } } FileInfo fileInfo = new FileInfo { DisplayName = shfi.szDisplayName, TypeName = shfi.szTypeName }; if (size == IconSize.Small) { fileInfo.SmallIcon = icon.ToImageSource(); } else { fileInfo.LargeIcon = icon.ToImageSource(); } return(fileInfo); }