原始大小
放大后
panel1 dock 属性值 top
panel2 dock 属性值 fill
代码
public partial class Form1 : Form
{
int normalWidth = 0; //窗体默认宽高
int normalHeight = 0; //记录控件的位置
Dictionary<string, Rectangle> normalControls = new Dictionary<string, Rectangle>();
public Form1()
{
InitializeComponent();
this.Load+=Form1_Load;
this.SizeChanged+=Form1_SizeChanged;
}
private void Form1_SizeChanged(object sender, EventArgs e)
{
foreach (Control item in panel2.Controls)
{
int w = this.panel2.Width;
int h = this.panel2.Height;
int newX = (int)(w * 1.0 / normalWidth * normalControls[item.Name].X);
int newY = (int)(h * 1.0 / normalHeight * normalControls[item.Name].Y);
int newW = (int)(w * 1.0 / normalWidth * normalControls[item.Name].Width);
int newH = (int)(h * 1.0 / normalHeight * normalControls[item.Name].Height);
item.Left = newX;
item.Top = newY;
item.Width = newW;
item.Height = newH;
}
}
private void Form1_Load(object sender, EventArgs e)
{
normalWidth = this.panel2.Width;
normalHeight = this.panel2.Height;
foreach (Control item in panel2.Controls)
{
normalControls.Add(item.Name, new Rectangle(item.Left, item.Top, item.Width, item.Height));
}
}
}