Changing the color of the title bar in WinForm

I created a C# class using @Jonas Kohls answer from here

The class works like a charm and makes it easy to work with multiple forms just call DarkTitleBarClass.UseImmersiveDarkMode(Handle, true); in your load method.

I used this when upgrading some old WinForms apps so its WinForm friendly but only tested on win 8,10 and 11

Example image below Winforms .NetCore 6.0

enter image description here

using System.Runtime.InteropServices;

namespace Myapp.Classes
{
internal class DarkTitleBarClass
{
    [DllImport("dwmapi.dll")]
    private static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, 
    ref int attrValue, int attrSize);

    private const int DWMWA_USE_IMMERSIVE_DARK_MODE_BEFORE_20H1 = 19;
    private const int DWMWA_USE_IMMERSIVE_DARK_MODE = 20;

    internal static bool UseImmersiveDarkMode(IntPtr handle, bool enabled)
    {
        if (IsWindows10OrGreater(17763))
        {
            var attribute = DWMWA_USE_IMMERSIVE_DARK_MODE_BEFORE_20H1;
            if (IsWindows10OrGreater(18985))
            {
                attribute = DWMWA_USE_IMMERSIVE_DARK_MODE;
            }

            int useImmersiveDarkMode = enabled ? 1 : 0;
            return DwmSetWindowAttribute(handle, attribute, ref useImmersiveDarkMode, sizeof(int)) == 0;
        }

        return false;
    }

    private static bool IsWindows10OrGreater(int build = -1)
    {
        return Environment.OSVersion.Version.Major >= 10 && Environment.OSVersion.Version.Build >= build;
    }
  }
}

[EDIT] Don't forget to add a app.manifest and uncomment the appropriate supported OS.


I solved this problem. This is the code:

[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);

[DllImport("User32.dll")]
private static extern IntPtr GetWindowDC(IntPtr hWnd);

protected override void WndProc(ref Message m)
{
    base.WndProc(ref m);
    const int WM_NCPAINT = 0x85;
    if (m.Msg == WM_NCPAINT)
    {
        IntPtr hdc = GetWindowDC(m.HWnd);
        if ((int)hdc != 0)
        {
            Graphics g = Graphics.FromHdc(hdc);
            g.FillRectangle(Brushes.Green, new Rectangle(0, 0, 4800, 23));
            g.Flush();
            ReleaseDC(m.HWnd, hdc);
        }
    }
}

What you can do is set the FormBorderStyle property to None and do what ever you want with the form using GDI.