防止从去离屏幕

问题描述:

如果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

为了将对话到左

这样做是简单地使用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

现在更新我的答案来解释左边与右边以及多个屏幕。 –

没有关于这类问题没有捷径可走。你必须弄清楚你正在使用的屏幕尺寸,然后手动调整信息窗口的位置。

看看这个*的帖子:How to get the size of the current screen in WPF?