<pre>using Microsoft.Win32; using System; using System.Globalization; using System.Management; using System.Security.Principal; using System.Windows; using System.Windows.Media; namespace WpfApp1 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private const string RegistryKeyPath = @"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize"; private const string RegistryValueName = "AppsUseLightTheme"; public void CheckRegKeyExists() { if (Registry.GetValue(RegistryValueName,RegistryValueName, null) == null) { Background = Brushes.AliceBlue; } } private enum WindowsTheme { Light, Dark } public void WatchTheme() { var currentUser = WindowsIdentity.GetCurrent(); string query = string.Format( CultureInfo.InvariantCulture, @"SELECT * FROM RegistryValueChangeEvent WHERE Hive = 'HKEY_USERS' AND KeyPath = '{0}\\{1}' AND ValueName = '{2}'", currentUser.User.Value, RegistryKeyPath.Replace(@"\", @"\\"), RegistryValueName); try { var watcher = new ManagementEventWatcher(query); watcher.EventArrived += (sender, args) => { WindowsTheme newWindowsTheme = GetWindowsTheme(); // React to new theme if (newWindowsTheme == WindowsTheme.Light) { Background = Brushes.WhiteSmoke; MessageBox.Show("Light"); } else { Background = Brushes.DarkGray; MessageBox.Show("Dark"); } }; // Start listening for events watcher.Start(); } catch (Exception) { // This can fail on Windows 7 } WindowsTheme initialTheme = GetWindowsTheme(); } private static WindowsTheme GetWindowsTheme() { using (RegistryKey key = Registry.CurrentUser.OpenSubKey(RegistryKeyPath)) { object registryValueObject = key?.GetValue(RegistryValueName); if (registryValueObject == null) { return WindowsTheme.Light; } int registryValue = (int)registryValueObject; return registryValue > 0 ? WindowsTheme.Light : WindowsTheme.Dark; } } } }
Original source of the above code
catch (Exception) { // This can fail on Windows 7 }
UserPreferenceChanged
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)