StartPosition设置为CenterPosition,但我的窗体没有居中

本文关键字:窗体 我的 设置 CenterPosition StartPosition | 更新日期: 2023-09-27 17:52:42

我使用的是Visual Studio 2012。我的表单打开的时候,并不是在屏幕的中心。我将表单的StartPosition设置为CenterScreen,但它总是在我的左监视器的左上角开始(我有2个监视器)。

任何想法?由于

StartPosition设置为CenterPosition,但我的窗体没有居中

试试这个!

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

在应用程序的构造函数中调用两个虚成员。

this.Text; 
this.MaximumSize;

不要在构造函数中调用虚成员,否则可能导致异常行为

固定代码
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); 
        }
    }
}