using System; using System.Runtime.InteropServices; using System.Text; using Vanara.Extensions; using static Vanara.PInvoke.Shell32; namespace Vanara.Windows.Shell { /// Provides a means to open Control Panel items and get their paths. public static class ControlPanel { private static SafeCP cp; /// Gets a value indicating whether the most recent Control Panel view was Classic view. /// /// if the most recent Control Panel view was Classic view; otherwise, for Category view. /// public static bool IsClassicView => CP.GetCurrentView() == CPVIEW.CPVIEW_CLASSIC; private static SafeCP CP => cp ?? (cp = new SafeCP()); /// Gets the path of a Control Panel item. /// The Control Panel item. /// The path. public static string GetPath(ControlPanelItem item) => CP.GetPath(item.CanonicalName()); /// Gets the path of a Control Panel GUID. /// The Control Panel GUID. /// The path. public static string GetPath(Guid item) => CP.GetPath(item.ToString()); /// Gets the path of a Control Panel item. /// The Control Panel item's canonical name. /// The path. public static string GetPath(string item) => CP.GetPath(item); /// Opens the Control Panel. /// if the Control Panel has been opened. if an error prevented opening. public static bool Open() => CP.Open(); /// Opens the specified Control Panel item. /// The Control Panel item. /// Optional. The Control Panel page. /// /// if this item is supported and has been opened. if an error prevented opening or /// the item or page was unsupported on this OS. /// /// page public static bool Open(ControlPanelItem item, string page = null) { if (page != null && Array.IndexOf(item.ValidPages(), page) == -1) throw new ArgumentOutOfRangeException(nameof(page)); return CP.Open(item.CanonicalName(), page); } /// Opens the specified Control Panel item. /// The Control Panel item's canonical name. /// Optional. The Control Panel page. /// /// if this item is supported and has been opened. if an error prevented opening or /// the item or page was unsupported on this OS. /// /// page public static bool Open(string item, string page = null) => CP.Open(item, page); private class SafeCP : IDisposable { internal IOpenControlPanel icp; private bool disposedValue = false; public SafeCP() => icp = new IOpenControlPanel(); ~SafeCP() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } public CPVIEW GetCurrentView() => icp.GetCurrentView(); public string GetPath(string pszName) { const int cchPath = 128; var pszPath = new StringBuilder(cchPath, cchPath); return icp.GetPath(pszName, pszPath, cchPath).Succeeded ? pszPath.ToString() : string.Empty; } public bool Open(string pszName = null, string page = null, object punkSite = null) => icp.Open(pszName, page, punkSite).Succeeded; protected virtual void Dispose(bool disposing) { if (disposedValue) return; icp = null; disposedValue = true; } } } }