FormStartPosition.CenterParent does not work

I found setting the location manually is the only reliable option in some more complex cases when form is auto-sized and dynamically modified.

However rather than computing the coordinates manually, I'd suggest using existing method:

this.CenterToParent();

This is because you are not telling f2 who its Parent is.

If this is an MDI application, then f2 should have its MdiParent set to f1.

Form f2 = new Form() { Width = 400, Height = 300 };
f2.StartPosition = FormStartPosition.CenterParent;
f2.MdiParent = f1;
f2.Show();

If this is not an MDI application, then you need to call the ShowDialog method using f1 as the parameter.

Form f2 = new Form() { Width = 400, Height = 300 };
f2.StartPosition = FormStartPosition.CenterParent;
f2.ShowDialog(f1);

Note that CenterParent does not work correctly with Show since there is no way to set the Parent, so if ShowDialog is not appropriate, the manual approach is the only viable one.


If you set the owner of the child form like so:

Form2 f = new Form2();
f.Show(this);

You can then center it easily like this:

Form2_Load(object sender, EventArgs e)
{
    if (Owner != null)
        Location = new Point(Owner.Location.X + Owner.Width / 2 - Width / 2,
            Owner.Location.Y + Owner.Height / 2 - Height / 2);
}

I'm using this code inside my main form, hope it helps:

var form = new MyForm();
form.Show();
if (form.StartPosition == FormStartPosition.CenterParent)
{
    var x = Location.X + (Width - form.Width) / 2;
    var y = Location.Y + (Height - form.Height) / 2;
    form.Location = new Point(Math.Max(x, 0), Math.Max(y, 0));
}