Search code examples
vb.netbuttonloadcenter

Centering (perfectly) dynamically created buttons on form?


this is my first post here so I hope I provide all the right information.

I am currently developing a simple menu application that has a control array of buttons (using the work around for control arrays suggested by MSDN) and I am having a hard time with re-sizing the form and centering the buttons. These buttons are created at compile time (with parameters from an INI file) and my current centering algorithm seems to slightly set them to the right. I am using the "button.location = new Point(...,...)" method but after reading about this it says the values locate the buttons left upper corner rather than center, thus accounting for the slight offset to the right.

My two questions are this:

How can I perfectly center these buttons at compile time? I have tried accounting for the difference by subtracting half of the button's width but the button width and point properties seem to be incompatible and the button gets heavily offset.

And... my other goal for re-sizing the menu is to have the buttons perfectly expand and contract when being re-sized. It seems as though anchoring is ineffective when the buttons are created dynamically so I have been forced to write ratio algorithms... Is there a way to get anchoring to work?

Here's what I have in the load up :

 MyControlArray(i).Location = New Point(CInt(((Width - ButtonWidth) / 2) +_
(ButtonWidth / 2)), CInt((Height - MyControlArray(i).Height) / 2))

I have already tried:

New Point(CInt(((Width - ButtonWidth) / 2)), CInt((Height - MyControlArray(i).Height)_
/ 2))

Solution

  • That's because you use the wrong variables, Width and Height include the borders and caption. You should use the ClientSize property instead. Like this:

    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