WPF - DPI Aware Centering of a Window


Posted by Blake on 9/9/2021

WPF: Center Window on Screen (DPI Aware)

The following code should assist you with centering a WPF window in a way that is DPI aware allowing to work both on high and low resolution screens.

C#

// Get the current monitor the main window is on.
var currentMonitor = Screen.FromHandle(new System.Windows.Interop.WindowInteropHelper(Application.Current.MainWindow).Handle);

// Find out if our WPF app is being scaled by the monitor
var 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 the window to the center by setting the top and left coordinates.
Application.Current.MainWindow.Left = (((workAreaWidth - (myWindowWidth * dpiScaling)) / 2) + (workArea.Left * dpiScaling));
Application.Current.MainWindow.Top = (((workAreaHeight - (myWindowHeight * dpiScaling)) / 2) + (workArea.Top * dpiScaling));