- 1 year ago
How to make WinForm use the system dark mode theme?
Comment
1 / 1
To make a WinForms application use the system dark mode theme, you can follow these steps:
- Set the Application.EnableVisualStyles property: Before launching any forms in your application, set the
Application.EnableVisualStyles
property totrue
. This enables the visual styles for the application to match the operating system's theme.
csharpApplication.EnableVisualStyles();
- Set the Application.SetHighDpiMode property: If you're targeting .NET Framework 4.7.2 or later, set the
Application.SetHighDpiMode
property toHighDpiMode.SystemAware
. This enables automatic scaling and adjusts the application to the system's DPI settings.
csharpApplication.SetHighDpiMode(HighDpiMode.SystemAware);
- Handle the SystemEvents.UserPreferenceChanged event: Subscribe to the
SystemEvents.UserPreferenceChanged
event to detect changes in the user's theme preference. In the event handler, you can update the theme of your forms accordingly.
csharpSystemEvents.UserPreferenceChanged += (sender, args) =>
{
if (args.Category == UserPreferenceCategory.General)
{
// Update the theme of your forms
UpdateTheme();
}
};
- Update the theme of your forms: In the event handler or when your forms are created, update the theme of your forms to reflect the system's dark mode preference. You can set the
Control.BackColor
andControl.ForeColor
properties, or use custom controls or themes to achieve the desired appearance.
csharpprivate void UpdateTheme()
{
// Set the background and foreground colors of your forms and controls
this.BackColor = SystemColors.ControlDark;
this.ForeColor = SystemColors.ControlLight;
// Update the theme of other controls in your form
// ...
}
By following these steps, your WinForms application will adapt to the system's dark mode theme, providing a consistent and visually pleasing experience for users who have enabled dark mode on their operating system.