How do you center your main window in WPF?

Viewed 97882

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 to certain user events. It has to be dynamically calculated since the window size itself is dynamic.

What's the simplest way to do this? Under old Win32 code, I'd call the system metrics functions and work it all out. Is that still the way it's done or is there a simple CenterWindowOnScreen() function I can now call.

16 Answers

What I am using in my app, it is working for multiple displays and for different DPI setting

    //center a window on chosen screen
    public static void CenterWindow(Window w, System.Windows.Forms.Screen screen = null)
    {
        if(screen == null)
            screen = System.Windows.Forms.Screen.PrimaryScreen;

        int screenW = screen.Bounds.Width;
        int screenH = screen.Bounds.Height;
        int screenTop = screen.Bounds.Top;
        int screenLeft = screen.Bounds.Left;

        w.Left = PixelsToPoints((int)(screenLeft + (screenW - PointsToPixels(w.Width, "X")) / 2), "X");
        w.Top = PixelsToPoints((int)(screenTop + (screenH - PointsToPixels(w.Height, "Y")) / 2), "Y");
    }

    public static double PixelsToPoints(int pixels, string direction)
    {
        if (direction == "X")
        {
            return pixels * SystemParameters.WorkArea.Width / System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Width;
        }
        else
        {
            return pixels * SystemParameters.WorkArea.Height / System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height;
        }
    }

    public static double PointsToPixels(double wpfPoints, string direction)
    {
        if (direction == "X")
        {
            return wpfPoints * System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Width / SystemParameters.WorkArea.Width;
        }
        else
        {
            return wpfPoints * System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height / SystemParameters.WorkArea.Height;
        }
    }

Another short way to make mainwindow render at center of the computer screen using code behind.

this.Left = (System.Windows.SystemParameters.PrimaryScreenWidth - this.Width)/2;
this.Top = (System.Windows.SystemParameters.PrimaryScreenHeight - this.Height)/2;

Go to property window of MainWindow.xaml

  • find WindowStartupLocation property from Common category
  • select CenterScreen option from dropdown
  • Run the Application

For Full Screen

Go to property window of MainWindow.xaml

  • find WindowState property from Common category
  • select Maximized option from dropdown
  • Run the Application

Copy-paste good quality extension code.

Runtime:

using System;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Interop;

namespace Extensions
{
    /// <summary>
    /// <see cref="Window"/> extensions.
    /// </summary>
    public static class WindowExtensions
    {
        /// <summary>
        /// Moves the window to the center of the current screen, also considering dpi.
        /// </summary>
        /// <param name="window"></param>
        /// <exception cref="ArgumentNullException"></exception>
        public static void MoveToCenter(this Window window)
        {
            window = window ?? throw new ArgumentNullException(nameof(window));

            var helper = new WindowInteropHelper(window);
            var screen = Screen.FromHandle(helper.Handle);
            var area = screen.WorkingArea;

            var source = PresentationSource.FromVisual(window);
            var dpi = source?.CompositionTarget?.TransformFromDevice.M11 ?? 1.0;

            window.Left = dpi * area.Left + (dpi * area.Width - window.Width) / 2;
            window.Top = dpi * area.Top + (dpi * area.Height - window.Height) / 2;
        }
    }
}

Initial position:

<Window WindowStartupLocation="CenterScreen">
</Window>

Just use:

WindowStartupLocation="CenterScreen"

And in case you only want to center horizontally / vertically, You can override the OnActivated method and set left or top to zero like this:

    protected override void OnActivated(EventArgs e)
    {
        base.OnActivated(e);

        // to center Vertically
        Left = 0;
        // or user top = 0 to center Horizontally
        //top = 0;
    }

You will have to find this line : Title="MainWindow" Height="450" Width="800"

And you add this line to it : WindowStartupLocation="CenterScreen"

To become this : Title="MainWindow" Height="450" Width="800" WindowStartupLocation="CenterScreen">

Thank me Later ♥

Related