代码之家  ›  专栏  ›  技术社区  ›  Martynas

更改应用程序中所有控件的字体大小(win窗体)

  •  3
  • Martynas  · 技术社区  · 7 年前

    我用表格布局面板完成了大部分工作。

    到目前为止,我已经通过使用

                if (Screen.PrimaryScreen.Bounds.Width < 1440)
            {
                button_5.Font = new Font("Impact", button_5.Font.Size - 4);
            }
    

    有没有办法一次更改应用程序上所有控件的字体?

    2 回复  |  直到 7 年前
        1
  •  6
  •   Steve    7 年前

    一个简单的递归函数将遍历表单中的所有控件并更改字体大小。您需要根据控件对其进行测试,并查看效果,因为在此代码中没有异常处理

    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);
    
        2
  •  0
  •   Matt    5 年前

    基于 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); 
    

    或者可以缩小字体大小

    SetAllControlsFont(this.Controls, amount: -4, amountInPercent: false); 
    

    this answer 您可以自动缩放字体 "Make everything bigger" ):

    var percentage = GetWindowsScaling() - 100;
    SetAllControlsFont(this.Controls, percentage); 
    

    if (percentage > 80)  percentage = 80;
    if (percentage < -20) percentage = -20;
    

    同样,绝对值也是如此-注意,在代码中已经设置了一个限制:实际上,字体不能小于4em-这被设置为最小限制(当然,您可以根据需要进行调整)。