【问题标题】:CenterScreen Window on Un-Maximizing, on StateChanged取消最大化,StateChanged 上的 CenterScreen 窗口
【发布时间】:2014-01-20 13:49:28
【问题描述】:

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

有什么方法可以在未最大化时将窗口放置在屏幕中心

我希望尝试以下代码,但没有成功

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

【问题讨论】:

    标签: c# wpf


    【解决方案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;
    

    【讨论】:

    • 这是用于 winforms
    【解决方案2】:

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

    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();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-21
      • 1970-01-01
      • 2011-05-22
      • 1970-01-01
      • 2019-08-12
      • 2010-09-23
      • 2010-10-03
      • 1970-01-01
      相关资源
      最近更新 更多