From f48bd1acba5667865678441915ee4457a77958cf Mon Sep 17 00:00:00 2001 From: dahall Date: Wed, 28 Oct 2020 22:40:36 -0600 Subject: [PATCH] Added GetSystemIcon overload that uses an index and optimized methods. --- Windows.Shell/ShellImageList.cs | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/Windows.Shell/ShellImageList.cs b/Windows.Shell/ShellImageList.cs index 92f65356..7d7f613c 100644 --- a/Windows.Shell/ShellImageList.cs +++ b/Windows.Shell/ShellImageList.cs @@ -29,6 +29,8 @@ namespace Vanara.Windows.Shell /// Represents the System Image List holding images for all shell icons. public static class ShellImageList { + private static HIMAGELIST hSystemImageList; + /// Gets the system icon for the given file name or extension. /// The file name or extension. /// Size of the icon. @@ -36,12 +38,22 @@ namespace Vanara.Windows.Shell public static Icon GetSystemIcon(string fileNameOrExtension, ShellImageSize iconSize = ShellImageSize.Large) { var shfi = new SHFILEINFO(); - var hImageList = (HIMAGELIST)SHGetFileInfo(fileNameOrExtension, 0, ref shfi, SHFILEINFO.Size, SHGFI.SHGFI_SYSICONINDEX | (iconSize == ShellImageSize.Small ? SHGFI.SHGFI_SMALLICON : 0)); - if (hImageList.IsNull) return null; + if (hSystemImageList.IsNull) + hSystemImageList = SHGetFileInfo(fileNameOrExtension, 0, ref shfi, SHFILEINFO.Size, SHGFI.SHGFI_SYSICONINDEX | (iconSize == ShellImageSize.Small ? SHGFI.SHGFI_SMALLICON : 0)); + if (hSystemImageList.IsNull) return null; if (iconSize <= ShellImageSize.Small) - return ImageList_GetIcon(hImageList, shfi.iIcon, IMAGELISTDRAWFLAGS.ILD_TRANSPARENT).ToIcon(); + return ImageList_GetIcon(hSystemImageList, shfi.iIcon, IMAGELISTDRAWFLAGS.ILD_TRANSPARENT).ToIcon(); + return GetSystemIcon(shfi.iIcon, iconSize); + } + + /// Gets the system icon for and index and size. + /// The index of the system icon to retrieve. + /// Size of the icon. + /// An instance if found; otherwise . + public static Icon GetSystemIcon(int index, ShellImageSize iconSize = ShellImageSize.Large) + { SHGetImageList((SHIL)iconSize, typeof(IImageList).GUID, out var il).ThrowIfFailed(); - return il.GetIcon(shfi.iIcon, IMAGELISTDRAWFLAGS.ILD_TRANSPARENT).ToIcon(); + return il.GetIcon(index, IMAGELISTDRAWFLAGS.ILD_TRANSPARENT)?.ToIcon(); } /// Gets the Shell icon for the given file name or extension.