How to enable dark title bar in Windows Forms and WPF (Windows Presentation Foundation) apps
Windows has had a dark mode feature for a long time now, however, as a Windows Forms and/or WPF developer, you may have noticed that the Windows dark mode does not affect your app at all automatically - in fact the Windows dark mode only affects UWP, WinUI and Chromium based user interfaces - there's no support for Windows dark mode in Windows Forms and WPF.
Luckily, it is very easy to determine if dark mode is currently enabled and be notified any time dark mode is switched on or off - from there it's just a matter of updating your UI to match which mode Windows is in. While this may work fine for the client area of your app (i.e. the area of your app that does not include the title bar and border), you don't have a lot of control over the non-client area of your app and you'll notice that by default, the title bar and border of any Windows Forms or WPF window will not adjust to dark mode regardless of the user's dark mode settings. Luckily, Windows includes a function that you can use to tell the DWM (Desktop Window Manager), which is responsible for drawing your app windows' title bars, to draw the title bar and border in dark mode like so:
To change the title bar back to light mode, simply call the same code by replace 'True' with 'False.
Tip: If calling this in a WPF Window's constructor, consider instead using the SourceInitialized or Loaded event, or using WindowInteropHelper.EnsureHandle() to ensure the window has a handle, otherwise, the window will not yet have a handle and therefore, this function will not work as it needs a window handle to apply the attribute to.
For more information about the DwmSetWindowAttribute function, see: