How to CenterParent a non-modal form

前端 未结 4 1354
旧时难觅i
旧时难觅i 2020-12-11 00:07

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<

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-11 00:59

    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();
    

提交回复
热议问题