C# 获取操作系统的主题强调色和颜色主题的方法

作者: zengde 分类: 笔记 发布时间: 2021-12-08 01:47

系统强调色

通过调用API即可实现

// See "https://docs.microsoft.com/en-us/windows/win32/api/dwmapi/nf-dwmapi-dwmgetcolorizationcolor"
[System.Runtime.InteropServices.DllImport("dwmapi.dll", PreserveSig = false)]
public static extern void DwmGetColorizationColor(out int pcrColorization, out bool pfOpaqueBlend);

public static System.Drawing.Color GetColor(int argb) => System.Drawing.Color.FromArgb(argb);
/*
public static System.Windows.Media.Color GetColor(int argb) => new System.Windows.Media.Color()
{
    A = (byte)(argb >> 24),
    R = (byte)(argb >> 16),
    G = (byte)(argb >> 8),
    B = (byte)(argb)
};
*/
// 使用例
static void Main(string[] args)
{
    try
    {
        DwmGetColorizationColor(out int pcrColorization, out _);
        var color = GetColor(pcrColorization);
    }
    catch { }
}

颜色模式

通过访问注册表实现

// true为深色模式 反之false
private static bool GetWindowsTheme()
{
    const string RegistryKeyPath = @"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize";
    const string RegistryValueName = "AppsUseLightTheme";
    // 这里也可能是LocalMachine(HKEY_LOCAL_MACHINE)
    // see "https://www.addictivetips.com/windows-tips/how-to-enable-the-dark-theme-in-windows-10/"
    object registryValueObject = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(RegistryKeyPath)?.GetValue(RegistryValueName);
    if (registryValueObject is null) return false;
    return (int)registryValueObject> 0 ? false : true;
}