通常,我使用以下方法编写可调整大小(优雅)的表单。
using System.Drawing;
using System.Windows.Forms;
namespace silly
{
public class Form1 : Form
{
private GroupBox g;
private Button b1, b2;
public Form1()
{
Init();
}
private void Init()
{
//create and add controls.
this.Controls.Add(g = new GroupBox());
g.Controls.AddRange(new Control[] {
b1 = new Button(),
b2 = new Button()});
g.Text = "group";
b1.Text = "b1";
b2.Text = "b2!";
b1.AutoSize = b2.AutoSize = true;
g.Resize += new System.EventHandler(g_Resize);
}
private void g_Resize(object sender, System.EventArgs e)
{
b1.Size = b2.Size = new Size(g.ClientSize.Width, g.ClientSize.Height/2);
b1.Location = Point.Empty;
b2.Location = new Point(b1.Left, b1.Bottom);
}
protected override void OnResize(System.EventArgs e)
{
g.Size = this.ClientSize;
g.Location = Point.Empty;
}
}
}
但是,您会很快注意到,该g.ClientSize
属性不像该属性那样工作Form.ClientSize
。我一直在做的是添加一个Point
值:
private readonly static Point grp_zero = new Point(10, 20);
帮助正确放置组件。使用这个值,我可以重构g_Resize
方法:
b1.Size = b2.Size = new Size(g.ClientSize.Width - grp_zero.X * 2,
g.ClientSize.Height/2 - grp_zero.X - grp_zero.Y);
b1.Location = grp_zero;
b2.Location = new Point(b1.Left, b1.Bottom);
取得了相当不错的成绩。但是,如果在 末尾Init();
,则找到以下代码:
g.Font = new Font(g.Font.FontFamily, 28);
或类似的东西,grp_zero
值得调整大小。
问题
有没有很好的解决方法来对抗这种疯狂?你做什么工作?
我试过Dock
and Anchor
,但我似乎无法让他们让按钮填满GroupBox
客户区。我在这里追求的效果是每个按钮填充他的客户区域的一半。
提前致谢。