winform 如何使: 控件的大小和位置随窗体的缩放改变
winform(c#) 如何使: 控件的大小和位置随窗体的缩放改变
注: 是指窗体内的所有控件。
不要跟我说什么Anchor属性 Dock属性设置,不是那类问题!~ 网上已经看过多方资料,未看到实用的办法!
已试过如下两种方法:
1.
public static void AutoScale(Form frm)
{
frm.Tag = frm.Width.ToString() + "," + frm.Height.ToString();
frm.SizeChanged += new EventHandler(frm_SizeChanged);
}
static void frm_SizeChanged(object sender, EventArgs e)
{
string[] tmp = ((Form)sender).Tag.ToString().Split(',');
float width = (float)((Form)sender).Width / (float)Convert.ToInt16(tmp[0]);
float heigth = (float)((Form)sender).Height / (float)Convert.ToInt16(tmp[1]);
((Form)sender).Tag = ((Form)sender).Width.ToString() + "," + ((Form)sender).Height;
foreach (Control control in ((Form)sender).Controls)
{
control.Scale(new SizeF(width, heigth));
}
}
此方法位置可变,但是字体大小不能缩放。并且,在窗体拉伸的时候不灵活,有滞留!
2.
public float X;
public float Y;
public float y;
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)
{
foreach (Control con in cons.Controls)
{
string[] mytag = con.Tag.ToString().Split(new char[] { ':' });//执行到此处报错,把Tag换成Name时候,不报错。但是执行到下一条语句编译无法通过
float a = Convert.ToSingle(mytag[0]) * newx;
con.Width = (int)a;
a = Convert.ToSingle(mytag[1]) * newy;
con.Height = (int)(a);
a = Convert.ToSingle(mytag[2]) * newx;
con.Left = (int)(a);
a = Convert.ToSingle(mytag[3]) * newy;
con.Top = (int)(a);
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);
}
}
}
void Form1_Resize(object sender, EventArgs e)
{
// throw new Exception("The method or operation is not implemented.");
float newx = (this.Width) / X;
// float newy = (this.Height - this.statusStrip1.Height) / (Y - y);
float newy = this.Height / Y;
setControls(newx, newy, this);
this.Text = this.Width.ToString() + " " + this.Height.ToString();
}
private void ResizeTest_Load(object sender, EventArgs e)
{
this.Resize += new EventHandler(Form1_Resize);
X = this.Width;
Y = this.Height;
y = this.statusStrip1.Height;
setTag(this);
}
此方法报错~没编译通过
[解决办法]
该回复于2011-11-24 13:20:11被版主删除