C# 使用 ShowDialog 显示对话框时如何控制对话框的位置?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/998675/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I control the location of a dialog when using ShowDialog to display it?
提问by ChrisF
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.
第二个来自系统托盘中 notifyIcon 上的上下文菜单,但它出现在屏幕的左上角。理想情况下,我希望它出现在主屏幕的中心,或者靠近系统托盘。
I've tried setting the
Location
, but this appears to be overridden whendialog.ShowDialog()
is called.I've tried using the
dialog.ShowDialog(IWin32Window)
overload, but that didn't seem to like me passingnull
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.
我试过设置
Location
,但这似乎在dialog.ShowDialog()
被调用时被覆盖。我试过使用
dialog.ShowDialog(IWin32Window)
重载,但这似乎不喜欢我null
作为窗口句柄传递。我已经尝试使用
dialog.Show()
,但是(这就是我可能出错的地方)设置位置似乎没有给出一致的结果。我什至尝试设置
dialog.Parent
属性 - 这当然引发了异常。
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.
感谢您的回答 - 正如我怀疑这很明显,但像往常一样,我让自己陷入了寻找错误路线的困境。更烦人的是,我也使用了设计师的这个属性。
采纳答案by heavyd
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.
您可以将Form.StartPosition
属性设置为FormStartPosition.Manual
,然后将Form.Location
属性设置为您想要的位置。当您调用ShowDialog
该表单时,该表单应显示在所需的位置。
MyForm frm = new MyForm();
frm.StartPosition = FormStartPosition.Manual;
frm.Location = new Point(10, 10);
frm.ShowDialog();
回答by micahtan
回答by Max Schmeling
Try the StartPosition property on the form.
尝试窗体上的 StartPosition 属性。