P.Brian.Mackey
P.Brian.Mackey

Reputation: 44295

How to center a form after programmatically switching screens

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;
        }
    }

Upvotes: 4

Views: 1716

Answers (3)

Ghasem
Ghasem

Reputation: 15623

What if instead of all these calculations, you just use Form.CenterToScreen

this.CenterToScreen();

Upvotes: 0

P.Brian.Mackey
P.Brian.Mackey

Reputation: 44295

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
                         );
    }

Upvotes: 7

corylulu
corylulu

Reputation: 3499

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.

Upvotes: 1

Related Questions