Search code examples
c#winformsfontsresolutionadaptive-design

Change the font size of all controls in the application (win forms)


I have an application that needs to be adaptive to a range of different screen sizes (resolutions). Most of that I've done using table layout panels.

But some of the control (buttons and labels mostly) have too large font and the text doesn't fit in the control. So far I've managed change the font of some controls by using

            if (Screen.PrimaryScreen.Bounds.Width < 1440)
        {
            button_5.Font = new Font("Impact", button_5.Font.Size - 4);
        }

But that is too much text to add for every single control in the application.

Is there a way of changing the fonts of all the controls on the application at once? Or at least all controls on a form?


Solution

  • A simple recursive function will traverse all the controls in your form and change the font size. You need to test it against your controls and look at the effect because in this code there is no exception handling

    public void SetAllControlsFont(ControlCollection ctrls)
    {
        foreach(Control ctrl in ctrls)
        {
            if(ctrl.Controls != null)
                SetAllControlsFont(ctrl.Controls);
    
            ctrl.Font = new Font("Impact", ctrl.Font.Size - 4);
    
        }
    }
    

    You can call it from your toplevel form passing the initial form's control collection

    SetAllControlsFont(this.Controls);