Reputation: 166
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.
Upvotes: 1
Views: 609
Reputation: 12014
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;
}
Upvotes: 3