基于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 设置自动缩放字体(您可以在桌面上右键单击找到,然后选择显示设置、缩放和布局,然后修改值“更改文本、应用程序和其他项目的大小” - 在比 build 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 - 这被设置为最小限制(当然您可以根据您的需要进行调整)。