Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / WinForms

Ensure visibility of your windows when switching computerscreens

4.60/5 (4 votes)
18 Nov 2010CPOL 19.6K  
When going from a multimonitor environment to a single monitor, windows get stuck on the other screens
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

C#
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)