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

后端 未结 19 1150
不思量自难忘°
不思量自难忘° 2020-11-28 08:21

I create a new form and call from the parent form as follows:

loginForm = new SubLogin();   
loginForm.Show();

I need to display the chi

19条回答
  •  日久生厌
    2020-11-28 09:10

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

提交回复
热议问题