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);
Rectangle workingArea = screen.WorkingArea;
workingArea.Width -= BOTTOMRIGHT_GAP;
workingArea.Height -= BOTTOMRIGHT_GAP;
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) <= 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) >= 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 - workingArea.Top;
int spareBelow = workingArea.Bottom - parentScreenRect.Bottom;
// Place it in the area with the most space
if (spareAbove > spareBelow)
popupLocation.Y = workingArea.Top;
else
popupLocation.Y = parentScreenRect.Bottom;
}
}
// Prevent the popup from being off the left side of the screen
if (popupLocation.X < workingArea.Left)
popupLocation.X = workingArea.Left;
// Preven the popup from being off the right size of the screen
if ((popupLocation.X + popupSize.Width) > workingArea.Right)
popupLocation.X = workingArea.Right - popupSize.Width;
return new Rectangle(popupLocation, popupSize);
}