我已经看到很多关于类似问题的问题,但我还没有找到一个非常具体到我的问题来找到答案.
我允许用户将我的程序的MainWindow移动到另一个监视器上(如果有的话).当他们单击以在MainWindow上添加内容时,会创建一个新窗口,以便他们可以填写表单.
问题是这个新窗口将在操作系统的主屏幕上启动,而不是在MainWindow当前所在的屏幕上启动.
我看了一下这个问题; 如何在与主窗口相同的监视器上打开一个对话框(视图),并看到在这种情况下将所有者设置为MainWindow.所以我补充道
Owner = Application.Current.MainWindow;
进入Window_Loaded方法的新窗口.这确实将Window加载到与MainWindow相同的屏幕上,但随后崩溃,说明Cannot set Owner property after Dialog is shown.
当然,我将所有者属性的设置移动到显示新窗口之前,所以它看起来像这样;
contractAddwindow.Owner = Application.Current.MainWindow;
contractAddwindow.ShowDialog();
然而,这与以前有相同的问题,在contractAddWindow主屏幕上开始.
所以我的问题是,如何强制新窗口加载到与MainWindow相同的监视器而不是主屏幕?
@编辑:在使用这个答案之前,请考虑尝试 Nawed 的答案(见下文)。他的要简单得多。
试试这个方法:
using System.Windows;
using System.Windows.Forms; // Reference System.Drawing
[...]
public void SetWindowScreen(Window window, Screen screen)
{
if (screen != null)
{
if (!window.IsLoaded)
{
window.WindowStartupLocation = WindowStartupLocation.Manual;
}
var workingArea = screen.WorkingArea;
window.Left = workingArea.Left;
window.Top = workingArea.Top;
}
}
public Screen GetWindowScreen(Window window)
{
return Screen.FromHandle(new System.Windows.Interop.WindowInteropHelper(window).Handle);
}
Run Code Online (Sandbox Code Playgroud)
然后,从Window要在与 相同的监视器上显示的的构造函数中像这样调用它MainWindow:
SetWindowScreen(this, GetWindowScreen(App.Current.MainWindow));
Run Code Online (Sandbox Code Playgroud)
你可以使用WindowStartupLocation:
来自XAML:
WindowStartupLocation="CenterOwner"
Run Code Online (Sandbox Code Playgroud)
来自代码:
WindowStartupLocation = WindowStartupLocation.CenterOwner;
Run Code Online (Sandbox Code Playgroud)