Assumption: All buttons are the same width.
Let's take the '2 buttons visible' scenario first.
You need to think of regions and gaps.
The regions are the buttons and each gap is the space between each button.
So, you have 2 buttons and 1 gap.
You also have a gap to the left of the leftmost button and a further gap to
the right of the rightmost button.
So now, you have 2 buttons and 3 gaps.
You want all the gaps to be the same width and to calculate that width you
need to take the width of the buttons into account:
int _numbuttons = 2;
int _numgaps = _numbuttons + 1;
int _gapwidth = (ClientSize.Width - button1.Width * numbuttons) /
_numgaps;
Now it is a simple matter of:
button1.Left = _gapwidth;
button2.Left = button1.Right + _gapwidth;
For the '3 button scenario' you need to increase the number of buttons and
the number of gaps accordingly.
int _numbuttons = 3;
int _numgaps = _numbuttons + 1;
int _gapwidth = (ClientSize.Width - button1.Width * numbuttons) / numgaps;
button1.Left = _gapwidth;
button2.Left = button1.Right + _gapwidth;
button3.Left = button2.Right + _gapwidth;
You may find that the actual result of the calculation may be either a pixel
less or a pixel more than the optimum depending on whether or not the result
of (ClientSize.Width - button1.Width * _numbuttons) is a multiple of
_numgaps. If you have several buttons and are not careful with your
calculations you could end up with a 'creep' toward the left or the right
for the rightmost buttons.
Post by proxyuserLet's say you had a dialog where you wanted to display either 2 or 3
buttons, but either way you wanted them spaced evenly across the bottom.
In other words, sometimes there are 2 buttons with the 3rd hidden, but
when the 3rd unhides you want the other 2 to shift over. In the Designer,
you can select them and click on Make Horizontal Spacing Equal. Is there
a way to do this programmatically? It seems tedious to have to actually
figure out the pixels to move each button.