Monday 11 April 2011

Resize a form in VB .Net and keep items centered

Funny, I would have thought this would have bee done lots of times before my Google search. But either my Google search skills failed me or it hasn't been done lots of times before. Thankfully one search result yielded the answer (John Robbins http://searchwindevelopment.techtarget.com/answer/How-do-you-center-controls-on-a-form-in-VBNET). For those who don't have a login for the searchxxxxx.com network this is how it works:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

CenterButton()
End Sub

Private Sub CenterButton()
    buttonMain.Top = (Me.ClientSize.Height/2) - (buttonMain.Height / 2)
    buttonMain.Left = (Me.ClientSize.Width/2) - (buttonMain.Width / 2)
    End Sub

Private Sub Form1_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Resize
    CenterButton()
End Sub
It simply takes the form width and height, divides by two, then minus half the width of the object (to ensure an accurate center) and shazam! The example above also has a nice handle for resizing so it repositions the objects as you resize the window. Cool! You learn something every day...