是否有任何简单的方法可以防止 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/