FormStartPosition.CenterParent does not work

前端 未结 13 909
独厮守ぢ
独厮守ぢ 2021-01-01 08:57

In the following code, only the second method works for me (.NET 4.0). FormStartPosition.CenterParent does not center the child form over its parent. Why?

相关标签:
13条回答
  • 2021-01-01 09:50

    Small Change to JYelton's answer

    Form2_Load(object sender, EventArgs e)
    {
        if (Owner != null && Parent == null && StartPosition == FormStartPosition.CenterParent)
        Location = new Point(Owner.Location.X + Owner.Width / 2 - Width / 2,
            Owner.Location.Y + Owner.Height / 2 - Height / 2);
    }
    
    0 讨论(0)
  • 2021-01-01 09:57

    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);
    }
    
    0 讨论(0)
  • 2021-01-01 09:57

    I found a solution that will center modeless window position to parent's position, and the child window can be still covered by parent window. You just have to call

    f2.Show(f1);
    

    which will set f2 owner to f1, f2 will show over the f1 at it's center position.

    Next you set

    f2.Owner = null;
    

    and there you go, f2 is a separate window, with correct startup position.

    0 讨论(0)
  • 2021-01-01 09:59

    JYelton's answer worked for me, but the form is only centered the first time Show() is called. If you want to Hide() the form, and then have it re-centered on the parent every time Show() is called you need use the following in your form:

    public new void Show(IWin32Window owner)
    {
        base.Show(owner);
    
        if (Owner != null)
            Location = new Point(Owner.Location.X + Owner.Width / 2 - Width / 2,
                Owner.Location.Y + Owner.Height / 2 - Height / 2);
    }
    
    0 讨论(0)
  • 2021-01-01 10:00

    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();
    
    0 讨论(0)
  • 2021-01-01 10:04

    An old question, I know, but I had the same issue but for a different reason.

    The Form I was opening had an overridden OnLoad method:

    protected override void OnLoad(EventArgs e)
    {
       //... etc.
    }
    

    but was not calling the base implementation as it must do:

    protected override void OnLoad(EventArgs e)
    {
       //... etc.
       base.OnLoad(e);
    }
    

    When overriding OnLoad(EventArgs) in a derived class, be sure to call the base class's OnLoad(EventArgs) method so that registered delegates receive the event.

    0 讨论(0)
提交回复
热议问题