要实现这个功能,选择使用代码,当窗口缩放的时候,控件位置与大小也跟着等比例缩放。将控件存放在Pannl容器中,以方便获取控件。
namespace 控件布局的自适应
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//容器的宽高
public int normWidth, normHeight;
//用来存放需要改变大小的控件字典
public Dictionary<string, Rec> buttonControl = new Dictionary<string, Rec>();//
//写一个类,里面用来存放控件原始的位置和宽高
public class Rec
{
public int x;
public int y;
public int width;
public int height;
public Rec(int x,int y, int width,int height)
{
this.x = x;
this.y = y;
this.height = height;
this.width = width;
}
}
//窗口加载时触发的事件
private void Form1_Load(object sender, EventArgs e)
{
//将初始值保存
normWidth = this.panel2.Width;
normHeight = this.panel2.Height;
//遍历容器中的所有控件,添加进字典
foreach (Control item in this.panel2.Controls)
{
buttonControl.Add(item.Name, new Rec(item.Left, item.Top, item.Width,item.Height));
}
}
//窗口大小变换时触发的事件
private void Form1_SizeChanged(object sender, EventArgs e)
{
//获取改变窗口位置后的容器宽高
int w = panel2.Width;
int h = panel2.Height;
//根据缩放后的容器大小按比例重新给控件位置赋值
foreach (Control item in panel2.Controls)//遍历容器中的控件
{
item.Left =(int)(w * 1.0 / normWidth * buttonControl[item.Name].x);
item.Top = (int)(h * 1.0 / normHeight * buttonControl[item.Name].y);
item.Width = (int)(w * 1.0 / normWidth * buttonControl[item.Name].width);
item.Height = (int)(h * 1.0 / normHeight * buttonControl[item.Name].height);
}
}
}
}