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]; } }
source share