How do you make the BackColor the accent color in C#?

132 Views Asked by At

I have a quick question.

So, I am working on a project in c#, just a little test, and I was wondering... (because I couldn't find anything online)

How do you make the BackColor of the form the user's accent color? (in windows)

I seem to not be able to find how to do it...

1

There are 1 best solutions below

0
Stefan Wuebbe On

If you probably mean the Windows.Forms namespace, you can do something like this

using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace WindowsFormsApp2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            var accentColor1 = GetAccentColor();
            BackColor = accentColor1;
        }

        [DllImport("uxtheme.dll", EntryPoint = "#95")]
        private static extern uint GetImmersiveColorFromColorSetEx(uint dwImmersiveColorSet, uint dwImmersiveColorType,
                                                                    bool bIgnoreHighContrast, uint dwHighContrastCacheMode);
        [DllImport("uxtheme.dll", EntryPoint = "#96")]
        private static extern uint GetImmersiveColorTypeFromName(IntPtr pName);
        
        [DllImport("uxtheme.dll", EntryPoint = "#98")]
        private static extern int GetImmersiveUserColorSetPreference(bool bForceCheckRegistry, bool bSkipCheckOnFail);

        public static Color GetAccentColor()
        {
            var userColorSet = GetImmersiveUserColorSetPreference(false, false);
            var colorType = GetImmersiveColorTypeFromName(Marshal.StringToHGlobalUni("ImmersiveStartSelectionBackground"));
            var colorSetEx = GetImmersiveColorFromColorSetEx((uint)userColorSet, colorType, false, 0);
            return ConvertDWordColorToRGB(colorSetEx);
        }

        private static Color ConvertDWordColorToRGB(uint colorSetEx)
        {
            byte redColor = (byte)((0x000000FF & colorSetEx) >> 0);
            byte greenColor = (byte)((0x0000FF00 & colorSetEx) >> 8);
            byte blueColor = (byte)((0x00FF0000 & colorSetEx) >> 16);
            byte alphaColor = (byte)((0xFF000000 & colorSetEx) >> 24);
            return Color.FromArgb(alphaColor, redColor, greenColor, blueColor);
        }
    }
}