简体   繁体   中英

C# console get Windows 10 Accent Color

Is there a way in .Net Core 2.X to read the Selected Windows 10 Accent Color in a Console Application.

Most of the solution I found are UWP or WPF apps.

Too show you which color I mean, here is a picture of it:

Starting with .NET Core 3.0 it is also possible to call UWP APIs from non UWP apps with the help ofMicrosoft.Windows.SDK.Contracts package.

So we can use UWP API to get accent color from .NET Core console app using:

var uiSettings = new UISettings();
var accentColor = uiSettings.GetColorValue(UIColorType.Accent);

The returned color is of type Windows.UI.Color , but can easily converted into for example System.Drawing.Color

Color.FromArgb(accentColor.A, accentColor.R, accentColor.G, accentColor.B);

HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\DWM\\ - Stores all decoration colors. So if app launched with rights to HKEY_CURRENT_USER you can read or change " AccentColor " property (and others in directory) or change the color code in hexadecimal notation on your own.

To get access to windows registry you need to install package:https://www.nuget.org/packages/Microsoft.Windows.Compatibility/

Here info about package: https://docs.microsoft.com/en-us/dotnet/core/porting/windows-compat-pack/


The color values are stored as Registry DWORD (32-bit integer) values in ABGR order (as opposed to ARGB or RGBA order).

using Microsoft.Win32;

public static ( Byte r, Byte g, Byte b, Byte a ) GetAccentColor()
{
    const String DWM_KEY = @"Software\Microsoft\Windows\DWM";
    using( RegistryKey dwmKey = Registry.CurrentUser.OpenSubKey( DWM_KEY, RegistryKeyPermissionCheck.ReadSubTree ) )
    {
        const String KEY_EX_MSG = "The \"HKCU\\" + DWM_KEY + "\" registry key does not exist.";
        if( dwmKey is null ) throw new InvalidOperationException( KEY_EX_MSG );

        Object accentColorObj = dwmKey.GetValue( "AccentColor" );
        if( accentColorObj is Int32 accentColorDword )
        {
            return ParseDWordColor( accentColorDword );
        }
        else
        {
            const String VALUE_EX_MSG = "The \"HKCU\\" + DWM_KEY + "\\AccentColor\" registry key value could not be parsed as an ABGR color.";
            throw new InvalidOperationException( VALUE_EX_MSG );
        }
    }

}

private static ( Byte r, Byte g, Byte b, Byte a ) ParseDWordColor( Int32 color )
{
    Byte
        a = ( color >> 24 ) & 0xFF,
        b = ( color >> 16 ) & 0xFF,
        g = ( color >>  8 ) & 0xFF,
        r = ( color >>  0 ) & 0xFF;

    return ( r, g, b, a );
}

In .NET 5, (Unlike with .NET Core 3.0) you don't have to reference the Microsoft.Windows.SDK.Contracts NuGet package.

Open your csproj file and update it like the following:

<PropertyGroup>
  <TargetFramework>net5.0-windows10.0.17763.0</TargetFramework>
</PropertyGroup>

Supported platforms: 10.0.17763.0 10.0.18362.0 10.0.19041.0

And use it like this (From Erko's answer):

var uiSettings = new UISettings();
var accentColor = uiSettings.GetColorValue(UIColorType.Accent);

This works for desktop apps as well as Web Apps (ASP.NET Core).

In my case, I was working with Electron.NET and ASP.NET Core and it works flawlessly.

Source: Windows Developer Blog - Calling Windows APIs in .NET5

you can use a 'couple' of calls, and it works when "Automatically pick an accent color from my background" is enabled as well

    public static Color GetWindowsAccentColor()
    {
        WinApi.DWMCOLORIZATIONcolors colors = new WinApi.DWMCOLORIZATIONcolors();
        WinApi.DwmGetColorizationParameters(ref colors);

        //get the theme --> only if Windows 10 or newer
        if (OS.IsWindows10orGreater())
            return ParseColor((int)colors.ColorizationColor); 
        else
            return Color.CadetBlue; 
    }

    private static Color ParseColor(Int32 color)
    {
        var opaque = true;

        return Color.FromArgb((byte)(opaque ? 255 : (color >> 24) & 0xff),
            (byte)((color >> 16) & 0xff),
            (byte)((color >> 8) & 0xff),
            (byte)(color) & 0xff);
    }

having WinApi class with:

    public struct DWMCOLORIZATIONcolors
    {
        public uint ColorizationColor,
            ColorizationAfterglow,
            ColorizationColorBalance,
            ColorizationAfterglowBalance,
            ColorizationBlurBalance,
            ColorizationGlassReflectionIntensity,
            ColorizationOpaqueBlend;
    }

    [DllImport("dwmapi.dll", EntryPoint = "#127")]
    public static extern void DwmGetColorizationParameters(ref DWMCOLORIZATIONcolors colors);

and OS class with:

    public static bool IsWindows10orGreater()
    {
        if (WindowsVersion() >= 10)
            return true;
        else
            return false;

    }

    public static int WindowsVersion()
    {
        //for .Net4.8 and Minor
        int result = 10;
        var reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion");
        string[] productName = reg.GetValue("ProductName").ToString().Split((char)32);
        int.TryParse(productName[1], out result);
        return result;

        //fixed .Net6
        //return System.Environment.OSVersion.Version.Major;
    }

Hope this Helps Angelo

use winrt-api

.net 5 example:

GetAccentColor.csproj

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net5.0-windows10.0.19041.0</TargetFramework>
  </PropertyGroup>

</Project>

Program.cs

using System;

namespace GetAccentColor
{
    public static class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine($"GetAccentColor = {GetAccentColor()}");
        }

        public static Windows.UI.Color GetAccentColor()
        {
            var color = new Windows.UI.Color();
            if (Windows.Foundation.Metadata.ApiInformation.IsMethodPresent("Windows.UI.ViewManagement.UISettings", "GetColorValue"))
            {
                var uiSettings = new Windows.UI.ViewManagement.UISettings();
                color = uiSettings.GetColorValue(Windows.UI.ViewManagement.UIColorType.Accent);
            }
            return color;
        }
    }
}

Result: 获取重音颜色

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM