C-Sharp: Changing font of all controls in run time

Some time it required when we want to change font of all controls in windows forms or dialogs. For doing this there is one very simple method by using which you can change font of all controls. and by using some conditions and trick you can make this function more useful.

You can create this function in you form class or base class or you can make this function static in some utility class. Here i am giving example in a form class.

Write following function in your form class

public void SetFont(Control parent, Font font)
{
foreach (Control ctl in parent.Controls)
{
ctl.Font = font;
SetFont(ctl, font);
}
}

and call this method where you want either on load event or any button click event whether you want.

For example, suppose you want to change font of all controls of a panel, for this you have to call above function like this

Font fnt = new Font(“Arial”, 10.5f, FontStyle.Regular);

SetFont(Panel1,  fnt);

But if some control (Windows or third party dotnet controls) has some other font properties like in DatagridView

dataGridView1.RowsDefaultCellStyle.Font will not be changed, for doing these kind of changes. you have to modify above function like this

public void SetFont(Control parent, Font font)
{
foreach (Control ctl in parent.Controls)
{
ctl.Font = font;

if (ctl is DataGridView)
{
((DataGridView)ctl).RowsDefaultCellStyle.Font = font;
}
SetFont(ctl, font);

}
}

Leave a Reply

Your email address will not be published. Required fields are marked *