Hi there.
This is an extension method to move a form onto the first non-primary screen.
It returns a
Nullable<bool> to tell whether the form have been moved, not moved or an error did occur.
namespace System.Windows.Forms
{
public static class FormExtensions
{
public static bool? SetScreenToFirstNonPrimary(this Form self)
{
try
{
var aScreens = Screen.AllScreens;
if (aScreens.Length <= 1)
return false;
var screenOld = Screen.FromControl(self);
foreach (var screen in aScreens)
{
if (screen.Primary || screen.Equals(screenOld))
continue;
var boundsScreen = screen.Bounds;
var oldState = self.WindowState;
if (oldState == FormWindowState.Maximized)
{
self.WindowState = FormWindowState.Normal;
self.StartPosition = FormStartPosition.Manual;
self.Location = boundsScreen.Location;
self.WindowState = FormWindowState.Maximized;
}
else
{
self.StartPosition = FormStartPosition.Manual;
var sizeGaps = boundsScreen.Size - self.Size;
var x = boundsScreen.Left + (sizeGaps.Width / 2);
var y = boundsScreen.Top + (sizeGaps.Height / 2);
self.Location = new Point(x, y);
}
return true;
}
return false;
}
catch (Exception ex)
{
return null;
}
}
}
}
You can call it from the form's constructor just after
InitializeComponent(); as
this.SetScreenToFirstNonPrimary();