我正在使用Visual Studio 2012.我的表单在打开时不会居中到屏幕上。我将表单的StartPosition
设置为CenterScreen
,但它始终位于左侧监视器的左上角(我有2个监视器)。
有什么想法吗?感谢
答案 0 :(得分:6)
试试这个!
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);
}
}
}