Search code examples
c#wpfwindow

Open Window on the Same Monitor as MainWindow


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?


Solution

  • @EDIT: Consider trying Nawed's answer (see below) before using this one. His is much simpler.

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