控件随窗体的大小改变
窗体默认是最大化显示,在第一次启动的时候 控件就得根据窗体的大小变化而变化编程时 窗体不是最大化的 控件取得是相应的大小。。。
怎么样才能在第一次默认最大化启动下 控件也能做相应的改变。。
程序代码:using System;
using System.Collections.Generic;
using using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace _2_end
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private float X; private float Y;
//获取控件的width、height、left、top、字体大小的值,存放在控件的Tag属性中
private void setTag(Control cons)
{
foreach (Control con in cons.Controls)//获取所有控件
{
con.Tag = con.Width + ";" + con.Height + ";" + con.Left + ";" + con.Top + ";" + con.Font.Size;
if (con.Controls.Count > 0)
setTag(con);
}
}
//根据窗体大小调整控件大小
private void setControls(float xinX, float xinY, Control cons)
{
foreach (Control con in cons.Controls)
{
if (con.Tag == null)
{
this.WindowState = FormWindowState.Normal;
}
else
{
string[] mytag = con.Tag.ToString().Split(new char[] { ';' });
//获取控件的Tag属性值,并分割后存储字符串数组
float a = Convert.ToSingle(mytag[0]) * xinX;//根据窗体缩放比例确定控件的值
con.Width = (int)a;//宽度
a = Convert.ToSingle(mytag[1]) * xinY;//高度
con.Height = (int)(a);
a = Convert.ToSingle(mytag[2]) * xinX;//左边距离
con.Left = (int)(a);
a = Convert.ToSingle(mytag[3]) * xinY;//顶端距离
con.Top = (int)(a);
Single currentSize = Convert.ToSingle(mytag[4]) * xinY;//字体大小
con.Font = new Font(con.Font.Name, currentSize, con.Font.Style, con.Font.Unit);
if (con.Controls.Count > 0)
{
setControls(xinX, xinY, con);
}
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
this.Resize += new EventHandler(Form1_Resize);//窗体调整大小时引发事件
X = this.Width;//获取窗体的宽度
Y = this.Height;//获取窗体的高度
setTag(this);//调用方法
}
private void Form1_Resize(object sender, EventArgs e)
{
float xinX = (this.Width) / X;
float xinY = (this.Height) / Y;//得到窗体缩放的比例
setControls(xinX, xinY, this);
}
}
}这个代码只能在第二次拖放后才有效果。。。第一次默认最大化启动 没有任何效果









