Saturday, May 21, 2016

Positioning a control on the center of the form

Sometimes when I created a resizable or maximized form, I want to position my control on the center of my form depending on the screen resolution.

I use this code:
Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
    MyBase.OnLoad(e)
    Dim btn = New Button()
    Controls.Add(btn)
    btn.Location = New Point((ClientSize.Width - btn.Width) \ 2, _
                             (ClientSize.Height - btn.Height) \ 2)
End Sub
Reference: Centering (perfectly) dynamically created buttons on form?




I can replace the btn to txt or other control. just make sure to change the type.

Or I can use direct location on form Load event:
lblMessage.Location = New Point((ClientSize.Width - lblMessage.Width) \ 2, (ClientSize.Height - lblMessage.Height) \ 2)
txtUnlock.Location = New Point((ClientSize.Width - txtUnlock.Width) \ 2, (ClientSize.Height - txtUnlock.Height) \ 2)

Or if I want to alter a bit below, I can do addition at the end:
lblMessage.Location = New Point((ClientSize.Width - lblMessage.Width) \ 2, (ClientSize.Height - lblMessage.Height) \ 2 + 50)
txtUnlock.Location = New Point((ClientSize.Width - txtUnlock.Width) \ 2, (ClientSize.Height - txtUnlock.Height) \ 2 + 100)




No comments:

Post a Comment