WPF : Keep the window maximized when switch main screen

1.3k views Asked by At

I want to keep the window always maximized, it works perfectly in a single screen. But when I use two screen(especially when the main screen change), I catch the resolution changed event and make it maximized,but it doesn't work. And I have tried to deal with the width and height of the window,it doesn't work either.

here is how I operate:

  1. Use a single small screen(1366 * 768),and the window is maximized.
  2. Connect another a big screen(1920 * 1080),which is set to be main screen(we have two screen now).Then the window will be displayed in the big one,and it is not maximized and stays in size of 1366*768 (Wierdly it get maximized sometimes,but not always).

here is my code:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        this.WindowState = WindowState.Maximized;
        SystemEvents.DisplaySettingsChanged += SystemEvents_DisplaySettingsChanged;
    }

    //this method catch the resolution changed event
    private void SystemEvent_DisplaySettingsChanged(object sender, EventsArgs e)
    {            
        WindowState = WindowState.Maximized;
    }
}

the window xaml code:

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        ResizeMode="CanMinimize"
        SizeToContent="Manual"
        WindowStartupLocation="CenterScreen" />
1

There are 1 answers

4
Xavier On BEST ANSWER

You mentioned that it works sometimes, but not always. Perhaps instead of immediately reacting to the settings change, you should queue your response with the dispatcher so that it runs after things have settled down.

In your SystemEvent_DisplaySettingsChanged method, try changing the code to this:

WindowState = WindowState.Normal;
Dispatcher.BeginInvoke(new Action(() => WindowState = WindowState.Maximized), DispatcherPriority.Background);

I have not tried to reproduce your issue, so I cannot say for sure if this will work. It seems worth a try though.

Edit: Setting the window state to normal first in case it thought it was already maximized.