需求:當窗體尺寸動態改變時,窗體中的各類控件(包括Panel以及Panel中的子控件)能夠動態調節自身大小,以適應窗體內容比例。函數
方法:this
第一步,新建一個類,代碼以下:spa
class Resize { private Form _form; public Resize(Form form) { int count = form.Controls.Count * 2 + 2; float[] factor = new float[count]; int i = 0; factor[i++] = form.Size.Width; factor[i++] = form.Size.Height; foreach (Control ctrl in form.Controls) { factor[i++] = ctrl.Location.X / (float)form.Size.Width; factor[i++] = ctrl.Location.Y / (float)form.Size.Height; ctrl.Tag = ctrl.Size; } form.Tag = factor; this._form = form; } public void Form1_Resize(object sender, EventArgs e) { float[] scale = (float[])this._form.Tag; int i = 2; foreach (Control ctrl in this._form.Controls) //panel的長寬增加到一個固定的值就不會再增加了,緣由:Panel的寬和高上限是65535像素(https://blog.csdn.net/dufangfeilong/article/details/41805073?utm_source=blogxgwz5) { ctrl.Left = (int)(this._form.Size.Width * scale[i++]); ctrl.Top = (int)(this._form.Size.Height * scale[i++]); ctrl.Width = (int)(this._form.Size.Width / (float)scale[0] * ((Size)ctrl.Tag).Width); ctrl.Height = (int)(this._form.Size.Height / (float)scale[1] * ((Size)ctrl.Tag).Height); } } }
第二步,在Form的初始化函數中使用這個類:.net
public Form_StockCount() { InitializeComponent(); this.SizeChanged += new Resize(this).Form1_Resize; //窗口自適應代碼 }