Skip to content

Instantly share code, notes, and snippets.

@meatcar
Last active April 5, 2024 18:37
Show Gist options
  • Save meatcar/06274be6203555afd2a9eb4dc1c8450f to your computer and use it in GitHub Desktop.
Save meatcar/06274be6203555afd2a9eb4dc1c8450f to your computer and use it in GitHub Desktop.
Subscribe to Dark Mode change event in Windows

Wait for Dark Mode change in Windows

This is a snippet I came up with that doesn't exist anywhere else on the net (so far). I think its the best way to programmatically detect dark mode change in Windows. Unlike other approaches, there's no busy-waiting/polling involved. Instead, we use the native event system to subscribe to the AppsUseLightTheme registry key change.

A big benefit of this approach is that theme change detection is almost instantaneous.

To run this in a loop, call this script, react to it's output, then call it again. An example script is provided.

# Elevated prompts and WSL doesn't have current user's username/SID. Let's get it.
$username = Get-WMIObject -class Win32_ComputerSystem | select -ExpandProperty username
$SID = (Get-WMIObject -class Win32_UserAccount | ? {$_.Caption -eq $username}).SID
# The Registry value we want to listen to.
$key = "Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"
$value = “AppsUseLightTheme”
# Register-WmiEvent can't listen to HKEY_CURRENT_USER, hence the HKEY_USERS:\$SID\$key hack
$query = “SELECT * FROM RegistryValueChangeEvent WHERE Hive='HKEY_USERS' AND KeyPath='$SID\\$key' AND ValueName='$value'"
$event = Register-WmiEvent -Query $query -SourceIdentifier $value
try {
Wait-Event -SourceIdentifier $value | Remove-Event
echo (Get-ItemProperty -Path HKCU:$key).$value
# prints 0 for dark mode, 1 for light
} finally {
# trap Ctrl+C, cleanup.
Unregister-Event -SourceIdentifier $value
}
#!/bin/sh
cd $(dirname "$0") # directory containing both scripts.
while true; do
MODE=
case $(powershell.exe -NoProfile -Command ./wait-dark-mode-change.ps1) in
0)
# react to dark mode
MODE=dark
;;
1)
# react to light mode
MODE=light
;;
esac
for s in /tmp/nvim-*.sock; do
nvim --remote="$s" --remote-send ":set background=$MODE<CR>"
done
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment