using System; using System.Drawing; using Vanara.PInvoke; using static Vanara.PInvoke.Kernel32; using static Vanara.PInvoke.User32_Gdi; namespace Vanara.Windows.Shell { /// Wraps the icon location string used by some Shell classes. public class IconLocation { /// Initializes a new instance of the class. public IconLocation() { } /// Initializes a new instance of the class. /// The module file name. /// If this number is positive, this is the index of the resource in the module file. If negative, the absolute value of the number is the resource ID of the icon in the module file. public IconLocation(string module, int resourceIdOrIndex) { ModuleFileName = module; ResourceId = resourceIdOrIndex; } /// Gets the icon referred to by this instance. /// The icon. public Icon Icon { get { if (!IsValid) return null; using (var lib = LoadLibraryEx(ModuleFileName, LoadLibraryExFlags.LOAD_LIBRARY_AS_IMAGE_RESOURCE)) return new SafeHICON(LoadImage(lib, ResourceId, LoadImageType.IMAGE_ICON, 0, 0, 0)).ToIcon(); //var hIconEx = new[] { IntPtr.Zero }; //if (large) // ExtractIconEx(loc.ModuleFileName, loc.ResourceId, hIconEx, null, 1); //else // ExtractIconEx(loc.ModuleFileName, loc.ResourceId, null, hIconEx, 1); } } /// Returns true if this location is valid. /// true if this location is valid; otherwise, false. public bool IsValid => System.IO.File.Exists(ModuleFileName) && ResourceId != 0; /// Gets or sets the module file name. /// The module file name. public string ModuleFileName { get; set; } /// Gets or sets the resource index or resource ID. /// If this number is positive, this is the index of the resource in the module file. If negative, the absolute value of the number is the resource ID of the icon in the module file. public int ResourceId { get; set; } /// Gets the string value. /// The string value. public string StringValue => IsValid ? ToString() : null; /// Tries to parse the specified string to create a instance. /// The string representation in the format of either "ModuleFileName,ResourceIndex" or "ModuleFileName,-ResourceID". /// The resulting instance on success. /// true if successfully parsed. public static bool TryParse(string value, out IconLocation loc) { var parts = value?.Split(','); if (parts != null && parts.Length == 2 && int.TryParse(parts[1], out var i)) { loc = new IconLocation(parts[0], i); return true; } loc = new IconLocation(); return false; } /// Returns a that represents this instance. /// A that represents this instance. public override string ToString() => IsValid ? $"{ModuleFileName},{ResourceId}" : string.Empty; } }