一、概述

     本文要实现的功能是:当窗体最大化时,控件的大小可以随窗体一起变化。开发环境,vs2010 c# winform,窗体名称采用默认的Form1.

2、把调整控件大小的方法放到一个类中:FormSetSelfAuto.cs

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Windows.Forms;
 6 using System.Drawing;
 7 
 8 
 9 namespace Kaifafanli
10 {
11    public class FormSetSelfAuto
12     {
13         private float X;
14         private float Y;
15         public float _x
16         {
17             set { X = value; }
18         }
19         public float _y
20         {
21             set { Y = value; }
22         }
23        //获取控件的width,height,left,top,字体的大小值,存放在控件的tag属性中
24         public void setTag(Control cons)
25         { 
26          //遍历窗体中的控件
27             foreach(Control con in cons.Controls)
28             {
29                 con.Tag = con.Width + ":" + con.Height + ":" + con.Left + ":" + con.Top + ":" + con.Font.Size;
30                 if(con.Controls.Count>0)
31                 {
32                     setTag(con);
33                 }
34             }
35         }
36        //根据窗体大小调整控件大小 
37        public void setControls(float newx,float newy,Control cons)
38         { 
39           //遍历窗体中的控件,重新设置控件的值
40             foreach(Control con in cons.Controls)
41             {
42             //获取控件tag属性值,并分割后存储字符串数组
43                 string[] mytag=con.Tag.ToString().Split(new char[]{':'});
44                 float a = Convert.ToSingle(mytag[0]) * newx;//根据窗体缩放比例确定控件的宽度值
45                 con.Width = (int)a;
46                 a = Convert.ToSingle(mytag[1]) * newy;
47                 con.Height = (int)a;//高度
48 
49                 a = Convert.ToSingle(mytag[2]) * newx;
50                 con.Left = (int)a;//左边缘距离
51                 a = Convert.ToSingle(mytag[3]) * newy;
52                 con.Top = (int)a;//上边缘距离
53                 Single currentSize = Convert.ToSingle(mytag[4]) * newy;
54                 con.Font = new Font(con.Font.Name,currentSize,con.Font.Style,con.Font.Unit);
55                 if(con.Controls.Count>0)
56                 {
57                     setControls(newx,newy,con);
58                 }
59 
60             }
61         }
62        public void form_Resize(Form fr)
63        {
64            float newx = (fr.Width) / X;
65            float newy = (fr.Height) / Y;
66            setControls(newx, newy, fr);
67            fr.Text = fr.Width.ToString() + " " + fr.Height.ToString();
68        }
69     }
70 }
FormSetSelfAuto.cs

相关文章: