在最小的WPF应用程序中,主窗口不会占用屏幕的右半部分

mnowg1ta  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(94)

我希望在启动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;
        }
    }
}

字符串
我在只用一台显示器的情况下进行了测试,结果如下:


的数据
当我将主窗口拖到屏幕中间时,它看起来也像窗口太宽:



我做错了什么?为什么应用程序不会占用我上一个显示器的右半部分?

w8biq8rn

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

<Window x:Class="WpfApp8.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:local="clr-namespace:WpfApp8"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        Title="MainWindowName"
        Loaded="Window_Loaded"
        SizeToContent="WidthAndHeight"
        mc:Ignorable="d">

    <Border x:Name="border" Background="LightBlue"/>
</Window>

字符串

代码背后

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        Screen[] allScreens = Screen.AllScreens;
        Screen lastScreen = allScreens[allScreens.Length - 1];

        var p = this.PointFromScreen(new Point(lastScreen.WorkingArea.X, lastScreen.WorkingArea.Y));
     
        border.Width = lastScreen.WorkingArea.Width / 2;
        border.Height = lastScreen.WorkingArea.Height;

        this.Top = 0;
        this.Left += (p.X + border.Width);
    }
}

相关问题