Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center a form after programmatically switching screens

Tags:

c#

winforms

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;
        }
    }
like image 604
P.Brian.Mackey Avatar asked Feb 18 '23 16:02

P.Brian.Mackey


2 Answers

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
                         );
    }
like image 80
P.Brian.Mackey Avatar answered Mar 05 '23 13:03

P.Brian.Mackey


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.

like image 37
corylulu Avatar answered Mar 05 '23 11:03

corylulu