I am working on Winform application and want to open modal form in center of parent form. In Winform application there is :
So for opening modal form in center 1st obvious solution i had done is
TestModalForm obj = new TestModalForm()
obj.StartPosition = FormStartPosition.CenterParent;
obj.showdialog(this);
but above solution didn't work as modal form always considers MDI Form as its Parent. So I workout for 2nd solution: in that i wrote method in Form Load of Modal window to position it in center as below:
private void MakeWinInCenter()
{
if (this.Owner != null)
{
Form objParent = null;
int TopbarHeight = 0;
if (this.Owner.IsMdiContainer && this.Owner.ActiveMdiChild != null)
{
objParent = this.Owner.ActiveMdiChild;
TopbarHeight = GetTopbarHeight(this.Owner);
}
else
objParent = this.Owner;
Point p = new Point((objParent.Width - this.Width) / 2, (objParent.Height - this.Height) / 2);
p.X += objParent.Location.X;
p.Y += TopbarHeight + objParent.Location.Y;
this.Location = p;
}
else
{
//If owner is Null then, we have reference of MDIForm in Startup Class - use that ref and opens win in center of MDI
if (Startup.MDIObj != null)
{
this.Left = Convert.ToInt32((Startup.MDIObj.Width - this.Width) / 2);
this.Top = Convert.ToInt32((Startup.MDIObj.Height - this.Height) / 2);
}
}
}
private int GetTopbarHeight(Form MDIForm)
{
int TopbarHeight = 0;
MdiClient objMDIClient = null;
foreach (Control ctl in MDIForm.Controls)
{
if (ctl is MdiClient)
{
objMDIClient = ctl as MdiClient;
break;
}
}
if (objMDIClient != null)
{
TopbarHeight = MDIForm.Height - objMDIClient.Size.Height;
}
return TopbarHeight;
}
Above solution works perfect when MDI form is opened in Maximized form. But when we checked by resizing the MDI form (i.e. not in maximized form) or moving MDI Form to other screen - in case of multiple screens, above solution is not working and doesn't opens the modal form in center of MDI Child form
Also looked at this Question but its not helpful to my problem.
Can anyone have any suggestions or solution to solve the problem.
Thanks
Try this:
TestModalForm.showdialog(this.MdiParent);