gpt4 book ai didi

c# - 有没有办法调整带有循环的表单上每个控件的字体大小?

转载 作者:太空宇宙 更新时间:2023-11-03 23:09:18 26 4
gpt4 key购买 nike

我有一个带有一堆标签、富文本框、文本框和按钮的表单。我一直在搞乱锚定和自动缩放(dpi/字体),试图让我的 UI 在各种屏幕分辨率下看起来或多或少相同。到目前为止,我在让控件正确调整大小方面取得了一些进展,但现在我需要在控件更改后调整字体大小。

我已经尝试了 this question 中的解决方案(稍作改动以忽略父容器并仅使用标签本身),这对标签非常有用,但文本框没有绘画事件,所以我无法从通常情况下的信息中获取缩放比例传入 PaintEventArgs 的 e.Graphics 以给出字符串的大小:

 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;

}

首要问题:有没有类似的方法可以调整文本框的字体大小?

次要问题:循环遍历表单上一种类型的所有控件的正确方法是什么?我试过:

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;
}
}

而且我知道有一种方法可以检查控件是否是标签,但似乎不是。

最佳答案

第二个问题:

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

另一种方式是这样的:

foreach (Label label in Controls.OfType<Label>())
{
label.Font = f;
}

关于c# - 有没有办法调整带有循环的表单上每个控件的字体大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39971892/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com