[c#] How do I center a window onscreen in C#?

I need a way to center the current window. So for example, if a user pushes a button, I want the window to center itself onscreen. 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?

This question is related to c# winforms screen center

The answer is


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


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


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.


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

A single line:

this.Location = new Point((Screen.PrimaryScreen.WorkingArea.Width - this.Width) / 2,
                          (Screen.PrimaryScreen.WorkingArea.Height - this.Height) / 2);

Use this:

this.CenterToScreen();  // This will take care of the current form

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

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


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;

  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.


In Windows Forms:

this.StartPosition = FormStartPosition.CenterScreen;

In WPF:

this.WindowStartupLocation = WindowStartupLocation.CenterScreen;

That's all you have to do...


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to winforms

How to set combobox default value? Get the cell value of a GridView row Getting the first and last day of a month, using a given DateTime object Check if a record exists in the database Delete a row in DataGridView Control in VB.NET How to make picturebox transparent? Set default format of datetimepicker as dd-MM-yyyy Changing datagridview cell color based on condition C# Inserting Data from a form into an access Database How to use ConfigurationManager

Examples related to screen

How to make flutter app responsive according to different screen size? Unable to capture screenshot. Prevented by security policy. Galaxy S6. Android 6.0 Clear screen in shell How to detect iPhone 5 (widescreen devices)? How to develop or migrate apps for iPhone 5 screen resolution? Android splash screen image sizes to fit all devices How to support different screen size in android Finish all previous activities Android screen size HDPI, LDPI, MDPI How to get the screen width and height in iOS?

Examples related to center

Center Plot title in ggplot2 How to make a <div> or <a href="#"> to align center How to center an unordered list? Bootstrap 3 modal vertical position center How to align title at center of ActionBar in default theme(Theme.Holo.Light) How to center absolute div horizontally using CSS? Resize to fit image in div, and center horizontally and vertically Center fixed div with dynamic width (CSS) RelativeLayout center vertical Center button under form in bootstrap