我有一个非模态的子窗体,它从一个父窗体中打开。我需要将子窗体居中到其父窗体。我已经将子窗体的属性设置为 CenterParent
并尝试了以下操作:
Form2 f = new Form2();
f.Show(this);
但一无所获。这适用于模态表单,但对非模态表单则不是如此。有简单的解决方案,还是需要我进行所有的数学计算来将其位置修正到中心?
我有一个非模态的子窗体,它从一个父窗体中打开。我需要将子窗体居中到其父窗体。我已经将子窗体的属性设置为 CenterParent
并尝试了以下操作:
Form2 f = new Form2();
f.Show(this);
但一无所获。这适用于模态表单,但对非模态表单则不是如此。有简单的解决方案,还是需要我进行所有的数学计算来将其位置修正到中心?
很抱歉,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);
Point
类需要 using System.Drawing;
。 - Godsmith在关于窗体居中方面,Show(this) 和 ShowDialog(this) 的行为不同真是很奇怪。我能提供的只有 Rotem 的解决方案,这个方案可以很好地隐藏掉 hacky workaround。
创建一个扩展类:
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;
}
}
轻松调用:
var form = new Form();
form.CenterForm(this).Show();
对于非模态窗体,这是解决方案。
如果您想在父窗体中心显示一个非模态对话框,则需要将子窗体的StartPosition
设置为FormStartPosition.Manual
。
form.StartPosition = FormStartPosition.Manual;
form.Location = new Point(parent.Location.X + (parent.Width - form.Width) / 2, parent.Location.Y + (parent.Height - form.Height) / 2);
form.Show(parent);
form.ControlBox = false;
form.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
如果将StartPosition
设置为FormStartPosition.Manual
,则可能会遇到子窗体部分未显示的问题。
要解决这个问题,您需要将子窗体的Localizable
属性设置为true
。
Form2 f = new Form2();
f.StartPosition = FormStartPosition.CenterParent;
f.Show(this);
StartPosition
属性吗? - Daniel A. White