152

I need a way to center the current window on the screen.

So for example, if a user pushes a button, I want the window to center itself on the screen.

I know you can use the startposition property, but I cannot figure out a way to use that other than when the application first starts up.

So how do I center the form on the screen?

Ola Ström
  • 4,136
  • 5
  • 22
  • 41
Sean
  • 8,401
  • 15
  • 40
  • 48

13 Answers13

228

Use Form.CenterToScreen() method.

emcor
  • 284
  • 4
  • 15
dzendras
  • 4,721
  • 1
  • 25
  • 20
  • 8
    On system with two monitors the form will be centered on one that currently have the cursor. So, the form may suddenly jump to other monitor. See the post [here](http://stackoverflow.com/questions/6837463/how-come-centertoscreen-method-centers-the-form-on-the-screen-where-the-cursor-i/6837499#6837499). – Artemix Feb 07 '13 at 10:28
  • 8
    The documentation you reference does say "Do not call this directly from your code." though it doesn't say why. – Stephen Turner Jun 09 '14 at 13:11
  • 5
    The documentation does say use the form's StartPosition property to center it. It worked for me. – John Kroetch Aug 19 '14 at 16:29
  • 1
    This works, I just had to instantiate it: this.CenterToScreen(); – Laki Politis Jul 21 '17 at 07:06
  • 1
    I would also like to know why the documentation says "Do not call this directly from your code." – Pete May 13 '19 at 10:23
  • 1
    This won't work if placed after this line of code: ```this.Location = Screen.AllScreens[0].WorkingArea.Location;``` – TK-421 Jul 31 '19 at 13:24
189
  1. Using the Property window

    Select form → go to property window → select "start position" → select whatever the place you want.

    "

  2. Programmatically

    Form form1 = new Form(); form1.StartPosition = FormStartPosition.CenterScreen; form1.ShowDialog();

    Note: Do not directly call Form.CenterToScreen() from your code. Read here.

Nayana Adassuriya
  • 23,596
  • 30
  • 104
  • 147
46

A single line:

this.Location = new Point((Screen.PrimaryScreen.WorkingArea.Width - this.Width) / 2,
                          (Screen.PrimaryScreen.WorkingArea.Height - this.Height) / 2);
Furqan Safdar
  • 16,260
  • 13
  • 59
  • 93
Sith2021
  • 3,245
  • 30
  • 22
  • This shows a good way of getting the center of *either* the 'x' or 'y' manually. I needed 'center screen', but only for the 'y' coordinate. – atconway Nov 20 '12 at 19:30
  • 12
    Why Screen.PrimaryScreen? What if the form is on 'SecondaryScreen'? You should use `Screen screen = Screen.FromControl(this);` here. – Artemix Feb 07 '13 at 10:38
  • I use this primitive techniques simply because it works on **.NET Compact Framework 3.5**, and this also explain why I don't use `Screen.FromControl(this)` but keep it to `PrimaryScreen`. (I'm developing an application under hardware constraint) :-) – Yeo Oct 27 '15 at 14:45
  • That method is ok if you are only using one screen. However, if you have multiple monitors and click a shortcut over here on the left monitor, you don't really want it opening on the right one. The StartPosition property handles that for you. – Trevor_G Feb 16 '17 at 13:41
  • This is not [per monitor DPI aware]. – vt. May 15 '17 at 18:31
37

In Windows Forms:

this.StartPosition = FormStartPosition.CenterScreen;

In WPF:

this.WindowStartupLocation = WindowStartupLocation.CenterScreen;

That's all you have to do...

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Saimon
  • 379
  • 3
  • 2
  • Best answer for the situation. I did not want to set the position but to have it reset once I came back to the form. This is perfect. – KangarooRIOT Apr 25 '17 at 00:29
25

If you want to center your windows during runtime use the code below, copy it into your application:

protected void ReallyCenterToScreen()
{
  Screen screen = Screen.FromControl(this);

  Rectangle workingArea = screen.WorkingArea;
  this.Location = new Point() {
    X = Math.Max(workingArea.X, workingArea.X + (workingArea.Width - this.Width) / 2),
    Y = Math.Max(workingArea.Y, workingArea.Y + (workingArea.Height - this.Height) / 2)};
}

And finally call the method above to get it working:

ReallyCenterToScreen();
Bruno Bieri
  • 9,724
  • 11
  • 63
  • 92
Sarsur.A
  • 295
  • 1
  • 4
  • 7
  • This works best since it will work even if you run ```this.Location = Screen.AllScreens[0].WorkingArea.Location;``` before it, other answers do not work in such case of moving app when using multiple screens. – TK-421 Jul 31 '19 at 13:24
  • This worked on my machine with 3 monitors. – ThePeter Jun 11 '21 at 19:43
9

 Centering a form in runtime

1.Set following property of Form:
   -> StartPosition : CenterScreen
   -> WindowState: Normal

This will center the form at runtime but if form size is bigger then expected, do second step.

2. Add Custom Size after InitializeComponent();

public Form1()
{
    InitializeComponent();
    this.Size = new Size(800, 600);
}
Faiz Siddiqui
  • 2,623
  • 1
  • 15
  • 15
6

Use this:

this.CenterToScreen();  // This will take care of the current form
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
UJS
  • 853
  • 1
  • 10
  • 16
  • 1
    -100. "**Do not** call CenterToScreen() directly from your code. Instead, set the StartPosition property to CenterScreen." http://msdn.microsoft.com/en-us/library/system.windows.forms.form.centertoscreen.aspx – A876 Jul 28 '17 at 19:15
6
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace centrewindow
{
    public partial class Form1 : Form
    {
        public struct RECT
        {
            public int Left;        // x position of upper-left corner
            public int Top;         // y position of upper-left corner
            public int Right;       // x position of lower-right corner
            public int Bottom;      // y position of lower-right corner
        }

        [DllImport("user32.dll")]
        public static extern IntPtr SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int Y, int cx, int cy, int wFlags);

        [DllImport("user32.dll")]
        public static extern bool GetWindowRect(HandleRef hwnd, out RECT lpRect);

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            CentreWindow(Handle, GetMonitorDimensions());
        }

        private void CentreWindow(IntPtr handle, Size monitorDimensions)
        {
            RECT rect;
            GetWindowRect(new HandleRef(this, handle), out rect);

            var x1Pos = monitorDimensions.Width/2 - (rect.Right - rect.Left)/2;
            var x2Pos = rect.Right - rect.Left;
            var y1Pos = monitorDimensions.Height/2 - (rect.Bottom - rect.Top)/2;
            var y2Pos = rect.Bottom - rect.Top;

            SetWindowPos(handle, 0, x1Pos, y1Pos, x2Pos, y2Pos, 0);
        }

        private Size GetMonitorDimensions()
        {
            return SystemInformation.PrimaryMonitorSize;
        }
    }
}

Centers any window you can get the handle of

Rob
  • 26,989
  • 16
  • 82
  • 98
4

Might not be completely relevant to the question. But maybe can help someone.

Center Screen non of the above work for me. Reason was I was adding controls dynamically to the form. Technically when it centered it was correct , based on the form before adding the controls.

So here was my solution. ( Should work with both scenarios )

int x = Screen.PrimaryScreen.Bounds.Width - this.PreferredSize.Width;
int y = Screen.PrimaryScreen.Bounds.Height - this.PreferredSize.Height;

this.Location = new Point(x / 2, y / 2);

So you will notice that I am using "PreferredSize" instead of just using Height / Width. The preferred size will hold the value of the form after adding the controls. Where Height / Width won't.

Hope this helps someone .

Cheers

De Wet Ellis
  • 720
  • 6
  • 7
2

Use Location property of the form. Set it to the desired top left point

desired x = (desktop_width - form_witdh)/2

desired y = (desktop_height - from_height)/2

Sarwar Erfan
  • 18,034
  • 5
  • 46
  • 57
2

Working sample

private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
    AccountAddForm f = new AccountAddForm();
    f.StartPosition = FormStartPosition.CenterScreen;
    f.Show();            
}
Vy Do
  • 46,709
  • 59
  • 215
  • 313
1

You can use the Screen.PrimaryScreen.Bounds to retrieve the size of the primary monitor (or inspect the Screen object to retrieve all monitors). Use those with MyForms.Bounds to figure out where to place your form.

C.Evenhuis
  • 25,996
  • 2
  • 58
  • 72
0

In case of multi monitor and If you prefer to center on correct monitor/screen then you might like to try these lines:

// Save values for future(for example, to center a form on next launch)
int screen_x = Screen.FromControl(Form).WorkingArea.X;
int screen_y = Screen.FromControl(Form).WorkingArea.Y;

// Move it and center using correct screen/monitor
Form.Left = screen_x;
Form.Top = screen_y;
Form.Left += (Screen.FromControl(Form).WorkingArea.Width - Form.Width) / 2;
Form.Top += (Screen.FromControl(Form).WorkingArea.Height - Form.Height) / 2;
Artfaith
  • 1,183
  • 4
  • 19
  • 29