2017-08-11 116 views
0

如果MainWindow太靠近屏幕邊緣,相對定位可以去關閉屏幕打開New Window新窗口。防止從去離屏幕

我想有它檢測到它的關閉屏幕並自己重新定位接近邊緣,甚至重疊MainWindow。頂部,底部,左側和右側。

示例項目來源
https://www.dropbox.com/s/3r2guvssiakcz6f/WindowReposition.zip?dl=0

private Boolean IsWindowOpened = false; 


// Info Button 
// 
private void buttonInfo_Click(object sender, RoutedEventArgs e) 
{ 
    MainWindow mainwindow = this; 

    // Start Info Window 
    InfoWindow info = new InfoWindow(mainwindow); 

    // Only Allow 1 Window Instance 
    if (IsWindowOpened) return; 
    info.ContentRendered += delegate { IsWindowOpened = true; }; 
    info.Closed += delegate { IsWindowOpened = false; }; 

    // Position Relative to MainWindow 
    info.Left = mainwindow.Left - 270; 
    info.Top = mainwindow.Top + 0; 

    // Open Info Window 
    info.Show(); 
} 

1280x720的屏幕

MainWindow中心屏幕
InfoWindow -270px左,0像素頂級

Example 01


關閉屏幕

MainWindow頂部屏幕
InfoWindow -270px左的左派,0像素頂級

Example 02


重新定位在屏幕

MainWindow頂部屏幕
InfoWindow -160px左的左派,0像素頂級

Example 03

回答

1

爲了將對話到左

這樣做是簡單地使用Math.Max的快速正骯髒的方式(即最右邊的值)使用偏移量或0時,取較大。使用System.Windows.Forms.Screen使我們能夠適應多個顯示器。

private void btnInfoToLeft_Click(object sender, RoutedEventArgs e) 
    { 
     // Figure out which screen we're on 
     var allScreens = Screen.AllScreens.ToList(); 
     var thisScreen = allScreens.SingleOrDefault(s => this.Left >= s.WorkingArea.Left && this.Left < s.WorkingArea.Right); 

     // Place dialog to left of window, but not past screen border 
     InfoWindow info= new InfoWindow(); 
     info.Left = Math.Max(this.Left - info.Width - 10, thisScreen.WorkingArea.Left); 
     info.Top = Math.Max(this.Top - info.Height - 10, thisScreen.WorkingArea.Top); 
     info.Show(); 
    } 

請注意,我們使用對話框的Width - 這是ActualWidth將是0在屏幕上顯示之前。

爲了將對話框向右

同樣,我們需要弄清楚屏幕最右邊的邊界,並考慮在主窗口和對話框的寬度,並採取Math.Min值(即最左邊的值)。

private void btnInfoToRight_Click(object sender, RoutedEventArgs e) 
    { 
     // Figure out which screen we're on 
     var allScreens = Screen.AllScreens.ToList(); 
     var thisScreen = allScreens.SingleOrDefault(s => this.Left >= s.WorkingArea.Left && this.Left < s.WorkingArea.Right); 

     // Place dialog to right of window, but not past screen border 
     InfoWindow info = new InfoWindow(); 
     info.Left = Math.Min(this.Left + this.ActualWidth + 10, thisScreen.WorkingArea.Right - info.Width); 
     info.Top = Math.Min(this.Top + this.ActualHeight + 10, thisScreen.WorkingArea.Bottom - info.Height); 
     info.Show(); 
    } 

這一次,我們還是用對話的Width,但主窗口的ActualWidth,這將是寬度已經繪製後(也可能調整)。

在這些例子中,我還將對話框放在主窗口的上方/下方。您可以將對話框的頂部設置爲與主窗口的頂部相同,或者使用此示例作爲指導,將其對齊到底部等。

+0

這是行之有效的。我會進一步測試並回復你。 –

+0

它適用於重新定位在屏幕的左側,但不是右側。如果我從'InfoWindow'開始定位到'MainWindow'的右側。 'info.Left = Math.Max(mainwindow.Left + mainwindow.Width,0);' –

+1

現在更新我的答案來解釋左邊與右邊以及多個屏幕。 –