Since built in functionality for positioning forms in VB.NET are not always suitable to use I try to make my sub to do that.
But I missed something...
I had the problem with StartPosition = CenterParent
not working. I solved it calling the form with .ShowDialog()
instead of .Show()
:
' first you should set your form's Start Position as Center Parent
Private Sub button_Click(sender As Object, e As EventArgs) Handles button.Click
MyForm.ShowDialog()
End Sub
This might also be of use:
myForm.StartPosition = FormStartPosition.CenterParent
myForm.ShowDialog()
You can also use FormStartPosition.CenterScreen
The code is just wrong. It is also essential that this code runs late enough, the constructor is too early. Be sure to call it from the Load event, at that time the form is properly auto-scaled and adjusted for the user's preferences, the StartPosition property no longer matters then. Fix:
Public Shared Sub CenterForm(ByVal frm As Form, Optional ByVal parent As Form = Nothing)
'' Note: call this from frm's Load event!
Dim r As Rectangle
If parent IsNot Nothing Then
r = parent.RectangleToScreen(parent.ClientRectangle)
Else
r = Screen.FromPoint(frm.Location).WorkingArea
End If
Dim x = r.Left + (r.Width - frm.Width) \ 2
Dim y = r.Top + (r.Height - frm.Height) \ 2
frm.Location = New Point(x, y)
End Sub
Incidentally, one of the very few reasons to actually implement the Load event handler.
I know this is an old post and this doesn't directly answer the question, but for anyone else who stumbles upon this thread, centering a form can be done simply without requiring you to write your own procedure.
The System.Windows.Forms.Form.CenterToScreen()
and System.Windows.Forms.Form.CenterToParent()
allow you to center the a form in reference to the screen or in reference to the parent form depending on which one you need.
One thing to note is that these procedures MUST be called before the form is loaded. It is best to call them in the form_load event handler.
EXAMPLE CODE:
Private Sub Settings_Load(sender As Object, e As EventArgs) Handles Me.Load
Me.CenterToScreen()
'or you can use
Me.CenterToParent()
End Sub