Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center form on screen or on parent

Tags:

vb.net

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?

like image 384
Wine Too Avatar asked Oct 15 '13 22:10

Wine Too


1 Answers

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
like image 104
mike100111 Avatar answered Sep 30 '22 02:09

mike100111