C# winform控件大小跟随窗体大小改变

发布时间 2023-11-03 20:39:44作者: 芈璐
int iFormWidth, iFormHeight;//初始窗体宽高
//窗体加载事件
private void Form1_Load(object sender, EventArgs e)
{
    iFormWidth = this.Width;//初始宽
    iFormHeight = this.Height;//初始高
    WriteIn_Tags(this);//记录初始控件信息
}

//调整控件大小事件
private void Form1_Resize(object sender, EventArgs e)
{
    Form frmMain = (Form)sender;
    double scaleX = frmMain.Width * 1.0 / iFormWidth;
    double scaleY = frmMain.Height * 1.0 / iFormHeight;
    ResizeAllControls(frmMain, scaleX, scaleY);
}

//将所有控件信息写入控件的Tag里
public void WriteIn_Tags(Control cons)
{
    //遍历所有控件
    foreach (Control con in cons.Controls)
    {
        string strConInfo = con.Width.ToString() + "?" + con.Height.ToString() + "?" + con.Left.ToString() + "?" + con.Top.ToString() + "?" + con.Font.Size.ToString();//记录控件的宽、高、左距、顶距和字体大小
        con.Tag = strConInfo;
        if (con.Controls.Count > 0)//子控件处理
        {
            WriteIn_Tags(con);//递归遍历
        }
    }
}

//控件大小跟随窗体大小比例进行转换
public void ResizeAllControls(Control cons, double scaleX, double scaleY)
{
    //遍历所有控件
    foreach (Control con in cons.Controls)
    {
        var tags = con.Tag.ToString().Split(new char[] { '?' });//识别保存在Tag里控件信息
        int iWidthOld = Convert.ToInt32(tags[0]);
        int iHeightOld = Convert.ToInt32(tags[1]);
        int iLeftOld = Convert.ToInt32(tags[2]);
        int iTopOld = Convert.ToInt32(tags[3]);
        double dFontSizeOld = Convert.ToDouble(tags[4]);

        con.Width = Convert.ToInt32(iWidthOld * scaleX);
        con.Height = Convert.ToInt32(iHeightOld * scaleY);
        con.Left = Convert.ToInt32(iLeftOld * scaleX);
        con.Top = Convert.ToInt32(iTopOld * scaleY);
        int iFontSizeNew = Convert.ToInt32(dFontSizeOld * scaleX);
        con.Font = new Font(con.Font.Name, iFontSizeNew, Font.Style);

        if (con.Controls.Count > 0)//子控件处理
        {
            ResizeAllControls(con, scaleX, scaleY);//递归遍历
        }
    }
}