How do you center your main window in WPF?

前端 未结 13 1381
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-28 07:07

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

13条回答
  •  一个人的身影
    2020-11-28 07:27

    In case you need to draw a window in an multiple screen environment. I've made a static class where the following method can be re-used:

    public static void PostitionWindowOnScreen(Window window, double horizontalShift = 0, double verticalShift = 0)
    {
        Screen screen = Screen.FromHandle(new System.Windows.Interop.WindowInteropHelper(window).Handle);
        window.Left = screen.Bounds.X + ((screen.Bounds.Width - window.ActualWidth) / 2) + horizontalShift;
        window.Top = screen.Bounds.Y + ((screen.Bounds.Height - window.ActualHeight) / 2) + verticalShift;        
    }
    

    In the constructor of the Window now just call the method:

    this.Loaded += (s, a) => Globals.PostitionWindowOnScreen(this, 0, 0)
    

提交回复
热议问题