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?
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();
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With