Search code examples
c#windows-10console-application.net-core-2.0

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:


Solution

  • 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://learn.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 );
    }