开发者

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-s开发者_Python百科izing 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))


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


Setting the Anchor property to AnchorStyles.None will cause the control to be centered, both horizontally and vertically.

control.Anchor = AnchorStyles.None

To mantain vertical positioning (only horizontal centering):

control.Anchor = AnchorStyles.Top

To mantain horizontal positioning (only vertical centering):

control.Anchor = AnchorStyles.Left

Source

I tried it, and it worked for me. The control will be centered within the parent element.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜