Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StartPosition is set to CenterPosition but my form is not centered

I'm using Visual Studio 2012. My form, when it opens doesn't center to the screen. I have the form's StartPosition set to CenterScreen, but it always starts in the top left corner of my left monitor (I have 2 monitors).

Any ideas? Thanks

like image 231
bd528 Avatar asked Jan 12 '13 12:01

bd528


People also ask

How do I center a form in C#?

use the CenterToScreen() Method in the constructor of the form class.

How do you center a window on screen in Winforms development in c3?

To achieve this select the form you want to start in the center screen then go to properties and set the Startposition property to CenterScreen. It's not advisable to call this directly in your source code, “Do not call this directly from your code.


1 Answers

try this way!

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();


            //Method 1. center at initilization
            this.StartPosition = FormStartPosition.CenterScreen;

            //Method 2. The manual way
            this.StartPosition = FormStartPosition.Manual;
            this.Top = (Screen.PrimaryScreen.Bounds.Height - this.Height)/2;
            this.Left = (Screen.PrimaryScreen.Bounds.Width - this.Width)/2;

        }
    }
}

Two virtual members are called in constructor of the application.

namely

this.Text; 
this.MaximumSize;

do not call virtual member in constructor it may lead to abnormal behaviour

fixed code

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();



            this.Location = new System.Drawing.Point(100, 100);
            this.Name = "Form1";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            // to see if form is being centered, disable maximization
            //this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
            this.Load += new System.EventHandler(this.Form1_Load);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.Text = "Convertor";
            this.MaximumSize = new System.Drawing.Size(620, 420); 
        }
    }
}
like image 119
Parimal Raj Avatar answered Sep 18 '22 05:09

Parimal Raj