2

デュアルモニター設定で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 が現在のモニター内に完全に収まっていればよいと思います。

4

1 に答える 1

0

2番目のウィンドウの親ウィンドウと同じ幅、高さ(およびおそらく位置)を使用できます。追加のコードがなければ、ウィンドウを2つのモニターにまたがるように強制することはできないと思います。ただし、限られたコードで、2つではなく1つで開始できます。

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クラスが適しています。

于 2012-12-01T13:53:17.040 に答える