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