c# - 防止窗口跨越多个显示器

标签 c# wpf visual-studio-2010 .net-4.0

是否有任何简单的方法可以防止 WPF 窗口在双显示器设置中跨越多个显示器? “简单”是指不编写测量显示器大小并为窗口分配宽度的代码隐藏。

如果窗口仅使用当前监视器上可用的部分(其中“当前”表示具有当前焦点窗口的监视器),我会更喜欢。如果用户调整窗口大小使其覆盖两个显示器是可以的,但在窗口打开时它应该停留在一个显示器上。

这是一个例子:

主窗口.xaml:

<Window x:Class="MultiMonitorTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Button Content="Open Window" 
                Height="70" 
                HorizontalAlignment="Left" 
                Margin="165,147,0,0" 
                Name="button1" 
                VerticalAlignment="Top" 
                Width="179" 
                Click="button1_Click" />
    </Grid>
</Window>

MainWIndow.xaml.cs:

using System.Windows;

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

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            Window2 win = new Window2();
            win.ShowDialog();
        }
    }
}

Window2.xaml:

<Window x:Class="MultiMonitorTest.Window2"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window2" 
        SizeToContent="WidthAndHeight">
    <Grid>
        <TextBox x:Name="txt" 
                 Margin="10" 
                 Background="LightPink" 
                 AcceptsTab="True" 
                 AcceptsReturn="True" 
                 TextWrapping="Wrap"/>
    </Grid>
</Window>

Window2.xaml.cs:

using System.Windows;

namespace MultiMonitorTest
{
    public partial class Window2 : Window
    {
        public Window2()
        {
            InitializeComponent();

            txt.Text = new string('x', 1000);
        }
    }
}

单击“打开窗口”按钮时,新窗口会在两个显示器上打开。我希望 Window2 完全保持在当前监视器内。

最佳答案

好吧,您可以使用与第二个父窗口相同的宽度、高度(可能还有位置)。如果没有额外的代码,我不认为你真的可以强制窗口跨越两个监视器。但是,您可以使用有限的代码从一个而不是两个开始。

WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen; // in your Window Xaml

//and combine with

Rectangle workingArea = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea; // Reference System.Windows.Forms and set left, top, width and height accordingly.

这是我认为无需编写“大量”代码(这将使它居中于主屏幕的工作区域)就可以做到的最好结果。如果你真的想限制你的窗口跨越多个显示器当然是可能的,但需要一些工作。 一个好的起点是 WindowInteropHelper类。

关于c# - 防止窗口跨越多个显示器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13493900/

相关文章:

wpf - 从 UI 绑定(bind)到 View 模型属性需要从 TextBox 中移除焦点

c# - Marshal.StructureToPtr 使 Visual Studio 崩溃

c# - ADO.net BETWEEN 奇怪的行为

c# - 将自定义数据添加到 ADFS 身份验证

c# - 如何使用 WPF Canvas 以编程方式将图像从一点动画化到另一点?

Wpf控制内容大小?

visual-studio-2010 - 如何使用 MSBuild 更改嵌入式资源的默认命名空间?

c# - 在 C# 中类型安全绑定(bind)到 Oracle 存储过程?

C# 将字符串 [] 数组与通用对象列表进行比较

c# - TextBox 中的 ASP.net 简写