C#窗体设计:[9]自动调整控件大小
1、新建一个C#应用程序,应用程序命名为Change
![C#窗体设计:[9]自动调整控件大小](https://exp-picture.cdn.bcebos.com/bfa52adaf05e4a235aa5f1a91dd818196020e26b.jpg)
3、双击窗体添加Load()函数,函数中添加一下代码:private void Form1_Load(object sender, EventArgs e) { this.Resize += new EventHandler(Form1_Resize);//窗体调整大小时引发事件 X = this.Width;//获取窗体的宽度 Y = this.Height;//获取窗体的高度 setTag(this);//调用方法 }
![C#窗体设计:[9]自动调整控件大小](https://exp-picture.cdn.bcebos.com/7496877bbbf4da58420ed1fdea0f8b56ac04d76b.jpg)
5、根据窗体大小调整控件大小,添加一下代码: private void setControls(float newx, float newy, Control cons) { //遍历窗体中的控件,重新设置控件的值 foreach (Control con in cons.Controls) { string[] mytag = con.Tag.ToString().Split(new char[] { ':' });//获取控件的Tag属性值,并分割后存储字符串数组 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); } } }
![C#窗体设计:[9]自动调整控件大小](https://exp-picture.cdn.bcebos.com/ba274f598540102a46363116b142a07aa110c56b.jpg)
7、程序运行如下:
![C#窗体设计:[9]自动调整控件大小](https://exp-picture.cdn.bcebos.com/a007a9b1eef97fbd18a83b07b74133bad2413368.jpg)