using System;
using System.Drawing;
using System.Windows.Forms;
namespace Form_Controls_Scaling
{
public partial class Scaling : Form
{
public Scaling()
{
InitializeComponent();
this.MinimumSize = new Size(400, 400); //设置窗体最小尺寸
}
#region 定义全局变量
float origin_width; //起始窗体宽度
float origin_height; //起始窗体高度
#endregion
protected override void onl oad(EventArgs e) //窗体加载
{
base.OnLoad(e);
origin_width = this.Width; //赋值起始窗体宽度
origin_height = this.Height; //赋值起始窗体高度
SetTag(this); //记录当前窗体控件信息
}
protected void SetTag(Control controls) //记录当前窗体控件信息
{
foreach (Control control in controls.Controls) //遍历当前窗体控件
{
control.Tag = control.Width + "," + control.Height + "," + control.Top + "," + control.Left + "," + control.Font.Size; //记录信息
if (control.Controls.Count > 0) //判断是否存在子控件
{
SetTag(control); //记录子控件信息
}
}
}
protected override void OnResize(EventArgs e) //窗体控件大小改变
{
base.OnResize(e);
float scale_Width = Width / origin_width; //计算控件宽度缩放比例
float scale_Height = Height / origin_height; //计算控件高度缩放比例
SetControls(scale_Width, scale_Height, this); //窗体控件缩放
}
protected void SetControls(float scale_Width, float scale_Height, Control controls) //窗体孔家缩放
{
foreach (Control control in controls.Controls) //遍历窗体控件
{
string[] controlTag = control.Tag.ToString().Split(','); //分割控件信息
float newWidth = Convert.ToSingle(controlTag[0]) * scale_Width; //计算新控件宽度
float newHeight = Convert.ToSingle(controlTag[1]) * scale_Height; //计算新控件高度
float newTop = Convert.ToSingle(controlTag[2]) * scale_Width; //计算新控件顶部距离
float newLeft = Convert.ToSingle(controlTag[3]) * scale_Height; //计算新控件左侧距离
float fontSize = Convert.ToSingle(controlTag[4]) * scale_Height; //计算新控件文字高度
control.Width = Convert.ToInt32(newWidth); //赋值新控件宽度
control.Height = Convert.ToInt32(newHeight); //赋值新控件高度
control.Top = Convert.ToInt32(newTop); //赋值新控件顶部距离
control.Left = Convert.ToInt32(newLeft); //赋值新控件左侧距离
control.Font = new Font(control.Font.Name, fontSize, control.Font.Style, control.Font.Unit); //赋值新控件字体高度
if (control.Controls.Count > 0) //判断是否存在子控件
{
SetControls(newWidth, newHeight, control); //设置子控件
}
}
}
}
}