WPF - DPI Aware Centering of a Window

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.


// 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));

Leave a comment

Please note that we won't show your email to others, or use it for sending unwanted emails. We will only use it to render your Gravatar image and to validate you as a real person.