Home > Software engineering >  UWP/WinUI3 How to get system theme in C#?
UWP/WinUI3 How to get system theme in C#?

Time:01-18

Is there a programming way to access the system theme (i.e., theme for Windows)?

The similar question #UWP get system theme (Light/Dark) is answered here:

var DefaultTheme = new Windows.UI.ViewManagement.UISettings();
var uiTheme = DefaultTheme.GetColorValue(Windows.UI.ViewManagement.UIColorType.Background).ToString();

But as tipa comments, the accepted answer suggests a way to access the theme for applications, not the theme for Windows.

Therefore, I wonder if there are other ways to access the system theme.

CodePudding user response:

Try this:

[DllImport("UXTheme.dll", SetLastError = true, EntryPoint = "#138")]
public static extern bool ShouldSystemUseDarkMode();

If the system uses dark mode, it will return true.

That's not the theme for applications.

CodePudding user response:

Here is a method I have used previously in WPF applications to determine if Windows is in High Contrast or Dark theme.

It hasn't been updated for a while so it maybe out of date, but might be a starting point? You can easily adapt it to return an enum or bool for just light/dark if required.

private static string GetWindowsTheme()
{
    string RegistryKeyPath = @"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize";
    string RegistryValueName = "AppsUseLightTheme";

    if (SystemParameters.HighContrast)
        return "High Contrast";

    using (RegistryKey key = Registry.CurrentUser.OpenSubKey(RegistryKeyPath))
    {
        object registryValueObject = key?.GetValue(RegistryValueName);
        if (registryValueObject == null)
            return "Default";

        int registryValue = (int)registryValueObject;
        return registryValue > 0 ? "Default" : "Dark Theme";
    }
}

CodePudding user response:

In WinUI 3, the enum ApplicationTheme is defined in the Microsoft.UI.Xaml namespace.

public enum ApplicationTheme
{
    //
    // Summary:
    //     Use the **Light** default theme.
    Light,
    //
    // Summary:
    //     Use the **Dark** default theme.
    Dark
}

You can get the theme like this.

public App()
{
    this.InitializeComponent();
    ApplicationTheme theme = RequestedTheme;
}
  • Related