naw*_*fal 22 c# forms parent-child winforms centering
我有一个非模态子表单,从父表单打开.我需要将子表单居中到其父表单.我已经设置了子表单的属性CenterParent并尝试了这个:
Form2 f = new Form2();
f.Show(this);
Run Code Online (Sandbox Code Playgroud)
但无济于事.这适用于模态形式,但非模态形式则不然.任何简单的解决方案,还是需要我通过所有数学计算来确定其位置为中心?
Rot*_*tem 58
我担心StartPosition.CenterParent只对模态对话框有好处(.ShowDialog).
您必须手动设置位置:
Form f2 = new Form();
f2.StartPosition = FormStartPosition.Manual;
f2.Location = new Point(this.Location.X + (this.Width - f2.Width) / 2, this.Location.Y + (this.Height - f2.Height) / 2);
f2.Show(this);
Run Code Online (Sandbox Code Playgroud)
Joe*_*Joe 11
Show(this)与ShowDialog(this)形式居中的行为方式不同,这似乎很奇怪.我所提供的只是Rotem的解决方案,以一种简洁的方式来隐藏hacky的解决方法.
创建扩展类:
public static class Extension
{
public static Form CenterForm(this Form child, Form parent)
{
child.StartPosition = FormStartPosition.Manual;
child.Location = new Point(parent.Location.X + (parent.Width - child.Width) / 2, parent.Location.Y + (parent.Height - child.Height) / 2);
return child;
}
}
Run Code Online (Sandbox Code Playgroud)
用最小的麻烦来称呼它:
var form = new Form();
form.CenterForm(this).Show();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18943 次 |
| 最近记录: |