Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ensuring WPF Window is inside screen bounds

Tags:

wpf

I restore coordinates of Window on application startup. In good-old-Windows-Forms I used System.Windows.Forms.Screen collection. Is there anything similar in WPF world?

I did notice PrimaryScreen*, VirtualScreen* parameters in System.Windows.SystemParameters. However they left me hanging since it seems to be impossible to detect whether Window is inside bounds in cases when monitors are not same size.

like image 772
Josip Medved Avatar asked Oct 15 '22 07:10

Josip Medved


1 Answers

System.Windows.Forms.Screen works perfectly well within WPF, so I think the designers of WPF saw no advantage in replacing it with a WPF-specific version.

You'll have to do a coordinate transformation of course. Here's an easy class to do the conversion:

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;
  }
}

Example usage:

var converter = new ScreenBoundsConverter(this);

foreach(var screen in System.Windows.Forms.Screen.AllScreens)
{
  Rect bounds = converter.ConvertBounds(screen.Bounds);
  ...
}
like image 141
Ray Burns Avatar answered Nov 09 '22 23:11

Ray Burns