using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace StandardLibrary { class AutoResize { private float defaultX = 0;//窗体初始宽度 private float defaultY = 0;//窗体初始高度 Control parentControl = new Control(); public void SetAutoResize(Control cons) { this.defaultX = cons.Width; this.defaultY = cons.Height; parentControl = cons; SetControlTag(cons); cons.Resize += ControlAutoResize; } private void SetControlTag(Control cons) { foreach (Control con in cons.Controls) { //设置控件Tag属性的数据位{控件宽度:控件高度:容器左边距离:容器右边距离:文字大小} con.Tag = con.Width + ":" + con.Height + ":" + con.Left + ":" + con.Top + ":" + con.Font.Size; if (con.Controls.Count > 0) SetControlTag(con); } } private void SetControlsAutoScaling(float newx, float newy, Control cons) { foreach (Control con in cons.Controls) { if (con.Tag == null) continue;//防止动态添加的控件(动态添加的控件没有设置Tag) string[] mytag = con.Tag.ToString().Split(':');//分割控件的Tag属性值 float controlTags = 0; controlTags = Convert.ToSingle(mytag[0]) * newx; con.Width = (int)controlTags; controlTags = Convert.ToSingle(mytag[1]) * newy; con.Height = (int)(controlTags); controlTags = Convert.ToSingle(mytag[2]) * newx; con.Left = (int)(controlTags); controlTags = Convert.ToSingle(mytag[3]) * newy; con.Top = (int)(controlTags); Single currentSize = Convert.ToSingle(mytag[4]) * Math.Min(newx, newy); con.Font = new System.Drawing.Font(con.Font.Name, currentSize, con.Font.Style, con.Font.Unit); if (con.Controls.Count > 0) SetControlsAutoScaling(newx, newy, con); } } private void ControlAutoResize(object sender, EventArgs e) { float newx = parentControl.Width / defaultX;//获取窗体宽度变化前后大小的比值 float newy = parentControl.Height / defaultY;//获取窗体高度变化前后大小的比值 SetControlsAutoScaling(newx, newy, parentControl); } } }