如何将非模态表单居中
我有一个从父表单打开的非模式子表单。我需要将子窗体以其父窗体居中。我已将子窗体的属性设置为 CenterParent 并尝试了此操作:
Form2 f = new Form2();
f.Show(this);
但无济于事。这适用于模态形式,但不适用于非模态形式。有什么简单的解决方案,还是需要我进行所有数学计算才能将其位置固定在中心?
I have a non-modal child form which opens up from a parent form. I need to center the child form to its parent form. I have set property of child form to CenterParent
and tried this:
Form2 f = new Form2();
f.Show(this);
but to no avail. This works with modal form, but not so with non-modal forms. Any simple solution, or need I go through all that mathematical calculation to fix its position to center?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
恐怕
StartPosition.CenterParent
仅适用于模式对话框 (.ShowDialog
)。您必须手动设置位置,如下所示:
I'm afraid
StartPosition.CenterParent
is only good for modal dialogs (.ShowDialog
).You'll have to set the location manually as such:
看起来很奇怪,Show(this) 的行为与 ShowDialog(this) 对于表单居中的方式不同。我所提供的只是 Rotem 的解决方案,以一种巧妙的方式隐藏了 hacky 解决方法。
创建一个扩展类:
轻松调用它:
It seems really weird that Show(this) doesn't behave the same way as ShowDialog(this) w.r.t form centering. All I have to offer is Rotem's solution in a neat way to hide the hacky workaround.
Create an extension class:
Call it with minimal fuss:
对于无模式形式,这就是解决方案。
如果您想在父窗体的中心显示无模式对话框,则需要将子窗体的
StartPosition
设置为FormStartPosition.Manual
。在 .NET Framework 4.0 中 - 如果将子窗体的 ControlBox 属性设置为
false
并将FormBorderStyle
属性设置为NotSizes
如下所示:那么您将面临如果将
StartPosition
设置为FormStartPosition.Manual
,则出现部分子表单不显示的问题。要解决此问题,您需要将子表单的
Localizable
属性设置为true
。For modeless form, this is the solution.
If you want to show a modeless dialog in the center of the parent form then you need to set child form's
StartPosition
toFormStartPosition.Manual
.In .NET Framework 4.0 - If you set ControlBox property of child form to
false
andFormBorderStyle
property toNotSizable
like below:then you will face the problem where part of child form doesn't show, if
StartPosition
is set toFormStartPosition.Manual
.To solve this you need to set child form's
Localizable
property totrue
.