Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to CenterParent a non-modal form

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?

like image 419
nawfal Avatar asked Dec 19 '11 19:12

nawfal


4 Answers

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);
like image 64
Rotem Avatar answered Nov 08 '22 05:11

Rotem


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();
like image 30
Joe Avatar answered Nov 08 '22 04:11

Joe


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.

like image 27
prmsmp Avatar answered Nov 08 '22 04:11

prmsmp


Form2 f = new Form2();
f.StartPosition = FormStartPosition.CenterParent;
f.Show(this);
like image 38
Daniel A. White Avatar answered Nov 08 '22 06:11

Daniel A. White