SamKr
2/13/2017 - 9:22 PM

Center window on primary screen (WPF)

Center window on primary screen (WPF)

public static void PostitionWindowOnScreen(Window window)
{
  // Place in 'loaded' function
  
  try
  {
      var mainScreenBounds = Screen.PrimaryScreen.WorkingArea;
      double dpiX = 1, dpiY = 1;
      var ps = PresentationSource.FromVisual(window);
      if (ps != null)
      {
          dpiX = ps.CompositionTarget.TransformToDevice.M11;
          dpiY = ps.CompositionTarget.TransformToDevice.M22;
      }
      var newWidth = window.Width * dpiX;
      var newHeight = window.Height * dpiY;

      window.Left = (mainScreenBounds.X + (mainScreenBounds.Width - newWidth) / 2) / dpiX;
      window.Top = (mainScreenBounds.Y + (mainScreenBounds.Height - newHeight) / 2) / dpiX;
  }
  catch (Exception)
  {
      window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
  }
}