How can I control the location of a dialog when using ShowDialog to display it?

ChrisF picture ChrisF · Jun 16, 2009 · Viewed 38.4k times · Source

This is a very trivial problem but I can't seem to find a way of solving it. It's annoying me because I feel I should know the answer to this, but I'm either searching for the wrong terms or looking at the wrong methods and properties.

I have a configuration dialog that's called from two places.

The first is from the button on the form which is working correctly - as you'd expect.

The second is from a context menu on the notifyIcon in the system tray, but here it appears at the top left of the screen. Ideally I'd like it to appear centered on the primary screen, or perhaps close to the system tray.

  • I've tried setting the Location, but this appears to be overridden when dialog.ShowDialog() is called.

  • I've tried using the dialog.ShowDialog(IWin32Window) overload, but that didn't seem to like me passing null as the window handle.

  • I've tried using dialog.Show() instead, but (and this is where I could be going wrong) setting the location doesn't appear to give consistent results.

  • I've even tried setting the dialog.Parent property - which of course raised an exception.

I just know that I'm going to realise that the answer is obvious when I (hopefully) see some answers, but at the moment I'm completely stuck.

Thanks for the answers - as I suspected it was obvious, but as usual I'd got myself stuck into looking down the wrong route. The even more annoying thing is that I've used this property from the designer too.

Answer

heavyd picture heavyd · Jun 16, 2009

You can set the Form.StartPosition property to FormStartPosition.Manual and then set the Form.Location property to your desired location. When you call ShowDialog the form should show up in the desired location.

MyForm frm = new MyForm();
frm.StartPosition = FormStartPosition.Manual;
frm.Location = new Point(10, 10);
frm.ShowDialog();