How to CenterParent a non-modal form

北城余情 提交于 2019-11-28 11:54:33

I'm afraid StartPosition.CenterParent is only good for modal dialogs (.ShowDialog).
You'll have to set the location manually as such:

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);

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:

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;
    }
}

Call it with minimal fuss:

var form = new Form();
form.CenterForm(this).Show();
prmsmp

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 to 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);

In .NET Framework 4.0 - If you set ControlBox property of child form to false and FormBorderStyle property to NotSizable like below:

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

then you will face the problem where part of child form doesn't show, if StartPosition is set to FormStartPosition.Manual.

To solve this you need to set child form's Localizable property to true.

Form2 f = new Form2();
f.StartPosition = FormStartPosition.CenterParent;
f.Show(this);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!