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

6

我正在使用Visual Studio 2012。我的窗体打开时不会居中显示在屏幕上。我已将窗体的StartPosition设置为CenterScreen,但它总是开始于我的左侧显示器的左上角(我有两个显示器)。

有什么建议吗?谢谢


6
放在构造函数中对我有效。你能展示一些代码吗? - e_ne
你需要看哪段代码?我原本以为可以通过表单属性来设置这个? - bd528
对我来说,无论是在代码中设置 StartPosition = FormStartPosition.CenterScreen; 还是从设计器中设置都可以正常工作。我想请您提供代码,以便查看是否有其他内容覆盖或干扰了您的设置。 - e_ne
@user1936588 - 已更新! - Parimal Raj
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); 
        }
    }
}

方法1和方法2都没有起作用。这是Form1的初始化代码:- this.Location = new System.Drawing.Point(100, 100); this.MaximumSize = new System.Drawing.Size(620, 420); this.Name = "Form1"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "转换器"; this.WindowState = System.Windows.Forms.FormWindowState.Maximized; this.Load += new System.EventHandler(this.Form1_Load); this.ResumeLayout(false); this.PerformLayout(); - bd528
2
这对我有用,但在构造函数中不起作用。由于某种原因,表单继承会破坏“CenterScreen”,即使删除了破坏它的继承。所以,对我来说,解决方案是将方法#2中的代码放入我的基本表单的“Load”事件处理程序中。 - InteXX

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接