From 42febae25e268c2e439f751369b52ce8819f9723 Mon Sep 17 00:00:00 2001
From: Martin Wiethan <47688561+Marterich@users.noreply.github.com>
Date: Sat, 21 Sep 2024 17:01:02 +0200
Subject: [PATCH] Actively follow windows theme (#2781)

---
 functions/private/Invoke-WinUtilDarkMode.ps1 |  4 +++
 scripts/main.ps1                             | 29 ++++++++++++++++++++
 2 files changed, 33 insertions(+)

diff --git a/functions/private/Invoke-WinUtilDarkMode.ps1 b/functions/private/Invoke-WinUtilDarkMode.ps1
index 870155bab2..3fb1ecc558 100644
--- a/functions/private/Invoke-WinUtilDarkMode.ps1
+++ b/functions/private/Invoke-WinUtilDarkMode.ps1
@@ -22,6 +22,10 @@ Function Invoke-WinUtilDarkMode {
         Set-ItemProperty -Path $Path -Name AppsUseLightTheme -Value $DarkMoveValue
         Set-ItemProperty -Path $Path -Name SystemUsesLightTheme -Value $DarkMoveValue
         Invoke-WinUtilExplorerRefresh
+        # Update Winutil Theme if the Theme Button shows the Icon for Auto
+        if ($sync.ThemeButton.Content -eq [char]0xF08C) {
+            Invoke-WinutilThemeChange -theme "Auto"
+        }
     } catch [System.Security.SecurityException] {
         Write-Warning "Unable to set $Path\$Name to $Value due to a Security Exception"
     } catch [System.Management.Automation.ItemNotFoundException] {
diff --git a/scripts/main.ps1 b/scripts/main.ps1
index 62ee527586..d0fb1b3fed 100644
--- a/scripts/main.ps1
+++ b/scripts/main.ps1
@@ -80,6 +80,35 @@ if (-NOT ($readerOperationSuccessful)) {
     [System.GC]::Collect()
     exit 1
 }
+
+# Setup the Window to follow listen for windows Theme Change events and update the winutil theme
+# throttle logic needed, because windows seems to send more than one theme change event per change
+$lastThemeChangeTime = [datetime]::MinValue
+$debounceInterval = [timespan]::FromSeconds(2)
+$sync.Form.Add_Loaded({
+    $interopHelper = New-Object System.Windows.Interop.WindowInteropHelper $sync.Form
+    $hwndSource = [System.Windows.Interop.HwndSource]::FromHwnd($interopHelper.Handle)
+    $hwndSource.AddHook({
+        param (
+            [System.IntPtr]$hwnd,
+            [int]$msg,
+            [System.IntPtr]$wParam,
+            [System.IntPtr]$lParam,
+            [ref]$handled
+        )
+        # Check for the Event WM_SETTINGCHANGE (0x1001A) and validate that Button shows the icon for "Auto" => [char]0xF08C
+        if (($msg -eq 0x001A) -and $sync.ThemeButton.Content -eq [char]0xF08C) {
+            $currentTime = [datetime]::Now
+            if ($currentTime - $lastThemeChangeTime -gt $debounceInterval) {
+                Invoke-WinutilThemeChange -theme "Auto"
+                $script:lastThemeChangeTime = $currentTime
+                $handled = $true
+            }
+        }
+        return 0
+    })
+})
+
 Invoke-WinutilThemeChange -init $true
 # Load the configuration files
 #Invoke-WPFUIElements -configVariable $sync.configs.nav -targetGridName "WPFMainGrid"