ComponentFactory.Krypton.Toolkit.VisualPopup.CalculateBelowPopupRect C# (CSharp) Method

CalculateBelowPopupRect() private method

private CalculateBelowPopupRect ( Rectangle parentScreenRect, Size popupSize ) : Rectangle
parentScreenRect System.Drawing.Rectangle
popupSize System.Drawing.Size
return System.Drawing.Rectangle
        private Rectangle CalculateBelowPopupRect(Rectangle parentScreenRect, Size popupSize)
        {
            // Get the screen that the parent rectangle is mostly within, this is the
            // screen we will attempt to place the entire popup within
            Screen screen = Screen.FromRectangle(parentScreenRect);

            Point popupLocation = new Point(parentScreenRect.X, parentScreenRect.Bottom);

            // Is there enough room below the parent for the entire popup height?
            if ((parentScreenRect.Bottom + popupSize.Height) <= screen.WorkingArea.Bottom)
            {
                // Place the popup below the parent
                popupLocation.Y = parentScreenRect.Bottom;
            }
            else
            {
                // Is there enough room above the parent for the enture popup height?
                if ((parentScreenRect.Top - popupSize.Height) >= screen.WorkingArea.Top)
                {
                    // Place the popup above the parent
                    popupLocation.Y = parentScreenRect.Top - popupSize.Height;
                }
                else
                {
                    // Cannot show entire popup above or below, find which has most space
                    int spareAbove = parentScreenRect.Top - screen.WorkingArea.Top;
                    int spareBelow = screen.WorkingArea.Bottom - parentScreenRect.Bottom;

                    // Place it in the area with the most space
                    if (spareAbove > spareBelow)
                        popupLocation.Y = screen.WorkingArea.Top;
                    else
                        popupLocation.Y = parentScreenRect.Bottom;
                }
            }

            // Prevent the popup from being off the left side of the screen
            if (popupLocation.X < screen.WorkingArea.Left)
                popupLocation.X = screen.WorkingArea.Left;

            // Preven the popup from being off the right size of the screen
            if ((popupLocation.X + popupSize.Width) > screen.WorkingArea.Right)
                popupLocation.X = screen.WorkingArea.Right - popupSize.Width;

            return new Rectangle(popupLocation, popupSize);
        }