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

问题描述 投票:0回答:1

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

我仅使用一台显示器进行了测试,结果如下:

当我将主窗口拖到屏幕中间时,窗口看起来也太宽了:

我在这里做错了什么?为什么该应用程序不占用我最后一个显示器的右半部分?

c# wpf wpf-controls
1个回答
0
投票

基于 窗口宽度和高度不正确

不要依赖窗口来计算内容的精确宽度和高度。窗口具有不可见的操作系统级元素,这些元素会影响其总大小。

解决方案:从窗口中删除高度和宽度并使用 SizeToContent="WidthAndHeight" 改为。设置精确的宽度和 根布局元素的高度。

并基于 如何在多显示器上定位窗口

我已经成功测试了这个解决方案

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);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.