Reputation: 246
Disclaimer: I know answers have already been provided for a similar question however these do not appear to be working for me.
I have an application which uses a main form with an MDIClient; I want to show a dialog which allows the user to enter a value; this dialog is to show in the center of the MDIChild form from which the dialog is called.
I have already looked at the following solution:
C# - Show Dialog box at center of its parent
However, unless there is an application-related discrepancy with my solution, this seems to have some fundamental issues.
It is suggested that the following would achieve this:
private void OpenForm(Form parent)
{
FormLoading frm = new FormLoading();
frm.Parent = parent;
frm.StartPosition = FormStartPosition.CenterParent;
frm.ShowDialog();
}
This however, has the following issue:
When I try and implement this, when stepping through the code, as soon as it hits the line to set the form Parent, the following exception occurs:
Top-level control cannot be added to a control.
N.B. Unless all Forms initialise with a TopLevel value of true
, this value doesn't seem to be set anywhere!
Okay, so; we'll set the TopLevel to false
to allow the Parent form to be set as the Parent of the dialog. Assuming I do this, when it hits the line to ShowDialog()
:
Form that is not a top-level form cannot be displayed as a modal dialog box. Remove the form from any parent form before calling showDialog.
And therein lies my quagmire; the dialog form seems to NEED to NOT be a TopLevel form in order to have a Parent but then simultaneously needs to be a TopLevel form so it can be shown as a dialog...
Final note, I do not think I should have to set the 'StartPosition' of the form that I want to have as the dialog as this is already set in the InitializeComponent()
part of the form; nevertheless, I've tried explicitly setting this in the function and it makes no difference.
Upvotes: 1
Views: 1458
Reputation: 4879
You can position the dialog form manually:
private void invokeDialogButton_Click(object sender, EventArgs e)
{
var dialogForm = new DialogForm();
dialogForm.StartPosition = FormStartPosition.Manual;
//Get the actual position of the MDI Parent form in screen coords
Point screenLocation = Parent.PointToScreen(Parent.Location);
//Adjust for position of the MDI Child form in screen coords
screenLocation.X += Location.X;
screenLocation.Y += Location.Y;
dialogForm.Location = new Point(screenLocation.X + (Width - dialogForm.Width) / 2,
screenLocation.Y + (Height - dialogForm.Height) / 2);
dialogForm.ShowDialog(this);
}
Take a look at this working example project on my Github page (Visual Studio 2015 Community Edition project).
Upvotes: 2