测试目的:如何使得窗体内的控件可以跟从窗体巨细自动调治
测试环境:WIN10 ENT + VS2015
要领道理:记录初始时窗口巨细、控件巨细等信息。每当窗口巨细变革时,计算窗口巨细相对付初始时的缩放比例,,然后按照缩放比例再调解控件的位置(Location)、巨细(Size)、字体巨细(Font.Size)。
C#主要测试代码:
using System; using System.Drawing; using System.Windows.Forms; namespace TEST1111 { public partial class Form1 : Form { int igFormWidth = new int(); //窗口宽度 int igFormHeight = new int(); //窗口高度 float fgWidthScaling = new float(); //宽度缩放比例 float fgHeightScaling = new float(); //高度缩放比例 public Form1() { InitializeComponent(); igFormWidth = this.Width; igFormHeight = this.Height; InitConTag(this); } private void Form1_Load(object sender, EventArgs e) { } private void Form1_Resize(object sender, EventArgs e) { if (igFormWidth == 0 || igFormHeight == 0) return; fgWidthScaling = (float)this.Width / (float)igFormWidth; fgHeightScaling = (float)this.Height / (float)igFormHeight; ResizeCon(fgWidthScaling, fgHeightScaling, this); } //记录控件集初始的 位置、巨细、字体巨细信息 private void InitConTag(Control cons) { foreach (Control con in cons.Controls) //遍历控件集 { con.Tag = con.Left + "," + con.Top + "," + con.Width + "," + con.Height + "," + con.Font.Size; if (con.Controls.Count > 0) //措置惩罚惩罚子控件 { InitConTag(con); } } } //从头调解控件的 位置、巨细、字体巨细 private void ResizeCon(float widthScaling, float heightScaling, Control cons) { float fTmp = new float(); foreach (Control con in cons.Controls) //遍历控件集 { string[] conTag = con.Tag.ToString().Split(new char[] {‘,‘}); fTmp = Convert.ToSingle(conTag[0]) * widthScaling; con.Left = (int)fTmp; fTmp = Convert.ToSingle(conTag[1]) * heightScaling; con.Top = (int)fTmp; fTmp = Convert.ToSingle(conTag[2]) * widthScaling; con.Width = (int)fTmp; fTmp = Convert.ToSingle(conTag[3]) * heightScaling; con.Height = (int)fTmp; fTmp = Convert.ToSingle(conTag[4]) * widthScaling * heightScaling; con.Font = new Font("", fTmp); if (con.Controls.Count > 0) //措置惩罚惩罚子控件 { ResizeCon(widthScaling, heightScaling, con); } } } } }运行初始图: