Wpf - 以主桌面为中心

时间:2009-09-08 05:23:49

标签: .net wpf window wpf-positioning

我知道WPF有一个“CenterScreen”值,用于在桌面上居中一个窗口。 但是,在双显示器上,这不是很愉快。

如何以主显示器为中心?我是否需要经历检测主桌面,获取其几何图形等的歌曲和舞蹈,还是有更好的方法?

4 个答案:

答案 0 :(得分:6)

多个屏幕有点问题,它没有内置的,很好的方式来处理它们,但是通过一些数学和系统参数,你可以完成它。

如果您将窗口定位在主屏幕左上角的位置(0,0)。因此,为了使您的窗口显示在该屏幕的中心,请使用:

this.Left = (SystemParameters.PrimaryScreenWidth / 2) - (this.ActualWidth / 2);
this.Top = (SystemParameters.PrimaryScreenHeight / 2) - (this.ActualHeight / 2);

基本思想很简单,所以无需解释。

请注意,此代码适用于C#,但我确信VB具有类似的功能。

另请注意,您应该使用ActualWidth \ ActualHeight属性而不是Width \ Height属性,因为它可以保存NaN值。

祝你好运。

答案 1 :(得分:0)

我们遇到了同样的问题。不幸的是,在与TA和客户进行了很多讨论之后,我们决定在主要监视器上实现最大化(价值和时间)。

答案 2 :(得分:0)

使用SystemParameters.WorkArea。这为您提供了未被任务栏占用的主监视器的一部分,这可以为您提供更好的居中。

答案 3 :(得分:0)

这是我纯粹的WPF解决方案,它将一个Window集中在主监视器上,并在其周围留出空白边框(因为我不希望它最大化)。我的设置是左侧的方形显示器和右侧的宽屏幕。测试时将每个监视器设置为Windows中的主监视器。

在我找到解决方案之前,System.Windows.SystemParameters上有三个有用的属性可以提供不同的高度。给出的数字是我的1920x1080宽屏。

  • PrimaryScreenHeight - 1080.在Windows中设置的实际分辨率高度。
  • WorkArea.Height - 1040.实际分辨率高度减去开始栏
  • FullPrimaryScreenHeight - 1018.实际分辨率减去开始栏并减去窗口标题。

这是我的解决方案,我使用WorkArea.Height

    protected T SetWindowLocation<T>(T window) where T : Window
    {
        //This function will set a window to appear in the center of the user's primary monitor.
        //Size will be set dynamically based on resoulution but will not shrink below a certain size nor grow above a certain size

        //Desired size constraints.  Makes sure window isn't too small if the users monitor doesn't meet the minimum, but also not too big on large monitors
        //Min: 1024w x 768h
        //Max: 1400w x 900h

        const int absoluteMinWidth = 1024;
        const int absoluteMinHeight = 768;
        const int absoluteMaxWidth = 1400;
        const int absoluteMaxHeight = 900;

        var maxHeightForMonitor = System.Windows.SystemParameters.WorkArea.Height - 100;
        var maxWidthForMonitor = System.Windows.SystemParameters.WorkArea.Width - 100;

        var height = Math.Min(Math.Max(maxHeightForMonitor, absoluteMinHeight), absoluteMaxHeight);
        var width = Math.Min(Math.Max(maxWidthForMonitor, absoluteMinWidth), absoluteMaxWidth);

        window.Height = height;
        window.Width = width;
        window.Left = (System.Windows.SystemParameters.FullPrimaryScreenWidth - width) / 2;
        window.Top = (System.Windows.SystemParameters.FullPrimaryScreenHeight - height) / 2;
        window.WindowStartupLocation = WindowStartupLocation.Manual;

        return window;
    }