diff --git a/src/Titano.Core.Windows/Window/DwmWindow.cs b/src/Titano.Core.Windows/Window/DwmWindow.cs new file mode 100644 index 00000000..a3de3229 --- /dev/null +++ b/src/Titano.Core.Windows/Window/DwmWindow.cs @@ -0,0 +1,66 @@ +using System.Runtime.InteropServices; +using Titano.Core.Windows.Interop; + +namespace Titano.Core.Windows.Window; + +/// DWMWA_SYSTEMBACKDROP_TYPE values (Windows 11 22H2+). +public enum SystemBackdrop +{ + Auto = 0, + None = 1, + Mica = 2, + Acrylic = 3, + MicaAlt = 4, +} + +/// DWMWA_WINDOW_CORNER_PREFERENCE values (Windows 11+). +public enum WindowCornerPreference +{ + Default = 0, + DoNotRound = 1, + Round = 2, + RoundSmall = 3, +} + +/// +/// 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. +/// +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; + + /// Dark title bar (attribute 20; 19 on Windows 10 1809–1909). + 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); + + /// Title bar colour; null restores the system default. + public static bool SetCaptionColor(nint window, RgbColor? color) => + Win32Window.Exists(window) && Set(window, DWMWA_CAPTION_COLOR, unchecked((int)(color?.ToColorRef() ?? DWMWA_COLOR_DEFAULT))); + + /// Window border colour; null restores the system default. + 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); +} diff --git a/src/Titano.Core.Windows/Window/RgbColor.cs b/src/Titano.Core.Windows/Window/RgbColor.cs new file mode 100644 index 00000000..5dc12f39 --- /dev/null +++ b/src/Titano.Core.Windows/Window/RgbColor.cs @@ -0,0 +1,16 @@ +namespace Titano.Core.Windows.Window; + +/// An opaque 8-bit sRGB colour, as used by DWM window chrome and the system accent. +public readonly record struct RgbColor(byte R, byte G, byte B) +{ + /// Win32 COLORREF layout 0x00BBGGRR. + internal uint ToColorRef() => R | ((uint)G << 8) | ((uint)B << 16); + + /// From 0xAABBGGRR (COLORREF with alpha, as stored in the registry's AccentColor). + internal static RgbColor FromAbgr(uint value) => new((byte)value, (byte)(value >> 8), (byte)(value >> 16)); + + /// From 0xAARRGGBB (DwmGetColorizationColor). + 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}"; +} diff --git a/src/Titano.Core.Windows/Window/SystemTheme.cs b/src/Titano.Core.Windows/Window/SystemTheme.cs new file mode 100644 index 00000000..fc8f388e --- /dev/null +++ b/src/Titano.Core.Windows/Window/SystemTheme.cs @@ -0,0 +1,37 @@ +using System.Runtime.InteropServices; +using Microsoft.Win32; + +namespace Titano.Core.Windows.Window; + +/// The user's light/dark app mode and accent colour, read on demand (see for changes). +public static partial class SystemTheme +{ + internal const string PersonalizeKey = @"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize"; + internal const string DwmKey = @"Software\Microsoft\Windows\DWM"; + + /// HKCU …\Themes\Personalize\AppsUseLightTheme; true when absent (the Windows default). + public static bool AppsUseLightTheme + { + get + { + using var key = Registry.CurrentUser.OpenSubKey(PersonalizeKey); + return key?.GetValue("AppsUseLightTheme") is not int value || value != 0; + } + } + + /// The accent colour: HKCU …\DWM\AccentColor, else DwmGetColorizationColor; null when neither is available. + 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); +} diff --git a/src/Titano.Core.Windows/Window/SystemThemeWatcher.cs b/src/Titano.Core.Windows/Window/SystemThemeWatcher.cs new file mode 100644 index 00000000..b04ae165 --- /dev/null +++ b/src/Titano.Core.Windows/Window/SystemThemeWatcher.cs @@ -0,0 +1,95 @@ +using System.Runtime.InteropServices; +using Microsoft.Win32; +using Microsoft.Win32.SafeHandles; +using Titano.Core.Diagnostics; + +namespace Titano.Core.Windows.Window; + +/// +/// Raises 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. +/// +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(); + } + + /// Raised once per effective change of or . + 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().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); +} diff --git a/tests/Titano.Core.Windows.Tests/Window/WindowTests.cs b/tests/Titano.Core.Windows.Tests/Window/WindowTests.cs new file mode 100644 index 00000000..e6d0cd8b --- /dev/null +++ b/tests/Titano.Core.Windows.Tests/Window/WindowTests.cs @@ -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)); + } +}