Agile .NET

Ideas & Gotchas

CenterParent for non-modal forms

Posted by Vlad on October 16, 2007

As it turns out, if you want to show a non-modal form centered in the boundaries of its parent, in .NET 2.0, you’ll have to set its position manually.

Although the System.Windows.Forms.FormStartPosition.CenterParent works fine if you use form.ShowDialog(owner); (modal form), it doesn’t seem to make a difference when using form.Show (owner); for a non-modal form. I suspect a bug, because I didn’t find any mention of this behavior in help.

The solution:

form.StartPosition = FormStartPosition.Manual;

form.Location = new System.Drawing.Point(form.Owner.Location.X + (form.Owner.Width – form.Width) / 2, form.Owner.Location.Y + (form.Owner.Height – form.Height) / 2);

One Response to “CenterParent for non-modal forms”

  1. Vivek said

    The reason for this seems to stem from the Windows API.

    My understanding is that modal dialogs are implemented by the DialogBox native function and one of the possible styles is DS_CENTER which specifies its to be centered on owner window, however modeless dialogs are created with the CreateDialog family of functions and are displayed by the ShowWindow() function, so they behave like any old window and the DS_CENTER style makes no difference.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>