1

I have a form with a bunch of labels, rich text boxes, text boxes, and buttons. I have been messing around with anchoring and autoscale(dpi/font), trying to get my UI to look more or less the same for a wide range of screen resolutions. So far, I've made some progress with getting the controls to resize properly, but now I need to adjust font sizes once the controls have changed.

I have tried the solution from this question (with a minor change to disregard the parent container and just use the label itself), which worked great for labels, but text boxes dont have a paint event, so I'm unable to get the scaling ratio from the info that would normally be passed in e.Graphics of the PaintEventArgs to give a size of the string:

 public static float NewFontSize(Graphics graphics, Size size, Font font, string str)
    {
        SizeF stringSize = graphics.MeasureString(str, font);
        float wRatio = size.Width / stringSize.Width;
        float hRatio = size.Height / stringSize.Height;
        float ratio = Math.Min(hRatio, wRatio);
        return font.Size * ratio;
    }

    private void lblTempDisp_Paint(object sender, PaintEventArgs e)
    {
        float fontSize = NewFontSize(e.Graphics, lblTempDisp.Bounds.Size, lblTempDisp.Font, lblTempDisp.Text);
        Font f = new Font("Arial", fontSize, FontStyle.Bold);
        lblTempDisp.Font = f;

    }

Primary Question: Is there a similar way to adjust the font size of text boxes?

Secondary Question: What would be the proper way to loop through all of the controls of one type on my form? I tried:

foreach (Label i in Controls)
        {
            if (i.GetType() == Label)//I get an error here that says 
            //"Label is a type, which is not valid in the given context"
            {
                i.Font = f;
            }
        }

and I know there is a way to check if a control is a label, but this doesnt seem to be it.

Community
  • 1
  • 1
Lodestone6
  • 166
  • 2
  • 16
  • Try using the `is` operator instead of `==` when comparing types. – Roy123 Oct 11 '16 at 06:59
  • foreach (Label i in Controls) cannot work because you try to put non labels controls in i which is Label. – GuidoG Oct 11 '16 at 07:00
  • Font is an ambient property and if you set font of a parent control, all its children will use the same font. So I don't think you need a loop to assign font to all control, unless you need to apply the font to all child controls of a specific type, in this case you can take a look at [this post](http://stackoverflow.com/questions/3419159/how-to-get-all-child-controls-of-a-windows-forms-form-of-a-specific-type-button). – Reza Aghaei Oct 11 '16 at 11:11

1 Answers1

3

for your second question :

foreach(Control control in Controls)
{
     if (control is Label)
     {
          ((Label)control).Font = f;
     }
}

another way is this:

foreach (Label label in Controls.OfType<Label>())
{
    label.Font = f;
}
GuidoG
  • 11,359
  • 6
  • 44
  • 79