Search code examples
c#windowswinformsthemesdarkmode

How to make WinForm use the system dark mode theme?


Can WinForm use system dark mode theme like explorer or StartAllBack?

I've tried these things:

int trueValue = 0x01, falseValue = 0x00;
SetWindowTheme(this.Handle, "DarkMode_Explorer", null);
DwmSetWindowAttribute(this.Handle, DwmWindowAttribute.DWMWA_USE_IMMERSIVE_DARK_MODE, ref trueValue, Marshal.SizeOf(typeof(int)));
DwmSetWindowAttribute(this.Handle, DwmWindowAttribute.DWMWA_MICA_EFFECT, ref trueValue, Marshal.SizeOf(typeof(int)));

But these only make the titlebar and scrollbar in dark, no difference for other controls.

How to make all controls to system dark style, like this:

Dark mode theme Explorer


P.S.

If you apply this code only to the form's handle, this will only take effect for the title bar. However, if you iterate through the handles of all controls to apply this code, this will apply the dark theme to some controls, but not all controls.

private void ThemeAllControls(Control parent = null) {
    parent = parent ?? this;
    Action<Control> Theme = control => {
        int trueValue = 0x01;
        SetWindowTheme(control.Handle, "DarkMode_Explorer", null);
        DwmSetWindowAttribute(control.Handle, DwmWindowAttribute.DWMWA_USE_IMMERSIVE_DARK_MODE, ref trueValue, Marshal.SizeOf(typeof(int)));
        DwmSetWindowAttribute(control.Handle, DwmWindowAttribute.DWMWA_MICA_EFFECT, ref trueValue, Marshal.SizeOf(typeof(int)));
    };
    if (parent == this) Theme(this);
    foreach (Control control in parent.Controls) {
        Theme(control);
        if (control.Controls.Count != 0)
            ThemeAllControls(control);
    }
}

Dark mode for only a few controls

As you can see in the picture above, only the titlebar, all scrollbars, checkboxes, radio buttons (or maybe more controls I don't know) have the dark theme applied.

In addition, if you make additional color settings for the controls, they can indeed become similar to that dark theme, but the appearance of many controls behaves abnormally. For example, the style of the buttons in the picture does not match the button style in the real dark theme. Some controls are still represented in their original colors, but the text color has changed to white, making it impossible to read the text clearly.

control.BackColor = Color.FromArgb(32, 32, 32);
control.ForeColor = Color.White;

The fake dark theme

This is what real dark mode button and list view, used in Internet Download Manager (IDM).
(Although IDM may be developed using WPF, I believe those dark themes invoked using the Win32 API.)

Real dark mode


Solution

  • Based on the answers here and from other sources i made a Class "DarkModeCS" to automatically Apply DarkMode Color into all your Controls.

    Check it: https://github.com/BlueMystical/Dark-Mode-Forms