Search code examples
c#windowsmultiple-monitorsvirtual-screen

How can I check that a window is fully visible on the user's screen?


Is there a way to check that a WinForm is fully visible on the screen (eg is not out of bounds of the screen?)

I've tried using SystemInformation.VirtualScreen for this, which works great as long as the virtual screen is a rectangle, but as soon as it's not (eg 3 screens in a L shape), SystemInformation.VirtualScreen returns the smallest rectangle containing all the visible pixels (so a window on the upper right corner of the L won't be visible although it's in the virtual screen)


The reason I'm trying to achieve this is that I'd like my program to open its child windows in the last location they were on, but I don't want those window to be out of view if the user changes is setup (eg unplugs the extra screen from his laptop)


Solution

  • Here's how I eventually did it :

    bool isPointVisibleOnAScreen(Point p)
    {
        foreach (Screen s in Screen.AllScreens)
        {
            if (p.X < s.Bounds.Right && p.X > s.Bounds.Left && p.Y > s.Bounds.Top && p.Y < s.Bounds.Bottom)
                return true;
        }
        return false;
    }
    
    bool isFormFullyVisible(Form f)
    {
        return isPointVisibleOnAScreen(new Point(f.Left, f.Top)) && isPointVisibleOnAScreen(new Point(f.Right, f.Top)) && isPointVisibleOnAScreen(new Point(f.Left, f.Bottom)) && isPointVisibleOnAScreen(new Point(f.Right, f.Bottom));
     }
    

    There might be some false positive if the user has a "hole" in his display setup (see example below) but I don't think any of my users will ever be in such a situation :)

       [1]
    [2][X][3]