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...
Public Sub form_center(ByVal frm As Form, Optional ByVal parent As Form = Nothing)
Dim x As Integer
Dim y As Integer
Dim r As Rectangle
If Not parent Is Nothing Then
r = parent.ClientRectangle
x = r.Width - frm.Width + parent.Left
y = r.Height - frm.Height + parent.Top
Else
r = Screen.PrimaryScreen.WorkingArea
x = r.Width - frm.Width
y = r.Height - frm.Height
End If
x = CInt(x / 2)
y = CInt(y / 2)
frm.StartPosition = FormStartPosition.Manual
frm.Location = New Point(x, y)
End Sub
How to get this sub to place form correctly in the middle of the screen or other form if is defined?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With