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

喜欢而已 提交于 2019-12-28 05:56:33

问题


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.


回答1:


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();



回答2:


I assume you're using a Form, in which case you can use Form.StartPosition enumeration. You can find more about it here and the enumeration behavior here.




回答3:


Try the StartPosition property on the form.



来源:https://stackoverflow.com/questions/998675/how-can-i-control-the-location-of-a-dialog-when-using-showdialog-to-display-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!