保定网站建设亚洲足球最新排名
用于控件大小随窗体大小等比例缩放的C#代码。该代码可以在窗体重载中使用,以确保窗体中的控件在窗体大小改变时能够按比例缩放。
SetTag
方法:该方法用于设置控件的Tag
属性,以存储控件的宽度、高度、左边距、顶边距和字体大小等信息。SetControls
方法:该方法用于遍历窗体中的控件,并根据窗体缩放的比例重新设置控件的大小和位置。
封装缩放函数
/// <summary>
/// 定义当前窗体的宽度
/// </summary>
public static float X;
/// <summary>
/// 定义当前窗体的高度
/// </summary>
public static float Y;
/// <summary>
/// 控件大小随窗体大小等比例缩放,
/// 在窗体重载中使用
/// </summary>
/// <param name="cons"></param>
public static 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);}}}/// <summary>/// /// </summary>/// <param name="newx"></param>/// <param name="newy"></param>/// <param name="cons"></param>
public static void SetControls(float newx, float newy, Control cons)
{//遍历窗体中的控件,重新设置控件的值foreach(Control con in cons.Controls){//获取控件的Tag属性值,并分割后存储字符串数组if(con.Tag != null){string[] mytag = con.Tag.ToString().Split(new char[]{';'});//根据窗体缩放的比例确定控件的值con.Width = Convert.ToInt32(System.Convert.ToSingle(mytag[0]) * newx); //宽度con.Height = Convert.ToInt32(System.Convert.ToSingle(mytag[1]) * newy); //高度con.Left = Convert.ToInt32(System.Convert.ToSingle(mytag[2]) * newx); //左边距con.Top = Convert.ToInt32(System.Convert.ToSingle(mytag[3]) * newy); //顶边距Single currentSize = System.Convert.ToSingle(mytag[4]) * newy; //字体大小con.Font = new Font(con.Font.Name, currentSize, con.Font.Style, con.Font.Unit);if(con.Controls.Count > 0){SetControls(newx, newy, con);}}}
}
窗体初始化时使用
// 在窗体重载方法中调用SetTag方法,设置控件的Tag属性
public ExeStart()
{InitializeComponent();MechForm.X = this.Width;MechForm.Y = this.Height;MechForm.SetTag(this);
}
在Resize事件加载中使用
在窗体大小改变事件中调用SetControls方法,重新设置控件的大小和位置
private void ExeStart_Resize(object sender, EventArgs e)
{float newX = this.Width / MechForm.X; //获取当前宽度与初始宽度的比例float newY = this.Height / MechForm.Y; //获取当前高度与初始高度的比例MechForm.SetControls(newX, newY, this);
}