我有一个应用程序需要适应一系列不同的屏幕尺寸(分辨率)。 大部分工作我都是使用表格布局面板完成的。
但是某些控件(主要是按钮和标签)的字体太大,文本不适合控件。 到目前为止,我已经通过使用更改了一些控件的字体
if (Screen.PrimaryScreen.Bounds.Width < 1440)
{
button_5.Font = new Font("Impact", button_5.Font.Size - 4);
}
但是要为应用程序中的每个控件添加太多文本。
有没有办法一次性更改应用程序上所有控件的字体? 或者至少是表单上的所有控件?
一个简单的递归函数将遍历表单中的所有控件并更改字体大小。您需要针对您的控件进行测试并查看效果,因为在此代码中没有异常处理
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);
}
}
您可以从顶级表单中传递初始表单的控件集合来调用它
SetAllControlsFont(this.Controls);
基于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)
{
float oldSize = (float)ctrl.Font.Size;
float newSize =
(amountInPercent) ? oldSize + oldSize * ((float)amount / (float)100)
: oldSize + (float)amount;
if (newSize < 4) newSize = 4; // don't allow less than 4
var fontFamilyName = ctrl.Font.FontFamily.Name;
ctrl.Font = new Font(fontFamilyName, newSize);
};
};
}
这允许增大或缩小字体大小以百分比,例如:
SetAllControlsFontSize(this.Controls, 20);
或者您可以将字体大小绝对缩小-4,例如:
SetAllControlsFontSize(this.Controls, amount: -4, amountInPercent: false);
在这两个示例中,所有字体都将受到更改的影响。您不需要知道字体系列名称,每个控件可以有不同的。
结合这个答案您可以根据Windows设置在应用程序中自动缩放字体(如果右键单击桌面,然后选择显示设置,缩放和布局并修改值“更改文本、应用程序和其他项目的大小” - 在比 build 1809 更新的 Windows 10 版本中,这被(重新)命名为 “使所有内容变大”):
var percentage = GetWindowsScaling() - 100;
SetAllControlsFontSize(this.Controls, percentage);
您还应该根据您的表单布局将大小限制为某个最大/最小值,例如
if (percentage > 80) percentage = 80;
if (percentage < -20) percentage = -20;
同样,对于绝对值也是如此 - 请注意,在代码中已经设置了限制:实际上,字体不能小于 4 em - 这被设置为最小限制(当然您可以根据您的需要进行调整)。
只需设置父窗体的字体即可。除非您手动在子控件上设置字体,否则它将通过控件传播
示例代码:
public MyForm()
{
InitializeComponent();
Font = new Font(new FontFamily("Microsoft Sans Serif"), 8f); //replace 8f with desired font size
}
来自
Control.Font
文档:
备注
Font 属性是环境属性。环境属性是 控制属性,如果未设置,则从父级检索 控制。例如,按钮将具有与其相同的背景色 默认为父表单。
在
.NetFramework 4.6.2
和 .Net6
中测试