I have a WPF application and I need to know how to center the wain window programatically (not in XAML).
I need to be able to do this both at startup and in response
Rect workArea = System.Windows.SystemParameters.WorkArea;
this.Left = (workArea.Width - this.Width) / 2 + workArea.Left;
this.Top = (workArea.Height - this.Height) / 2 + workArea.Top;
This takes into account the taskbar size (by using System.Windows.SystemParameters.WorkArea
) and position (by adding workArea.Left
and workArea.Top
)
Go to property window of MainWindow.xaml
For Full Screen
Go to property window of MainWindow.xaml
I had to combine a few of these answers to cover all bases in my case:
workarea
rather than the screen bounds
to take into account the space for the taskbar. dpiScaling
variable is null if called on first load before the UI is displayed (explained here)//get the current monitor
Screen currentMonitor = Screen.FromHandle(new System.Windows.Interop.WindowInteropHelper(Application.Current.MainWindow).Handle);
//find out if our app is being scaled by the monitor
PresentationSource source = PresentationSource.FromVisual(Application.Current.MainWindow);
double dpiScaling = (source != null && source.CompositionTarget != null ? source.CompositionTarget.TransformFromDevice.M11 : 1);
//get the available area of the monitor
Rectangle workArea = currentMonitor.WorkingArea;
var workAreaWidth = (int)Math.Floor(workArea.Width*dpiScaling);
var workAreaHeight = (int)Math.Floor(workArea.Height*dpiScaling);
//move to the centre
Application.Current.MainWindow.Left = (((workAreaWidth - (myWindowWidth * dpiScaling)) / 2) + (workArea.Left * dpiScaling));
Application.Current.MainWindow.Top = (((workAreaHeight - (myWindowHeight * dpiScaling)) / 2) + (workArea.Top * dpiScaling));
where myWindowWidth
and myWindowHeight
are variables I used to manually set the size of the window earlier.
Isn't it just as simple to set
WindowStartupLocation="CenterScreen"
In the XAML definition for the window.
In the window element just add this attribute-value pair: WindowStartupLocation="CenterScreen"
private void CenterWindowOnScreen()
{
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);
}
You can use this method to set the window position to the center of your screen.