I am working on a Winform application and want to open a modal form in the center of the parent form. The Winform application has:
- MDI form (open as a launch form and acts as a container for everyone)
- when you click on one of the menu items of the MDI form, the MDI child form opens
- when you click one of the buttons on the MDI Child, open in step 2, the modal form opens, which we must open in the center of the MDI Child form (open in step 2).
So, to open the modal form in the center of the 1st obvious decision I made was
TestModalForm obj = new TestModalForm() obj.StartPosition = FormStartPosition.CenterParent; obj.showdialog(this);
but the solution above does not work, since the modal form always considers the MDI Form as its parent. Therefore, I train for the second solution: in that I wrote a method in the form of Loading a modal window to place it in the center, as shown 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); pX += objParent.Location.X; pY += 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; }
The above solution works perfectly when the MDI form opens in a maximized form. But when we checked by changing the MDI form (i.e. Not in a maximized form) or moving the MDI form to another screen - in the case of several screens above, the solution does not work and does not open the modal form in the center of the MDI Child form
Also looked at this question , but that did not help my problem.
Anyone have suggestions or solutions to solve the problem.
thanks
source share