public static void setTag(Control cons)
{
foreach (Control con in cons.Controls)
{
con.Tag = con.Width + ":" + con.Height + ":" + con.Left + ":" + con.Top + ":" + con.Font.Size;
if (con.Controls.Count > 0) setTag(con); //如果此控件存在子控件,则此控件的子控件执行此函数一次
}
}
public static void setControls(float newx, float newy, Control cons)
{
foreach (Control con in cons.Controls)
{
if (con.Tag == null) continue;
string[] myTag = con.Tag.ToString().Split(new char[] { ':' }); //将con的宽、高、左边距、顶边距离及字体大小通过字符“:”分割成数组
float a = Convert.ToSingle(myTag[0]) * newx; //根据窗口的缩放比例确定控件相应的值,宽度
con.Width = (int)a;
a = Convert.ToSingle(myTag[1]) * newy; //高度
con.Height = (int)a;
a = Convert.ToSingle(myTag[2]) * newx; //左边距
con.Left = (int)a;
a = Convert.ToSingle(myTag[3]) * newy; //顶边距离
con.Top = (int)a;
Single currentSize = Convert.ToSingle(myTag[4]) * newy; //字体大小
con.Font = new Font(con.Font.Name, currentSize, con.Font.Style, con.Font.Unit); ;
if (con.Controls.Count > 0) setControls(newx, newy, con); //如果此控件存在子控件,则将相应子控件执行一次setControls函数
}
}
float X; //默认窗口的宽度
float Y; //默认窗口的高度
private void FrmMain_Load(object sender, EventArgs e)
{
X = this.Width; //将窗体的宽度赋值给X
Y = this.Height; //将窗体的高度赋值给Y
Wode.setTag(this); //调用setTag函数
this.Resize += new EventHandler(FrmMain_Resize);//窗体调整大小时引发事件
}
//网上的不知道为什么
private void FrmMain_Resize(object sender, EventArgs e)
{
float newx = (this.Width) / X; //窗体宽度缩放比例
float newy = (this.Height) / Y; //窗体高度缩放比例
Wode.setControls(newx, newy, this); //调用setControls函数
}