feat(windows): add DWM window chrome and system theme watcher

DwmWindow sets dark mode (attribute 20, 19 on older Windows 10), Mica/none
backdrop, corner preference and caption/border colours, returning false for
null or stale windows and unsupported builds. SystemTheme reads
AppsUseLightTheme and the accent colour (DWM AccentColor, else
DwmGetColorizationColor); SystemThemeWatcher raises Changed from a
RegNotifyChangeKeyValue thread when either value actually changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-02 09:46:40 +00:00
1 parent 6f765aafbc
commit 598433773e
5 files changed
+266

No files matched your search

@@ -0,0 +1,66 @@
using System.Runtime.InteropServices;
using Titano.Core.Windows.Interop;
namespace Titano.Core.Windows.Window;
/// <summary>DWMWA_SYSTEMBACKDROP_TYPE values (Windows 11 22H2+).</summary>
public enum SystemBackdrop
{
Auto = 0,
None = 1,
Mica = 2,
Acrylic = 3,
MicaAlt = 4,
}
/// <summary>DWMWA_WINDOW_CORNER_PREFERENCE values (Windows 11+).</summary>
public enum WindowCornerPreference
{
Default = 0,
DoNotRound = 1,
Round = 2,
RoundSmall = 3,
}
/// <summary>
/// Window chrome through DwmSetWindowAttribute (BRIEF §2.1). Every helper returns false, without throwing, when the
/// handle is null or stale or this Windows build does not support the attribute, so callers need no version checks.
/// </summary>
public static partial class DwmWindow
{
private const uint DWMWA_USE_IMMERSIVE_DARK_MODE_BEFORE_20H1 = 19;
private const uint DWMWA_USE_IMMERSIVE_DARK_MODE = 20;
private const uint DWMWA_WINDOW_CORNER_PREFERENCE = 33;
private const uint DWMWA_BORDER_COLOR = 34;
private const uint DWMWA_CAPTION_COLOR = 35;
private const uint DWMWA_SYSTEMBACKDROP_TYPE = 38;
private const uint DWMWA_COLOR_DEFAULT = 0xFFFFFFFF;
/// <summary>Dark title bar (attribute 20; 19 on Windows 10 1809–1909).</summary>
public static bool SetDarkMode(nint window, bool enabled)
{
if (!Win32Window.Exists(window)) return false;
var value = enabled ? 1 : 0;
return Set(window, DWMWA_USE_IMMERSIVE_DARK_MODE, value) || Set(window, DWMWA_USE_IMMERSIVE_DARK_MODE_BEFORE_20H1, value);
}
public static bool SetBackdrop(nint window, SystemBackdrop backdrop) =>
Win32Window.Exists(window) && Set(window, DWMWA_SYSTEMBACKDROP_TYPE, (int)backdrop);
public static bool SetCornerPreference(nint window, WindowCornerPreference preference) =>
Win32Window.Exists(window) && Set(window, DWMWA_WINDOW_CORNER_PREFERENCE, (int)preference);
/// <summary>Title bar colour; null restores the system default.</summary>
public static bool SetCaptionColor(nint window, RgbColor? color) =>
Win32Window.Exists(window) && Set(window, DWMWA_CAPTION_COLOR, unchecked((int)(color?.ToColorRef() ?? DWMWA_COLOR_DEFAULT)));
/// <summary>Window border colour; null restores the system default.</summary>
public static bool SetBorderColor(nint window, RgbColor? color) =>
Win32Window.Exists(window) && Set(window, DWMWA_BORDER_COLOR, unchecked((int)(color?.ToColorRef() ?? DWMWA_COLOR_DEFAULT)));
private static unsafe bool Set(nint window, uint attribute, int value) =>
DwmSetWindowAttribute(window, attribute, &value, sizeof(int)) >= 0;
[LibraryImport("dwmapi.dll")]
private static unsafe partial int DwmSetWindowAttribute(nint window, uint attribute, void* value, uint size);
}
@@ -0,0 +1,16 @@
namespace Titano.Core.Windows.Window;
/// <summary>An opaque 8-bit sRGB colour, as used by DWM window chrome and the system accent.</summary>
public readonly record struct RgbColor(byte R, byte G, byte B)
{
/// <summary>Win32 COLORREF layout 0x00BBGGRR.</summary>
internal uint ToColorRef() => R | ((uint)G << 8) | ((uint)B << 16);
/// <summary>From 0xAABBGGRR (COLORREF with alpha, as stored in the registry's AccentColor).</summary>
internal static RgbColor FromAbgr(uint value) => new((byte)value, (byte)(value >> 8), (byte)(value >> 16));
/// <summary>From 0xAARRGGBB (DwmGetColorizationColor).</summary>
internal static RgbColor FromArgb(uint value) => new((byte)(value >> 16), (byte)(value >> 8), (byte)value);
public override string ToString() => $"#{R:X2}{G:X2}{B:X2}";
}
@@ -0,0 +1,37 @@
using System.Runtime.InteropServices;
using Microsoft.Win32;
namespace Titano.Core.Windows.Window;
/// <summary>The user's light/dark app mode and accent colour, read on demand (see <see cref="SystemThemeWatcher"/> for changes).</summary>
public static partial class SystemTheme
{
internal const string PersonalizeKey = @"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize";
internal const string DwmKey = @"Software\Microsoft\Windows\DWM";
/// <summary>HKCU <c>…\Themes\Personalize\AppsUseLightTheme</c>; true when absent (the Windows default).</summary>
public static bool AppsUseLightTheme
{
get
{
using var key = Registry.CurrentUser.OpenSubKey(PersonalizeKey);
return key?.GetValue("AppsUseLightTheme") is not int value || value != 0;
}
}
/// <summary>The accent colour: HKCU <c>…\DWM\AccentColor</c>, else DwmGetColorizationColor; null when neither is available.</summary>
public static RgbColor? AccentColor
{
get
{
using (var key = Registry.CurrentUser.OpenSubKey(DwmKey))
{
if (key?.GetValue("AccentColor") is int abgr) return RgbColor.FromAbgr(unchecked((uint)abgr));
}
return DwmGetColorizationColor(out var argb, out _) >= 0 ? RgbColor.FromArgb(argb) : null;
}
}
[LibraryImport("dwmapi.dll")]
private static partial int DwmGetColorizationColor(out uint colorization, out int opaqueBlend);
}
@@ -0,0 +1,95 @@
using System.Runtime.InteropServices;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using Titano.Core.Diagnostics;
namespace Titano.Core.Windows.Window;
/// <summary>
/// Raises <see cref="Changed"/> when the app light/dark mode or the accent colour changes, using
/// RegNotifyChangeKeyValue on a dedicated background thread (the registration lives as long as that thread).
/// Handlers run on that thread; marshal to the UI dispatcher.
/// </summary>
public sealed partial class SystemThemeWatcher : IDisposable
{
private const uint REG_NOTIFY_CHANGE_LAST_SET = 0x4;
private readonly ManualResetEvent _stop = new(false);
private readonly Thread _thread;
private int _disposed;
public SystemThemeWatcher()
{
_thread = new Thread(Run) { IsBackground = true, Name = "Titano theme watcher" };
_thread.Start();
}
/// <summary>Raised once per effective change of <see cref="SystemTheme.AppsUseLightTheme"/> or <see cref="SystemTheme.AccentColor"/>.</summary>
public event EventHandler? Changed;
public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) != 0) return;
_stop.Set();
// From a Changed handler the loop is still running on this thread and will observe the stop signal itself.
if (_thread == Thread.CurrentThread) return;
_thread.Join();
_stop.Dispose();
}
private void Run()
{
using var personalize = Registry.CurrentUser.OpenSubKey(SystemTheme.PersonalizeKey);
using var dwm = Registry.CurrentUser.OpenSubKey(SystemTheme.DwmKey);
var keys = new[] { personalize, dwm }.OfType<RegistryKey>().ToArray();
var signals = keys.Select(_ => new AutoResetEvent(false)).ToArray();
try
{
for (var i = 0; i < keys.Length; i++) Arm(keys[i], signals[i]);
WaitHandle[] handles = [_stop, .. signals];
var last = (SystemTheme.AppsUseLightTheme, SystemTheme.AccentColor);
while (true)
{
var index = WaitHandle.WaitAny(handles);
if (index == 0) return;
// Re-arm before reading so a change landing in between still signals.
Arm(keys[index - 1], signals[index - 1]);
var now = (SystemTheme.AppsUseLightTheme, SystemTheme.AccentColor);
if (now == last) continue;
last = now;
RaiseChanged();
}
}
finally
{
foreach (var signal in signals) signal.Dispose();
}
}
private static void Arm(RegistryKey key, AutoResetEvent signal)
{
var result = RegNotifyChangeKeyValue(key.Handle, false, REG_NOTIFY_CHANGE_LAST_SET, signal.SafeWaitHandle, true);
if (result != 0) Log.Warning("theme", $"RegNotifyChangeKeyValue failed for {key.Name} (error {result}).");
}
private void RaiseChanged()
{
try
{
Changed?.Invoke(this, EventArgs.Empty);
}
catch (Exception ex)
{
// An exception escaping this thread would terminate the process.
Log.Error("theme", "A theme Changed handler failed", ex);
}
}
[LibraryImport("advapi32.dll")]
private static partial int RegNotifyChangeKeyValue(
SafeRegistryHandle key,
[MarshalAs(UnmanagedType.Bool)] bool watchSubtree,
uint notifyFilter,
SafeWaitHandle eventHandle,
[MarshalAs(UnmanagedType.Bool)] bool asynchronous);
}
@@ -0,0 +1,52 @@
using Titano.Core.Windows.Window;
using Titano.Testing;
namespace Titano.Core.Windows.Tests.Window;
public sealed class WindowTests
{
private static readonly nint StaleWindow = 0x0BAD_F00D;
[Test]
[WindowsOnly]
public void DwmCallsWithoutAValidWindowReturnFalse()
{
foreach (var window in new[] { (nint)0, StaleWindow })
{
Assert.False(DwmWindow.SetDarkMode(window, true));
Assert.False(DwmWindow.SetBackdrop(window, SystemBackdrop.Mica));
Assert.False(DwmWindow.SetCornerPreference(window, WindowCornerPreference.Round));
Assert.False(DwmWindow.SetCaptionColor(window, new RgbColor(0x20, 0x20, 0x20)));
Assert.False(DwmWindow.SetBorderColor(window, null));
}
}
[Test]
[WindowsOnly]
public void SystemThemeReadsWithoutThrowing()
{
Assert.DoesNotThrow(() => _ = SystemTheme.AppsUseLightTheme);
Assert.DoesNotThrow(() => _ = SystemTheme.AccentColor);
}
[Test]
[WindowsOnly]
[Timeout(30_000)]
public void ThemeWatcherStartsAndStops()
{
var watcher = new SystemThemeWatcher();
watcher.Changed += (_, _) => { };
watcher.Dispose();
watcher.Dispose();
}
[Test]
public void ColoursConvertBetweenWin32Layouts()
{
var accent = RgbColor.FromAbgr(0xFFD77800);
Assert.Equal(new RgbColor(0x00, 0x78, 0xD7), accent);
Assert.Equal("#0078D7", accent.ToString());
Assert.Equal(0x00D77800u, accent.ToColorRef());
Assert.Equal(accent, RgbColor.FromArgb(0xFF0078D7));
}
}