6

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

有任何想法吗?谢谢

4

1 回答 1

7

试试这个方法!

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); 
        }
    }
}
于 2013-01-12T12:32:55.200 回答