Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open Window on the Same Monitor as MainWindow

Tags:

c#

window

wpf

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?

like image 564
CBreeze Avatar asked Dec 10 '22 13:12

CBreeze


1 Answers

You can use WindowStartupLocation:

From XAML:

WindowStartupLocation="CenterOwner"

From Code:

WindowStartupLocation = WindowStartupLocation.CenterOwner;
like image 71
Nawed Nabi Zada Avatar answered Dec 28 '22 12:12

Nawed Nabi Zada