Detect Windows 10 theme changing in c#

Viewed 641

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

1 Answers

Code above does not create any instance of the Class1. Therefore, the UserPreferenceChanged event handler does not created.

It is necessary to create instance of Class1. For example:

public partial class MainWindow : Window
{
    private Class1 DetectPreferenceChange = new Class1();
    
    public MainWindow()
    {
        InitializeComponent();        
    }
    ...
}

Or, if it is necessary to subscribe to the event without creating of the Class1 instance do the following:

Change signature of the event handler to public static:

public static void SystemEvents_UserPreferenceChanged(object sender, UserPreferenceChangedEventArgs e) 
{
    // ...
}

And now you can subscribe to the event directly:

public MainWindow()
{
    InitializeComponent();
    SystemEvents.UserPreferenceChanged += (s, e) => { Class1.SystemEvents_UserPreferenceChanged(s, e); };
}

Because of all methods in the class are static now the class constructor might be omitted and class can be declared as static.

For additional information see How to subscribe to and unsubscribe from events (C# Programming Guide)

Related