Title: Understand AutoScaleMode in C#
A form's AutoScaleMode property lets a form automatically resize itself when its font changes. This can be particularly useful with an aging user population that may have trouble seeing smaller fonts.
To try to help users out, you can give the program a menu item, check box, or some other method to allow the user to make a form's font bigger. Unfortunately if you just enlarge the font, its controls may not fit any more.
That's where the AutoScaleMode property comes is. To make this sort of resizing easier, Microsoft gave the Form class an AutoScaleMode property. If this property is set to AutoScaleMode.Font, which it is by default, then the form resizes itself to make room when its font changes size. The result isn't perfect, but it's better than nothing and you don't need to do any extra work.
This example uses the following code to switch between font sizes when you check and uncheck the Big Font box.
// Make the fonts.
private Font SmallFont;
private Font BigFont;
private void Form1_Load(object sender, EventArgs e)
{
// Save the original font.
SmallFont = this.Font;
// Make the big font.
BigFont = new Font("Times New Roman", 20);
}
// Change the form's font size.
private void chkBigFont_CheckedChanged(object sender, EventArgs e)
{
if (chkBigFont.Checked)
{
this.Font = BigFont;
}
else
{
this.Font = SmallFont;
}
}
When the form loads, the program saves the form's initial font in the variable SmallFont. It then creates a larger font and saves it in the variable BigFont.
When the Big Font checkbox is checked or unchecked, the program sets the form's font to either the big or little font. Because the form's AutoScaleMode property is set to AutoScaleMode.Font, the form automatically resizes itself.
Note that this isn't the only way you might want to handle larger fonts. For example, if the form is very large, then auto scaling might make it too big to fit on the screen.
Auto scaling also scales everything proportionally. In particular it increases the spacing between controls probably more than is necessary.
AutoScaleMode also scales controls such as PictureBox controls that may not need scaling. For example, if a PictureBox is displaying a graphic at full scale, then making it larger will just make it fuzzy.
In those cases you might be better off disabling AutoScaleMode and displaying information at a larger font size inside some sort of scrolling control. For example, the ListBox and RichTextBox controls can provide scrollbars as needed so you can make their fonts larger without changing the size of the form.
Download the example to experiment with it and to see additional details.
|