C# 窗体控件随窗体改变大小时间:2021-07-11 03:50:22 private void formChange() {int count = this.Controls.Count * 2 + 2; int gr1 = this.groupBox1.Controls.Count * 2 + 2; int gr2 = this.groupBox2.Controls.Count * 2 + 2;float[] factor = new float[count + gr1 + gr2]; int i = 0; factor[i++] = Size.Width; factor[i++] = Size.Height; foreach (Control ctrl in this.Controls) { factor[i++] = ctrl.Location.X / (float)Size.Width; factor[i++] = ctrl.Location.Y / (float)Size.Height; ctrl.Tag = ctrl.Size; } foreach (Control ctrl in this.groupBox1.Controls) { factor[i++] = ctrl.Location.X / (float)Size.Width; factor[i++] = ctrl.Location.Y / (float)Size.Height; ctrl.Tag = ctrl.Size; } foreach (Control ctrl in this.groupBox2.Controls) { factor[i++] = ctrl.Location.X / (float)Size.Width; factor[i++] = ctrl.Location.Y / (float)Size.Height; ctrl.Tag = ctrl.Size; }Tag = factor; } 注意窗体里的每个容器都要遍历,记录位置和大小。 在窗体 Resize事件里代码 private void JiuX_Sale_Resize(object sender, EventArgs e) { float[] scale = (float[])Tag; int i = 2; foreach (Control ctrl in this.Controls) { ctrl.Left = (int)(Size.Width * scale[i++]); ctrl.Top = (int)(Size.Height * scale[i++]); ctrl.Width = (int)(Size.Width / (float)scale[0] * ((Size)ctrl.Tag).Width); ctrl.Height = (int)(Size.Height / (float)scale[1] * ((Size)ctrl.Tag).Height); } foreach (Control ctrl in this.groupBox1.Controls) { ctrl.Left = (int)(Size.Width * scale[i++]); ctrl.Top = (int)(Size.Height * scale[i++]); ctrl.Width = (int)(Size.Width / (float)scale[0] * ((Size)ctrl.Tag).Width); ctrl.Height = (int)(Size.Height / (float)scale[1] * ((Size)ctrl.Tag).Height); } foreach (Control ctrl in this.groupBox2.Controls) { ctrl.Left = (int)(Size.Width * scale[i++]); ctrl.Top = (int)(Size.Height * scale[i++]); ctrl.Width = (int)(Size.Width / (float)scale[0] * ((Size)ctrl.Tag).Width); ctrl.Height = (int)(Size.Height / (float)scale[1] * ((Size)ctrl.Tag).Height); } }