Search code examples
c#winformsdarkmode

How to create a switch to select a dark theme for Windows Form? That can darken the whole background? in c#


How can I create a switch to select a dark theme for Windows Forum (like a swipe switch in VPN)? That can darken the whole background? And I want to give options about what the user wants, for example, does he just want the background to be dark or does he want the text boxes to be dark too? I didn't find anything on the google


Solution

  • This question is quite strangely formulated, but I did undestand that you want something like a "Appearance menu" where the user can just select colors for each controltype (or for selected only).

    This is nothing too hard, depending on your current skill-level. For the mentioned "swipe switch" (guessing like an IOS-toggle) try this simple video: https://www.youtube.com/watch?v=m7Iv6xfjnuw

    Now to the Theme-switching part: Define some color-variables you want the user to cusomize

    Color clrBackground = Color.FromArgb(32, 32, 32); 
    Color clrFont = Color.White;
    Color clrTbBack = Color.FromArgb(23, 23, 23);
    ...
    

    Now create a Methode to change colors:

    private void SwitchDesign()
    {
        this.ForeColor = clrFont;
        this.BackColor = clrBackground;
        //Now for every special-control that does need an extra color / property to be set use something like this
        foreach (TextBox tb in this.Controls.OfType<TextBox>())
        {
           tb.BackColor = clrTbBack;
           //Maybe do more here...
        }
        //You could now add more controls in a similar fashion.
        this.Invalidate(); //Forces a re-draw of your controls / form
    }
    

    The only thing you need to do yourself now is to create menu to change that colors and switch the design after that. Simple solution would be to use the ColorDialog https://learn.microsoft.com/de-de/dotnet/api/system.windows.forms.colordialog?view=net-5.0

    This is in no way a very good solution if your project get's too big, but for a small - mid sized project it should be alright.