I want to detect Windows 10 theme and I wrote this code:
public class Class1
{
public Class1()
{
SystemEvents.UserPreferenceChanged += SystemEvents_UserPreferenceChanged;
}
private void SystemEvents_UserPreferenceChanged(object sender, UserPreferenceChangedEventArgs e)
{
switch (e.Category)
{
case UserPreferenceCategory.General:
setTheme();
break;
}
}
private static bool ThemeIsLight()
{
RegistryKey registry =
Registry.CurrentUser.OpenSubKey(
@"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize");
return (int)registry.GetValue("SystemUsesLightTheme") == 1;
}
public static void setTheme()
{
var br = ThemeIsLight() ? Brushes.White : Brushes.Black;
MessageBox.Show(br.ToString());
}
}
Usage:
public MainWindow()
{
InitializeComponent();
Class1.setTheme();
}
The problem is that the code only works when the program is initially run, and the code does not run when the Windows theme is changed.
It works well if I write all the code in MainWindow.cs, but I want the code to be written in a separate class