Winfrom 控件跟随窗体大小变化而变化
#region 窗体基本事件,这里需要根据自己的窗体设置相应事件
private void Form_Load(object sender, EventArgs e)
{
serverFrom = this;
ChangeFormSize();
}
private void From_Resize(object sender, EventArgs e)
{
float WidthChangeProportion = (this.Width) / CurrentWidth;
float HeightChangeProportion = (this.Height) / CurrentHeight;
UpdateControlsSize(WidthChangeProportion, HeightChangeProportion, this);
}
#endregion
#region 控件大等比例放大,可以直接搬运代码
private float CurrentWidth { get; set; }
private float CurrentHeight { get; set; }
private void ChangeFormSize()
{
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
CurrentWidth = this.Width;
CurrentHeight = this.Height;
SetControTag(this);
}
private void SetControTag(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)
{
SetControTag(con);
}
}
}
public static void SetControlDoubleBuffer(Control cc)
{
cc.GetType().GetProperty("DoubleBuffered", System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.NonPublic).SetValue(cc, true, null);
}
private void UpdateControlsSize(float WidthChangeProportion, float HeightChangeProportion, Control cons)
{
foreach (Control con in cons.Controls)
{
SetControlDoubleBuffer(this);
SetControlDoubleBuffer(con);
if (con.Tag != null)
{
string[] mytag = con.Tag.ToString().Split(new char[] { ';' });
con.Width = Convert.ToInt32(System.Convert.ToSingle(mytag[0]) * WidthChangeProportion);
con.Height = Convert.ToInt32(System.Convert.ToSingle(mytag[1]) * HeightChangeProportion);
con.Left = Convert.ToInt32(System.Convert.ToSingle(mytag[2]) * WidthChangeProportion);
con.Top = Convert.ToInt32(System.Convert.ToSingle(mytag[3]) * HeightChangeProportion);
Single currentSize = System.Convert.ToSingle(mytag[4]) * HeightChangeProportion;
con.Font = new Font(con.Font.Name, currentSize, con.Font.Style, con.Font.Unit);
if (con.Controls.Count > 0)
{
UpdateControlsSize(HeightChangeProportion, HeightChangeProportion, con);
}
}
}
}
#endregion