hi all,

I got 3 form that is form1,form2,form3

I create a mainmenu to call form2 or form3

I got problem to getcenter the form2 or form3 in FORM 1....

Anyone have idea?...

9 Years
Discussion Span
Last Post by Teme64

This is what I came up with thinking quickly. The code is for the client forms

Public Class Form2

  Private Sub Form2_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Activated
    ' Call resize to position this form _after_ creation
    ' Call with dummy (empty) args
    Form2_Resize(Me, New System.EventArgs)

  End Sub

  Private Sub Form2_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

  End Sub

  Private Sub Form2_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Resize
    ' Center to calling form
    Dim ParentX As Integer ' Y coordinate
    Dim ParentY As Integer ' X coordinate
    Dim ParentHeight As Integer ' Height
    Dim ParentWidth As Integer ' Width
    Dim NewY As Integer ' This form's new vertical position
    Dim NewX As Integer ' This form's new horizontal position

    ' NOTICE: You have to know the name of the calling form
    ' Form1.Location.X and Form1.Location.Y return the parent's screen coordinates
    ParentY = Form1.Location.Y
    ParentX = Form1.Location.X
    ' Get Form1 size
    ParentHeight = Form1.Height
    ParentWidth = Form1.Width
    ' Calculate vertical position
    NewY = ParentY + (ParentHeight \ 2) - (Me.Height \ 2)
    ' Calculate horizontal position
    NewX = ParentX + (ParentWidth \ 2) - (Me.Width \ 2)
    ' Set the position
    Me.Location = New Point(NewX, NewY)

  End Sub

End Class

I commented the code as well as I could so it should be self-explanatory. Form2_Resize sub may not be the best place to relocate form, but you can put the calculation to some other sub.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.