SpongeBob SquarePants SpongeBob SquarePants - 7 months ago 11
Vb.net Question

Unable to position form to center

I have a form called Form1. Its set to startup-Position = Center but when executed it opens up somewhere else (At a random position evrytime).

I am working under Windows XP SP3 , using IDE Visual Studio - 2010. Please provide a workaround to this problem.

I have uploaded a sample project showing the above mentioned problem .

Download link:

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

Answer

You have to set:

Form1.StartPosition = FormStartPosition.Manual

Edit:

Here is a working sample:

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)

Edit 2:

Here is the improved code based on comments by Hans Passant, (much better):

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)