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?
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);
}
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 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.
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);
}
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();
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.