无法将表单定位到中心

Spo*_*nts 4 vb.net winforms

我有一个名为Form1的表单.它设置为启动 - 位置=中心但在执行时它会在其他地方打开(在随机位置evrytime).

我使用IDE Visual Studio - 2010在Windows XP SP3下工作.请提供此问题的解决方法.

我上传了一个显示上述问题的示例项目.

下载链接:

http://www.6ybh-upload.com/vt5i4z1wz9pl/Light.zip

Dav*_*ido 9

你必须设置:

Form1.StartPosition = FormStartPosition.Manual
Run Code Online (Sandbox Code Playgroud)

编辑:

这是一个工作样本:

Dim X As Integer = (Screen.PrimaryScreen.Bounds.Width - Me.Width) / 2
Dim Y As Integer = (Screen.PrimaryScreen.Bounds.Height - Me.Height) / 2
Me.StartPosition = FormStartPosition.Manual
Me.Location = New System.Drawing.Point(X, Y)
Run Code Online (Sandbox Code Playgroud)

编辑2:

以下是基于Hans Passant评论的改进代码(更好):

Dim mainScreen As Screen = Screen.FromPoint(Me.Location)
Dim X As Integer = (mainScreen.WorkingArea.Width - Me.Width) / 2 + mainScreen.WorkingArea.Left
Dim Y As Integer = (mainScreen.WorkingArea.Height - Me.Height) / 2 + mainScreen.WorkingArea.Top

Me.StartPosition = FormStartPosition.Manual
Me.Location = New System.Drawing.Point(X, Y)
Run Code Online (Sandbox Code Playgroud)

  • 假设主屏幕为0,0.不一定如此.将Bounds.Left和Bounds.Top添加到X和Y值.你应该使用WorkingArea而不是Bounds.并且表单可能不一定在主屏幕上打开,请使用Screen.FromPoint.它应该在Load事件中完成以处理AutoScaleMode.细节,细节. (2认同)