C#窗体内控件大小随窗体等比例变化

一、首先定义全局变量

1 private float X;//当前窗体的宽度
2 private float Y;//当前窗体的高度
3 private bool IsFirst = true;

二、定义一下两个函数

 1 /// <summary>
 2 /// 将控件的宽,高,左边距,顶边距和字体大小暂存到tag属性中
 3 /// </summary>
 4 /// <param name="cons">递归控件中的控件</param>
 5 private void setTag(Control cons)
 6 {
 7   foreach (Control con in cons.Controls)
 8   {
 9     con.Tag = con.Width + ":" + con.Height + ":" + con.Left + ":" + con.Top + ":" + con.Font.Size;
10     if (con.Controls.Count > 0)
11     setTag(con);
12   }
13 }
14 //根据窗体大小调整控件大小
15 private void setControls(float newx, float newy, Control cons)
16 {
17   //遍历窗体中的控件,重新设置控件的值
18   foreach (Control con in cons.Controls)
19   {
20 
21     string[] mytag = con.Tag.ToString().Split(new char[] { ':' });//获取控件的Tag属性值,并分割后存储字符串数组
22     float a = System.Convert.ToSingle(mytag[0]) * newx;//根据窗体缩放比例确定控件的值,宽度
23     con.Width = (int)a;//宽度
24     a = System.Convert.ToSingle(mytag[1]) * newy;//高度
25     con.Height = (int)(a);
26     a = System.Convert.ToSingle(mytag[2]) * newx;//左边距离
27     con.Left = (int)(a);
28     a = System.Convert.ToSingle(mytag[3]) * newy;//上边缘距离
29     con.Top = (int)(a);
30     Single currentSize = System.Convert.ToSingle(mytag[4]) * newy;//字体大小
31     con.Font = new Font(con.Font.Name, currentSize, con.Font.Style, con.Font.Unit);
32     if (con.Controls.Count > 0)
33     {
34       setControls(newx, newy, con);
35     }
36   }
37 }

三、给窗体添加事件

1 private void Form1_Load(object sender, EventArgs e)
2 {
3   X = this.Width;//获取窗体的宽度
4   Y = this.Height;//获取窗体的高度
5   setTag(this);//调用方法
6 }

这里需要注意一下,是否第一次运行程序

1 private void Form1_Resize(object sender, EventArgs e)
2 {
   //如果是第一次运行,需要把下面的if语句取消注释,否则会没反应,其以后再运行或调试的时候,就把它注释即可
3   //if (IsFirst) { IsFirst = false; return; } 4   float newx = (this.Width) / X; //窗体宽度缩放比例 5   float newy = (this.Height) / Y;//窗体高度缩放比例 6   setControls(newx, newy, this);//随窗体改变控件大小 7 }

那么,一个简单的窗体改变大小,其里面的控件会根据其窗体等比例改变,就不会出现格式乱套的情况了。



猜你喜欢

转载自www.cnblogs.com/scc-/p/10831357.html
今日推荐