Noman_1
Noman_1

Reputation: 530

C# AutoScaleMode Font, Bold controls don't scale

I'm developing a small application. I'm trying to use AutoScaleMode = Font and it works like a charm for all my intentions except one, I want some specific controls to have bold text, but then, they don't autoscale when the font size is changed.

Is it possible to change the default font of a control but still AutoScale as the rest of the controls?

Thanks in advance

Upvotes: 0

Views: 351

Answers (1)

Hans Passant
Hans Passant

Reputation: 941942

You are probably using font scaling to do a job it was not intended to do. It was designed to compensate for a different video DPI on the target machine. And yes, you can also use it to rescale your Form by changing the form's Font property. But then you'll run into trouble with controls that don't "inherit" their Parent's font. You have to update their Font property yourself.

Doing this automatically requires iterating the controls inside-out, updating only those that don't inherit their parent's font. This worked well:

    public static void ScaleFonts(Control ctl, float multiplier) {
        foreach (Control c in ctl.Controls) ScaleFonts(c, multiplier);
        if (ctl.Parent == null || ctl.Parent.Font != ctl.Font) {
            ctl.Font = new Font(ctl.Font.FontFamily, 
                                ctl.Font.Size * multiplier, ctl.Font.Style);
        }
    }

Sample usage:

    private void Form1_Load(object sender, EventArgs e) {
        ScaleFonts(this, 1.25f);
    }

A possible failure-mode is triggering layout events while doing this, getting the layout messed up. That's hard to reason through, you may need to call Suspend/ResumeLayout() to fix this.

Upvotes: 1

Related Questions