Open Window on the Same Monitor as MainWindow

半世苍凉 提交于 2019-12-24 00:54:33

问题


I've seen many questions regarding similar issues, but I haven't found one quite specific enough to my question to find an answer yet.

I allow the user to move the MainWindow of my program around and, if they have one, onto another monitor. When they click to add something on the MainWindow, a new Window is created so they can fill in a form.

The problem is that this new Window will start on the primary screen of the OS instead of starting on the screen that the MainWindow is currently located on.

I had a look at this question; How to make a dialog(view) open up on the same monitor as the main window and saw that setting the owner to the MainWindow worked in this case. So I added

Owner = Application.Current.MainWindow;

into the Window_Loaded method the new Window. This does load the Window on the same screen as the MainWindow but then crashes, stating Cannot set Owner property after Dialog is shown.

Naturally I move the setting of the Owner property to before the new Window is shown, so it looks like this;

contractAddwindow.Owner = Application.Current.MainWindow; contractAddwindow.ShowDialog();

however this then has the same issue as before, the contractAddWindow starts on the primary screen.

So my question is, how do I force the new Window to load on the same monitor as the MainWindow instead of the primary screen?


回答1:


Try this methods:

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

And then, call it like this from the constructor of the Window you want to show on the same monitor as the MainWindow:

SetWindowScreen(this, GetWindowScreen(App.Current.MainWindow));



回答2:


You can use WindowStartupLocation:

From XAML:

WindowStartupLocation="CenterOwner"

From Code:

WindowStartupLocation = WindowStartupLocation.CenterOwner;


来源:https://stackoverflow.com/questions/42108110/open-window-on-the-same-monitor-as-mainwindow

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