How to CenterParent a non-modal form

2019-01-19 10:08发布

问题:

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?

回答1:

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


回答2:

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


回答3:

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.



回答4:

Form2 f = new Form2();
f.StartPosition = FormStartPosition.CenterParent;
f.Show(this);