我希望在启动WPF应用程序时,我的主应用程序窗口占据显示器的一半。如果我使用多个显示器,我希望窗口占据最后一个显示器。以下是我到目前为止的尝试:
using System;
using System.Linq;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Forms;
namespace Line
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Screen[] allScreens = Screen.AllScreens;
int noScreens = allScreens.Length;
double lastScreenWidth = allScreens[noScreens - 1].Bounds.Width;
double lastScreenHeight = allScreens[noScreens - 1].Bounds.Height;
double totalWidth = allScreens.Sum(s => s.Bounds.Width);
this.Left = totalWidth - lastScreenWidth / 2;
this.Width = lastScreenWidth / 2;
this.Top = 0;
this.Height = lastScreenHeight;
}
}
}
字符串
我在只用一台显示器的情况下进行了测试,结果如下:
的数据
当我将主窗口拖到屏幕中间时,它看起来也像窗口太宽:
的
我做错了什么?为什么应用程序不会占用我上一个显示器的右半部分?
1条答案
按热度按时间w8biq8rn1#
基于Window width and height not correct
不要依赖Window来计算内容的精确宽度和高度。Window具有不可见的操作系统级元素,这些元素会影响其总大小。
解决方法:从Window中删除Height和Width,并使用SizeToContent=“WidthAndHeight”。在根布局元素中设置精确的Width和Height。
基于how to position a window on multi-monitor
我已经成功地测试了这个解决方案
XAML
字符串
代码背后
型