Wine Too Wine Too - 3 months ago 20x Question

Center form on screen or on parent

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
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?


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)
        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.