Show a child form in the centre of Parent form in C#

Try:

loginForm.StartPosition = FormStartPosition.CenterParent;
loginForm.ShowDialog(this);

Of course the child for will now be a blocking form (dialog) of the parent window, if that isn't desired then just replace ShowDialog with Show..

loginForm.Show(this);

You will still need to specify the StartPosition though.


The setting of parent does not work for me unless I use form.ShowDialog();.

When using form.Show(); or form.Show(this); nothing worked until I used, this.CenterToParent();. I just put that in the Load method of the form. All is good.

Start position to the center of parent was set and does work when using the blocking showdialog.


There seems to be a confusion between "Parent" and "Owner". If you open a form as MDI-form, i.e. imbedded inside another form, then this surrounding form is the Parent. The form property StartPosition with the value FormStartPosition.CenterParent refers to this one. The parameter you may pass to the Show method is the Owner, not the Parent! This is why frm.StartPosition = FormStartPosition.CenterParent does not work as you may expect.

The following code placed in a form will center it with respect to its owner with some offset, if its StartPosition is set to Manual. The small offset opens the forms in a tiled manner. This is an advantage if the owner and the owned form have the same size or if you open several owned forms.

protected override void OnShown(EventArgs e)
{
    base.OnShown(e);
    if (Owner != null && StartPosition == FormStartPosition.Manual) {
        int offset = Owner.OwnedForms.Length * 38;  // approx. 10mm
        Point p = new Point(Owner.Left + Owner.Width / 2 - Width / 2 + offset, Owner.Top + Owner.Height / 2 - Height / 2 + offset);
        this.Location = p;
    }
}

Tags:

C#

Winforms