如何让WPF应用图标随Windows系统深浅色模式自动切换
WPF应用跟随系统深浅色模式动态切换图标的实现方案
可以实现。 Windows 10 1809及以上版本、Windows 11全版本支持系统深浅色模式切换,WPF应用完全可以实现应用图标跟随系统模式自动切换,具体实现逻辑如下:
实现步骤
- 第一步:准备两套独立的图标素材,分别适配浅色模式和深色模式,建议覆盖16x16、32x32、48x48、256x256等常用分辨率,避免图标缩放时出现模糊。
- 第二步:监听系统深浅色模式变更状态,你可以通过监听指定注册表项的数值变化获取系统主题变更通知,获取当前主题的参考代码如下:
using Microsoft.Win32; /// <summary> /// 检测当前系统是否开启深色模式 /// </summary> /// <returns>深色模式返回true,浅色模式返回false</returns> public static bool CheckSystemDarkMode() { const string themeRegPath = @"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize"; const string themeRegKey = "AppsUseLightTheme"; var regValue = Registry.GetValue(themeRegPath, themeRegKey, 1); return regValue is int val && val == 0; }
- 第三步:收到系统主题变更通知后,动态替换应用对应的图标即可,替换窗口图标的参考代码如下:
/// <summary> /// 切换应用图标 /// </summary> /// <param name="isDarkMode">当前是否为深色模式</param> public void UpdateAppIcon(bool isDarkMode) { // 注意替换为你项目中对应的图标资源路径 var iconUri = isDarkMode ? new Uri("pack://application:,,,/Resources/Icons/AppDark.ico", UriKind.Absolute) : new Uri("pack://application:,,,/Resources/Icons/AppLight.ico", UriKind.Absolute); this.Icon = new BitmapImage(iconUri); // 如果有托盘图标,同步替换托盘图标 if (notifyIcon != null) { notifyIcon.Icon = isDarkMode ? Properties.Resources.AppIconDark : Properties.Resources.AppIconLight; } }
效果参考
系统原生应用的图标切换效果如下:
- Windows 10应用商店图标切换效果:

- Windows 11系统图标切换效果:

内容的提问来源于stack exchange,提问作者User
相关产品推荐
相关产品推荐

