デュアルモニター設定でWPFウィンドウが複数のモニターにまたがるのを防ぐ簡単な方法はありますか? 「シンプル」とは、モニターのサイズを測定し、ウィンドウに幅を割り当てるコード ビハインドを記述しないことを意味します。
ウィンドウが現在のモニターで使用可能な部分のみを使用することをお勧めします(「現在」とは、現在フォーカスされているウィンドウを持つモニターを意味します)。ユーザーが両方のモニターをカバーするようにウィンドウのサイズを変更しても問題ありませんが、ウィンドウが開いた時点では単一のモニターにとどまります。
次に例を示します。
MainWindow.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);
}
}
}
「ウィンドウを開く」ボタンをクリックすると、新しいウィンドウが 2 つのモニターにまたがって開きます。Window2 が現在のモニター内に完全に収まっていればよいと思います。