Winform的窗体自适应一直是PC桌面编程的难题,WPF的布局空间很强大,但是学习成本太高,介绍一种简单的在winform中可以实现的方式。
思路:1.在窗口程序中使用InitializeSize可以记录窗体初始位置
2.窗口大小变化后,会激发SizeChanged事件,计算出控件拉伸比例并重新绘制控件。
autoFit asc = new autoFit();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
asc.controllInitializeSize(this);
}
private void Form1_SizeChanged(object sender, EventArgs e)
{
asc.controlAutoSize(this);
}
自适应类
AutoFit.cs
public struct controlRect
{
public int Left;
public int Top;
public int Width;
public int Height;
}
public void controllInitializeSize(Form mForm)
{
// if (ctrl_first == 0)
{
// ctrl_first = 1;
oldCtrl = new List<controlRect>();
controlRect cR;
cR.Left = mForm.Left; cR.Top = mForm.Top; cR.Width = mForm.Width; cR.Height = mForm.Height;
oldCtrl.Add(cR);
foreach (Control c in mForm.Controls)
{
controlRect objCtrl;
objCtrl.Left = c.Left; objCtrl.Top = c.Top; objCtrl.Width = c.Width; objCtrl.Height = c.Height;
oldCtrl.Add(objCtrl);
}
}
// this.WindowState = (System.Windows.Forms.FormWindowState)(2);//记录完控件的初始位置和大小后,再最大化
//0 - Normalize , 1 - Minimize,2- Maximize
}
public void controlAutoSize(Form mForm)
{
//int wLeft0 = oldCtrl[0].Left; ;//窗体最初的位置
//int wTop0 = oldCtrl[0].Top;
////int wLeft1 = this.Left;//窗体当前的位置
//int wTop1 = this.Top;
float wScale = (float)mForm.Width / (float)oldCtrl[0].Width;//新旧窗体之间的比例,与最早的旧窗体
float hScale = (float)mForm.Height / (float)oldCtrl[0].Height;//.Height;
int ctrLeft0, ctrTop0, ctrWidth0, ctrHeight0;
int ctrlNo = 1;//第1个是窗体自身的 Left,Top,Width,Height,所以窗体控件从ctrlNo=1开始
foreach (Control c in mForm.Controls)
{
ctrLeft0 = oldCtrl[ctrlNo].Left;
ctrTop0 = oldCtrl[ctrlNo].Top;
ctrWidth0 = oldCtrl[ctrlNo].Width;
ctrHeight0 = oldCtrl[ctrlNo].Height;
//c.Left = (int)((ctrLeft0 - wLeft0) * wScale) + wLeft1;//新旧控件之间的线性比例
//c.Top = (int)((ctrTop0 - wTop0) * h) + wTop1;
c.Left = (int)((ctrLeft0) * wScale);//新旧控件之间的线性比例。控件位置只相对于窗体,所以不能加 + wLeft1
c.Top = (int)((ctrTop0) * hScale);//
c.Width = (int)(ctrWidth0 * wScale);//只与最初的大小相关,所以不能与现在的宽度相乘 (int)(c.Width * w);
c.Height = (int)(ctrHeight0 * hScale);//
ctrlNo += 1;
}
}
}
}