Skip to content

Instantly share code, notes, and snippets.

@Romiko
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Romiko/3b0ed989b80c9d8a9128 to your computer and use it in GitHub Desktop.
Save Romiko/3b0ed989b80c9d8a9128 to your computer and use it in GitHub Desktop.
Windows Form - Keep bounded within the viewable part of a multiple screen/monitor configuration
private void DockFormIfOutOfViewableArea()
{
var widthTolerance = Location.X + (Width / 2);
var heightTolerance = Location.Y + (Height / 2);
Screen.AllScreens.OrderBy(r => r.WorkingArea.X).ForEach(screen =>
{
if (!IsOnThisScreen(screen)) return;
if (heightTolerance > screen.WorkingArea.Height)
Location = new Point(screen.WorkingArea.X, screen.Bounds.Height - Height + screen.Bounds.Y);
if (Location.Y < screen.WorkingArea.Y )
Location = new Point(screen.WorkingArea.X, screen.WorkingArea.Y);
});
if (widthTolerance > SystemInformation.VirtualScreen.Right)
{
var closestScreen = Screen.AllScreens.OrderBy(r => r.WorkingArea.X).Last();
Location = new Point(closestScreen.Bounds.Right - Width, closestScreen.Bounds.Height - Height + closestScreen.Bounds.Y);
}
if (widthTolerance < SystemInformation.VirtualScreen.Left)
{
var closestScreen = Screen.AllScreens.OrderBy(r => r.WorkingArea.X).First();
Location = new Point(closestScreen.Bounds.Left, closestScreen.Bounds.Height - Height + closestScreen.Bounds.Y);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment