思路
逻辑很简单:
1、传入一个窗体(Form
),获取它的所有控件(Control
);
2、将这些控件的Size
和Location
按照相同的比例放大;
3、如果控件具有子控件(如GroupBox
),递归调用放大函数;
4、将窗体的Size
放大。
需要注意的几点:
1、Size
的Width
,Height
和Location
的X
,Y
是只读的,想要修改就只能new
一个Size
/Point
赋值给它们;
2、部分已经设置为依托父控件的控件可能不适用这一方法;
3、放大的效果并不会有多好,只能在特定场景下使用;
4、需要格外注意调用的时机,多次调用会导致窗体布局失真。
代码
这里提供一套已经封装好的函数:
public static void EnlargeForm(Form form, double bit)
{
if (bit == 1.0) { return; }
List<Control> controls = form.Controls.Cast<Control>().ToList();
foreach (Control c in controls)
{
c.Size = new Size((int)(c.Size.Width * bit), (int)(c.Size.Height * bit));
c.Location = new Point((int)(c.Location.X * bit), (int)(c.Location.Y * bit));
if (c.HasChildren)
{
EnlargeControls(c, bit);
}
}
form.Size = new Size((int)(form.Size.Width * bit), (int)(form.Size.Height * bit));
}
private static void EnlargeControls(Control cont, double bit)
{
List<Control> controls = cont.Controls.Cast<Control>().ToList();
foreach (Control c in controls)
{
c.Size = new Size((int)(c.Size.Width * bit), (int)(c.Size.Height * bit));
c.Location = new Point((int)(c.Location.X * bit), (int)(c.Location.Y * bit));
if (c.HasChildren)
{
EnlargeControls(c, bit);
}
}
}
调用时在窗体Load
事件时进行:
double bit = 1.2; // 放大或缩小的倍数
EnlargeForm(this, bit);