如何将CenterParent转换为非模态forms

我有一个非模态子表单,从父表单打开。 我需要将子表单居中到其父表单。 我已将子表单的属性设置为CenterParent并尝试了此操作:

 Form2 f = new Form2(); f.Show(this); 

但无济于事。 这适用于模态forms,但非模态forms则不然。 任何简单的解决方案,还是需要我通过所有数学计算来确定其位置为中心?

我担心StartPosition.CenterParent仅适用于modal dialog( .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); 

Show(this)的行为与ShowDialog(this)forms居中的行为方式相似,这似乎很奇怪。 我所提供的只是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; } } 

用最小的麻烦来称呼它:

 var form = new Form(); form.CenterForm(this).Show(); 
 Form2 f = new Form2(); f.StartPosition = FormStartPosition.CenterParent; f.Show(this); 

对于无模式,这是解决方案。

如果要在父窗体的中心显示无模式对话框,则需要将子窗体的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); 

在.NET Framework 4.0中 – 如果将子窗体的ControlBox属性设置为false ,将FormBorderStyle属性设置为NotSizable如下所示:

 form.ControlBox = false; form.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; 

如果StartPosition设置为FormStartPosition.Manual ,那么您将面临子窗体的一部分未显示的问题。

要解决此问题,您需要将子窗体的Localizable属性设置为true