Given a Form
I want to center the form after switching screens. How can I accomplish the task?
internal static void SetFormToBiggestMonitor(Form form, bool center = true)
{
Screen biggestScreen = FindBiggestMonitor();//assume this works
form.Location = biggestScreen.Bounds.Location;
if (center)
{
form.StartPosition = FormStartPosition.CenterScreen;
}
}
One not so loopy way to accomplish the task...
private static Point CenterForm(Form form, Screen screen)
{
return new Point(
screen.Bounds.Location.X + (screen.WorkingArea.Width - form.Width) / 2,
screen.Bounds.Location.Y + (screen.WorkingArea.Height - form.Height) / 2
);
}
You need to account for the offset of the monitor before setting the position, but other than that, it should be fairly simple.
if (center)
{
form.Location = new Point
(
biggestScreen.WorkingArea.X + ((biggestScreen.WorkingArea.Width + form.Width)/2),
biggestScreen.WorkingArea.Y + ((biggestScreen.WorkingArea.Height + form.Height)/2)
);
}
But Form.CenterToScreen() should work just fine, but apparently Microsoft doesn't recommend using it? Not sure why.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With