@@ -74,16 +74,22 @@ _Use_decl_annotations_ int CALLBACK WinMain(HINSTANCE instance, HINSTANCE, PSTR
7474 appWindow.Resize ({1000 , 1000 });
7575
7676 // Configure title bar to respect system theme (dark mode support)
77+ // Keep uiSettings alive for the lifetime of the app so the ColorValuesChanged
78+ // event subscription is not destroyed when the variable goes out of scope.
79+ static winrt::Windows::UI::ViewManagement::UISettings s_uiSettings;
7780 try {
7881 auto titleBar = appWindow.TitleBar ();
7982 if (titleBar) {
8083 // Enable title bar theming to follow system theme
8184 titleBar.ExtendsContentIntoTitleBar (false );
85+
86+ // Capture the DispatcherQueue so we can marshal theme updates to the UI thread
87+ auto dispatcherQueue = winrt::Microsoft::UI::Dispatching::DispatcherQueue::GetForCurrentThread ();
8288
8389 // Function to apply current system theme colors
8490 auto applySystemTheme = [titleBar]() {
8591 try {
86- auto uiSettings = winrt::Windows::UI::ViewManagement::UISettings () ;
92+ winrt::Windows::UI::ViewManagement::UISettings uiSettings ;
8793 auto foreground = uiSettings.GetColorValue (winrt::Windows::UI::ViewManagement::UIColorType::Foreground);
8894 auto background = uiSettings.GetColorValue (winrt::Windows::UI::ViewManagement::UIColorType::Background);
8995
@@ -110,10 +116,16 @@ _Use_decl_annotations_ int CALLBACK WinMain(HINSTANCE instance, HINSTANCE, PSTR
110116 // Apply initial theme
111117 applySystemTheme ();
112118
113- // Listen for system theme changes
114- auto uiSettings = winrt::Windows::UI::ViewManagement::UISettings ();
115- uiSettings.ColorValuesChanged ([applySystemTheme](auto const &, auto const &) {
116- applySystemTheme ();
119+ // Listen for system theme changes using the static uiSettings so the
120+ // event registration persists for the lifetime of the application.
121+ s_uiSettings.ColorValuesChanged ([applySystemTheme, dispatcherQueue](auto const &, auto const &) {
122+ // ColorValuesChanged fires on a background thread, so dispatch
123+ // the title bar update back to the UI thread.
124+ if (dispatcherQueue) {
125+ dispatcherQueue.TryEnqueue ([applySystemTheme]() {
126+ applySystemTheme ();
127+ });
128+ }
117129 });
118130 }
119131 } catch (...) {
0 commit comments