Skip to content

Instantly share code, notes, and snippets.

@punker76
Created February 6, 2019 20:36
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save punker76/fa520de6feeccf7d86c8c672e709e702 to your computer and use it in GitHub Desktop.
Save punker76/fa520de6feeccf7d86c8c672e709e702 to your computer and use it in GitHub Desktop.
Detecting Windows 10 Dark/Light mode
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" x:Name="theTextBlock" />
</Grid>
</Window>
using System;
using System.Windows;
using System.Windows.Interop;
namespace WpfApp1
{
public partial class MainWindow : Window
{
private bool isLightMode = false;
public MainWindow()
{
InitializeComponent();
isLightMode = IsLightMode();
theTextBlock.Text = $"Current Mode: {(isLightMode ? "Light" : "Dark")}";
this.SourceInitialized += MainWindow_SourceInitialized;
}
private IntPtr hwnd;
private HwndSource hsource;
private void MainWindow_SourceInitialized(object sender, EventArgs e)
{
if ((hwnd = new WindowInteropHelper(this).Handle) == IntPtr.Zero)
{
throw new InvalidOperationException("Could not get window handle.");
}
hsource = HwndSource.FromHwnd(hwnd);
hsource?.AddHook(WndProc);
}
private const int WM_WININICHANGE = 0x001A;
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
switch (msg)
{
case WM_WININICHANGE:
// Respond to dark/light theme change
var newMode = IsLightMode();
if (newMode != isLightMode)
{
isLightMode = newMode;
theTextBlock.Text = $"Current Mode: {(isLightMode ? "Light" : "Dark")}";
}
return IntPtr.Zero;
default:
return IntPtr.Zero;
}
}
private bool IsLightMode()
{
var is_light_mode = true;
try
{
var v = Microsoft.Win32.Registry.GetValue(
@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize", "AppsUseLightTheme", "1");
if (v != null && v.ToString() == "0")
{
is_light_mode = false;
}
}
catch
{
// ignored
}
return is_light_mode;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment