public partial class 控件自适应 : Form
{
public float X;
public float Y;
public 控件自适应()
{
InitializeComponent();
X = this.Width;
Y = this.Height;
setTag(this);
this.Resize += new System.EventHandler(this.Login_Resize);
}
private void Login_Resize(object sender, EventArgs e)
{
setControls((float)this.Width / X, (float)this.Height / Y, this);
}
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 newx, float newy, Control cons)
{
if (cons.Controls.Count > 0)
{
foreach (Control con in cons.Controls)
{
string[] mytag = con.Tag.ToString().Split(new char[] { ':' });
//string[] mytag = con.Tag != null ? con.Tag.ToString().Split(new char[] { ':' }) : new string[0];
float a = Convert.ToSingle(mytag[0]) * newx;
con.Width = int.Parse(a.ToString("#0"));
a = Convert.ToSingle(mytag[1]) * newy;
con.Height = int.Parse(a.ToString("#0"));
a = Convert.ToSingle(mytag[2]) * newx;
con.Left = int.Parse(a.ToString("#0"));
a = Convert.ToSingle(mytag[3]) * newy;
con.Top = int.Parse(a.ToString("#0"));
Single currentSize = 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);
}
}
}
else
{
// 处理 controls 为空的情况,例如返回错误提示或者执行其他操作
MessageBox.Show("sehugbj");
}
}
}