2010-04-13 88 views
5

我在應用程序啓動時恢復Window的座標。在老式的Windows窗體中,我使用了System.Windows.Forms.Screen集合。 WPF世界中有沒有類似的東西?確保WPF窗口在屏幕邊界內

我注意到,VirtualScreen*參數System.Windows.SystemParameters。然而,他們讓我掛了,因爲在顯示器尺寸不一樣的情況下,似乎無法檢測到Window是否在界限內。

回答

4

System.Windows.Forms.Screen在WPF中工作得很好,所以我認爲WPF的設計者沒有把WPF替換爲WPF的優勢。

當然你必須做一個座標轉換。下面是一個簡單的類來進行轉換:

public class ScreenBoundsConverter 
{ 
    private Matrix _transform; 

    public ScreenBoundsConverter(Visual visual) 
    { 
    _transform = 
     PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; 
    } 

    public Rect ConvertBounds(Rectangle bounds) 
    { 
    var result = new Rect(bounds.X, bounds.Y, bounds.Width, bounds.Height); 
    result.Transform(_transform); 
    return result; 
    } 
} 

用法示例:

var converter = new ScreenBoundsConverter { Visual = this }; 

foreach(var screen in System.Windows.Forms.Screen.AllScreens) 
{ 
    Rect bounds = converter.ConvertBounds(screen.Bounds); 
    ... 
}