public static Icon GetFolderIcon() { // Need to add size check, although errors generated at present! uint flags = NativeMethods.ShgfiIcon | NativeMethods.Usefileattributes; flags += NativeMethods.ShgfiOpenIcon; flags += NativeMethods.ShgfiSmallicon; // Get the folder icon var shfi = new NativeMethods.Shfileinfo(); NativeMethods.SHGetFileInfo(@"C:\Windows", NativeMethods.FileAttributeDirectory, ref shfi, (uint)Marshal.SizeOf(shfi), flags); 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 var icon = (Icon)Icon.FromHandle(shfi.hIcon).Clone(); NativeMethods.DestroyIcon(shfi.hIcon); // Cleanup return icon; }
public static Icon GetSmallIcon(string fileName) { try { if (string.IsNullOrEmpty(fileName)) { Logger.LogError("Invalid file name passed into GetLargeIcon."); return null; } // This just ensures that multiple threads don't try access the cache at the same time. lock (_lock) { // Caching the icon to prevent Win32 handle that was passed to Icon is not valid or is the wrong type. string extension = Path.GetExtension(fileName); if (string.IsNullOrEmpty(extension)) { //Global.Logger.Info("Failed to get the extension for the following file: " + fileName); // let it continue so that it returns the default missing icon. } else if (IconCache.ContainsKey(extension)) { return IconCache[extension]; } var shinfo = new NativeMethods.Shfileinfo(); NativeMethods.SHGetFileInfo(fileName, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), NativeMethods.ShgfiIcon | NativeMethods.ShgfiSmallicon | NativeMethods.Usefileattributes); //The icon is returned in the hIcon member of the shinfo struct if (shinfo.hIcon != IntPtr.Zero) { var icon = (Icon)Icon.FromHandle(shinfo.hIcon).Clone(); NativeMethods.DestroyIcon(shinfo.hIcon); if (!string.IsNullOrEmpty(extension) && extension.ToLower() != ".exe") // exe files can have different icons { IconCache.Add(extension, icon); } return icon; } return null; } } catch (Exception) { return null; } }
public static Icon GetLargeIcon(string fileName) { if (string.IsNullOrEmpty(fileName)) { Logger.LogError("Invalid file name passed into GetLargeIcon."); return null; } var shinfo = new NativeMethods.Shfileinfo(); NativeMethods.SHGetFileInfo(fileName, 0, ref shinfo, (uint) Marshal.SizeOf(shinfo), NativeMethods.ShgfiIcon | NativeMethods.ShgfiLargeicon | NativeMethods.Usefileattributes); var icon = (Icon) Icon.FromHandle(shinfo.hIcon).Clone(); NativeMethods.DestroyIcon(shinfo.hIcon); return icon; }