黑暗模式现在在很多应用程序中都挺常见的,但如何在桌面应用程序中实现它呢?这很简单,本文将为大家介绍如何使用一个类和命令行调用来实现!
Telerik UI for WinForms拥有适用Windows Forms的110多个令人惊叹的UI控件。所有的UI for WinForms控件都具有完整的主题支持,可以轻松地帮助开发人员在桌面和平板电脑应用程序提供一致美观的下一代用户体验。
获取Telerik UI for WinForms新版下载(Q技术交流:726377843)
为了实现黑暗主题,我们将使用Fluent Dark,对于day主题将使用Fluent,如果您喜欢也可以指定另一个主题。
下面是一个Fluent主题控件的示例:
下面是Fluent Dark Theme的一个示例:
在演示应用程序中,白天和夜晚主题看起来像这样:
实现Day/Night菜单
在您的主表单中,添加这行代码:
public RadForm1()
{
InitializeComponent();
_ = new DayNight(this);
}
创建并添加DayNight类到您的项目中:
using System;
using Telerik.WinControls;
using Telerik.WinControls.UI;
namespace TelerikWinFormsApp1;
internal class DayNight
{
private bool themeDay;
private RadImageButtonElement signInButton;
public DayNight(RadForm form)
{
new Telerik.WinControls.Themes.FluentTheme().DeserializeTheme();
new Telerik.WinControls.Themes.FluentDarkTheme().DeserializeTheme();
CreateDayNightButton(form);
themeDay = Telerik.WinControls.WindowsSettings.AppsUseLightTheme;
SetDayNight();
}
private void CreateDayNightButton(RadForm form)
{
daynightButton = new RadImageButtonElement
{
ThemeRole = "TitleBarMinimizeButton",
Text = "☾",
DisplayStyle = DisplayStyle.Text,
ShowBorder = false,
AutoSize = false,
Size = form.FormElement.TitleBar.MinimizeButton.Size
};
daynightButton.Click += DayNight_Click;
form.FormElement.TitleBar.SystemButtons.Children.Insert(0, daynightButton);
}
private void DayNight_Click(object sender, EventArgs e)
{
themeDay = !themeDay;
SetDayNight();
}
private void SetDayNight()
{
if (themeDay)
{
ThemeResolutionService.ApplicationThemeName = "Fluent";
signInButton.Text = "☾";
}
else
{
ThemeResolutionService.ApplicationThemeName = "FluentDark";
signInButton.Text = "☼";
}
}
}
如果您不喜欢用Windows默认主题启动应用程序,可以删除从Windows注册表读取设置的代码:
themeDay = Telerik.WinControls.WindowsSettings.AppsUseLightTheme;
并将themeDay变量设置为白天为true,夜晚为false:
themeDay = true;
RadForm的标题栏中的按钮是由CreateDayNightButton函数创建的:
private void CreateDayNightButton(RadForm form)
{
daynightButton = new RadImageButtonElement
{
ThemeRole = "TitleBarMinimizeButton",
Text = "☾",
DisplayStyle = DisplayStyle.Text,
ShowBorder = false,
AutoSize = false,
Size = form.FormElement.TitleBar.MinimizeButton.Size
};
daynightButton.Click += DayNight_Click;
form.FormElement.TitleBar.SystemButtons.Children.Insert(0, daynightButton);
}
DayNight_Click在主题之间切换:
private void DayNight_Click(object sender, EventArgs e)
{
themeDay = !themeDay;
SetDayNight();
}
SetDayNight()执行这些更改:
private void SetDayNight()
{
if (themeDay)
{
ThemeResolutionService.ApplicationThemeName = "Fluent";
signInButton.Text = "☾";
}
else
{
ThemeResolutionService.ApplicationThemeName = "FluentDark";
signInButton.Text = "☼";
}
}
这个命令改变了整个应用程序的主题:
ThemeResolutionService.ApplicationThemeName = "Fluent";
总结
Telerik UI for WinForms和它的主题使实现WinForms应用程序的暗模式变得很容易,可以在自己的应用程序中使用这个DayNight类。