我的应用程序需要适应各种不同的屏幕尺寸(分辨率)。 我使用表布局面板完成了大部分工作。
但是一些控件(主要是按钮和标签)的字体太大而且文本不适合控件。 到目前为止,我已经设法通过使用
更改某些控件的字体 if (Screen.PrimaryScreen.Bounds.Width < 1440)
{
button_5.Font = new Font("Impact", button_5.Font.Size - 4);
}
但是,为应用程序中的每个控件添加的文本太多了。
有没有办法一次更改应用程序上所有控件的字体? 或至少表格上的所有控件?
答案 0 :(得分:1)
一个简单的递归函数将遍历表单中的所有控件并更改字体大小。您需要针对控件测试它并查看效果,因为在此代码中没有异常处理
javax.persistence.Column
您可以通过初始表单的控件集合
从您的顶层表单中调用它public void SetAllControlsFont(ControlCollection ctrls)
{
foreach(Control ctrl in ctrls)
{
if(ctrl.Controls != null)
SetAllControlsFont(ctrl.Controls);
ctrl.Font = new Font("Impact", ctrl.Font.Size - 4);
}
}
答案 1 :(得分:0)
基于Steve's的良好答案,我将进行以下改进:
/// <summary>
/// Changes fonts of controls contained in font collection recursively. <br/>
/// <b>Usage:</b> <c><br/>
/// SetAllControlsFont(this.Controls, 20); // This makes fonts 20% bigger. <br/>
/// SetAllControlsFont(this.Controls, -4, false); // This makes fonts smaller by 4.</c>
/// </summary>
/// <param name="ctrls">Control collection containing controls</param>
/// <param name="amount">Amount to change: posive value makes it bigger,
/// negative value smaller</param>
/// <param name="amountInPercent">True - grow / shrink in percent,
/// False - grow / shrink absolute</param>
public static void SetAllControlsFontSize(
System.Windows.Forms.Control.ControlCollection ctrls,
int amount = 0, bool amountInPercent = true)
{
if (amount == 0) return;
foreach (Control ctrl in ctrls)
{
// recursive
if (ctrl.Controls != null) SetAllControlsFontSize(ctrl.Controls,
amount, amountInPercent);
if (ctrl != null)
{
var oldSize = ctrl.Font.Size;
float newSize =
(amountInPercent) ? oldSize + oldSize * (amount / 100) : oldSize + amount;
if (newSize < 4) newSize = 4; // don't allow less than 4
var fontFamilyName = ctrl.Font.FontFamily.Name;
ctrl.Font = new Font(fontFamilyName, newSize);
};
};
}
这允许按百分比增加或缩小字体大小 ,例如:
SetAllControlsFont(this.Controls, 20);
或者您可以将字体大小绝对缩小-4,例如:
SetAllControlsFont(this.Controls, amount: -4, amountInPercent: false);
在两个示例中,所有字体都会受到更改的影响。您不需要知道字体系列名称,每个控件可以有不同的名称。
结合this answer ,您可以根据Windows设置在应用程序中自动缩放字体(如果您右键单击桌面,然后选择显示设置,缩放和布局并修改值“更改文本,应用程序和其他项目的大小”-在比内部版本1809更新的Windows 10版本中,此(重新)命名为"Make everything bigger"):
var percentage = GetWindowsScaling() - 100;
SetAllControlsFont(this.Controls, percentage);
您还应该根据表单布局将大小限制为一定的最大值/最小值,例如
if (percentage > 80) percentage = 80;
if (percentage < -20) percentage = -20;
同样,绝对值也是如此-请注意,代码中已经设置了一个限制:实际上,字体不能小于4 em-设置为最小限制(当然,您可以根据需要进行调整)。