【问题标题】:c# pictureBox changes size with fontc#pictureBox随字体改变大小
【发布时间】:2018-04-23 17:20:21
【问题描述】:

当我使用此代码更改整个表单的字体时:

this.Font = new Font("Gravity", 12, FontStyle.Bold);

然后我所有的图片框(大小为 16x16)也变大了。

有没有办法阻止这种情况?

【问题讨论】:

  • 重力总是赢。
  • 为什么要更改整个表单的字体?而不是更改控件的字体,例如标签?
  • 如果你没有在 PictureBoxes 上设置 Font 属性,它们会采用 Container 的字体,为了防止这种情况,我建议在你需要保留大小的所有 PictureBoxes 上设置 Font 属性。
  • 如果您不喜欢/管理此行为,请将表单 AutoScaleMode 设置为不同于 Font 的内容。
  • 实际上,大多数情况下这并不会真正产生影响;但不同的系统组合表现不同。

标签: c# winforms picturebox


【解决方案1】:

如果你坚持要改变表格的字体,那就用

Control.OnFontChanged Method (EventArgs)

这个方法会在你每次改变表单的字体时执行,所以在执行的时候,你可以指定你的PictureBox(All)会保持你定义的字体。

如果你所有的PictureBox 有相同的字体:

public class Form1 : Form
{
    private void Form1_Load(object sender, EventArgs e)
    {

    }

    protected override OnFontChanged(EventArgs e)
    {
        foreach(Control control in this.Controls)
        {
            if(control is PictureBox)
            {
               control.Font = new Font(<Your constant defined font>);;
            }
        }
    }
}

现在,假设您的图片框有不同的字体。

您可以将源存储在一个列表中(或者也可以存储在一个数组中),并且每次更改表单的源时,您只需调用之前存储的源重新分配给每个PictureBox

public class Form1 : Form
{
    private List<Font> PBFonts = new List<Font>();

    private void Form1_Load(object sender, EventArgs e)
    {
        foreach(Control control in this.Controls)
        {
           if(control is PictureBox)
           {
               this.PBFonts.Add(control.Font);
           }
        }
    }

    protected override OnFontChanged(EventArgs e)
    {
        int index = 0;
        foreach(Control control in this.Controls)
        {
           if(control is PictureBox picture)
           {
               picture.Font = this.PBFonts[index];
           }
           index++;
        }
    }
}

【讨论】:

    猜你喜欢
    • 2014-03-23
    • 1970-01-01
    • 2019-12-12
    • 2012-06-04
    • 2012-09-27
    • 2019-11-29
    • 1970-01-01
    • 2012-07-16
    相关资源
    最近更新 更多