How to force launch WPF launch window to a specific screen?

I have a WPF application that will display projector information through a highlighted window. I would like to configure which screen will be used to display the projector and what will be used for the main application window.

This code will generate the projector output on the specified screen:

var screen = GetProjectorScreen(); _projectorWindow = new ProjectorWindow(); _projectorWindow.Left = screen.WorkingArea.Left; _projectorWindow.Top = screen.WorkingArea.Top; _projectorWindow.Owner = _parentWindow; _projectorWindow.Show(); public static Screen GetProjectorScreen() { var screens = Screen.AllScreens; if (screens.Length > 1 && Settings.Default.DisplayScreen < screens.Length) { return screens[Settings.Default.DisplayScreen]; } return screens[0]; } 

I tried to do the same trick with the launch form, but so far without success. I tried setting the Top and Left properties in the MainWindow constructor, but that didn't work.

The launch window is launched from App.xaml.cs by setting StartupUri:

 StartupUri = new Uri("Windows/MainWindow.xaml", UriKind.Relative); 

Is there any other way to run the launch form? I tried to just call the constructor, but it crashes because some resources are no longer loading.

+4
source share
1 answer

I have earned. Before setting the window location, you must set WindowState to Normal. And the setting will not work at all until a window is created, that is, after calling the constructor. Therefore, I call an explicit parameter in the Windows_Loaded event. This may cause flickering if you need to move the window, but it is acceptable to me.

The SetScreen method should also be called after the screen settings have been manually changed by the user.

 private void SetScreen() { var mainScreen = ScreenHandler.GetMainScreen(); var currentScreen = ScreenHandler.GetCurrentScreen(this); if (mainScreen.DeviceName != currentScreen.DeviceName) { this.WindowState = WindowState.Normal; this.Left = mainScreen.WorkingArea.Left; this.Top = mainScreen.WorkingArea.Top; this.Width = mainScreen.WorkingArea.Width; this.Height = mainScreen.WorkingArea.Height; this.WindowState = WindowState.Maximized; } } 

ScreenHandler backup utility is very simple:

 public static class ScreenHandler { public static Screen GetMainScreen() { return GetScreen(Settings.Default.MainScreenId); } public static Screen GetProjectorScreen() { return GetScreen(Settings.Default.ProjectorScreenId); } public static Screen GetCurrentScreen(Window window) { var parentArea = new Rectangle((int)window.Left, (int)window.Top, (int)window.Width, (int)window.Height); return Screen.FromRectangle(parentArea); } private static Screen GetScreen(int requestedScreen) { var screens = Screen.AllScreens; var mainScreen = 0; if (screens.Length > 1 && mainScreen < screens.Length) { return screens[requestedScreen]; } return screens[0]; } } 
+10
source

Source: https://habr.com/ru/post/1444076/


All Articles