WPF maximize main window with center for application

1k views Asked by At

i have WPF application and i want to maximize main window. i tried the below code but the issue is that the window is maximized but not centered. i want the window to be maximized as i maximize window with mouse click. my code is:

 mainWindow.Height = SystemParameters.MaximizedPrimaryScreenHeight;
 mainWindow.Width = SystemParameters.MaximizedPrimaryScreenWidth;
2

There are 2 answers

0
Clemens On BEST ANSWER

Set the WindowState property instead of Width and Height:

mainWindow.WindowState = WindowState.Maximized;
0
Olaru Mircea On

This should work:

window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
window.WindowState = WindowState.Maximized;

but if not, try this approach:

private void CenterWindow()
{
    double screenWidth = System.Windows.SystemParameters.PrimaryScreenWidth;
    double screenHeight = System.Windows.SystemParameters.PrimaryScreenHeight;
    double windowWidth = this.Width;
    double windowHeight = this.Height;
    this.Left = (screenWidth / 2) - (windowWidth / 2);
    this.Top = (screenHeight / 2) - (windowHeight / 2);
}

and then maximize it:

 window.WindowState = WindowState.Maximized;

Further more, when working with 2 ore more displays you may want to create a Window and show it on the display on which the cursor is active. In order to accomplish this you will need the following trick:

 Window window = new Window();
 window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
 window.SourceInitialized += (s, a) => window.WindowState = WindowState.Maximized;
 window.Show();