Monday, December 13, 2010

Ensure visibility of your windows when switching computerscreens

I find when switching between different resoultions on my computer screen, or switching from a dual monitor setup to a single, the windows of my application can dissapear.

For applications that consists of several "gadget" windows where you save the individual position for each window, its very important to get a hold of the gadgets when they dissapear.

So I wrote a small helper function to recover those windows if they are stuck on another monitor that is not connected



public static void ensureWindowVisibility(Window pWindow)
{
var screens = System.Windows.Forms.Screen.AllScreens;
var currentWorkArea = System.Windows.SystemParameters.WorkArea;
var windowRect = new Rect(pWindow.Left, pWindow.Top, pWindow.Width, pWindow.Height);

if (screens.Count() == 1)
{
if (!currentWorkArea.IntersectsWith(windowRect))
{
pWindow.Left = 100;
pWindow.Top = 100;
}
}
}


Call this function the first time after you have initialized a window, or whenever you need to ensure the visibility. You could also change the end position which is now set to 100 to something more clever. For example finding out where the window was closest to the primary screen and put in just inside the bounds of the WorkArea.

Works with winforms applications aswell as WPF apps.

Hope this will help someone else too, for me it was absolutely essential for my app.

No comments :

Post a Comment