在StateChanged上取消最大化的CenterScreen窗口

时间:2014-01-20 13:49:28

标签: c# wpf

我有一个主窗口,负载设置为最大化。但是当我取消最大化窗口或双击窗口的标题栏时。它随机地放在屏幕上的任何地方,但不是ScreenCenter

有什么办法可以在未最大化的时候在ScreenCenter放置窗口

我希望以下代码尝试,但没有效果

private void InfoWindow_OnStateChanged(object sender, EventArgs e)
{
    var window = sender as Window;
    if(window != null && window.WindowState == WindowState.Normal)
        WindowStartupLocation = WindowStartupLocation.CenterScreen;
}

2 个答案:

答案 0 :(得分:1)

由于WPF不提供此工作的直接方法,您需要执行以下操作:

var workingArea = System.Windows.SystemParameters.WorkArea;
this.Left = (workingArea.Width - this.Width) / 2 + workingArea.Left;
this.Top = (workingArea.Height - this.Height) / 2 + workingArea.Top;

答案 1 :(得分:1)

您可以使用此方法将窗口位置设置为屏幕中心。

private void CenterWindowOnScreen()
    {
        double screenWidth = System.Windows.SystemParameters.PrimaryScreenWidth;
        double screenHeight = System.Windows.SystemParameters.PrimaryScreenHeight;
        double windowWidth = this.Width;
        double windowHeight = this.Height;
        this.Left = (screenWidth / 2) - (windowWidth / 2);
        this.Top = (screenHeight / 2) - (windowHeight / 2);
    }

private void InfoWindow_OnStateChanged(object sender, EventArgs e)
{
    var window = sender as Window;
    if(window != null && window.WindowState == WindowState.Normal)
      CenterWindowOnScreen();
}
相关问题