Left align the toolbars by code

74 Views Asked by At

Is there a way to left align the toolbars (without leaving the "spaces") by code? enter image description here

(say, when clicking to the button2) enter image description here

PS
Also this situation

enter image description here
To "left align" means :
enter image description here

2

There are 2 best solutions below

1
On BEST ANSWER

Update

Based upon your criteria changing quite dramatically, here is some code which will get you going. It is not perfect nor even close to being perfect!

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        _otherStrips = new List<OtherStrips>();
    }

    private int _currentHeight = 0;
    private List<OtherStrips> _otherStrips;

    private void button1_Click(object sender, EventArgs e)
    {
        foreach (var c in panel1.Controls)
        {
            if (c is ToolStrip)
            {
                ToolStrip ts = (ToolStrip)c;
                _otherStrips.Add(new OtherStrips() { Top = ts.Top, Width = ts.Width, Name = ts.Name });
                MoveToPosition(ts);
            }
        }
    }

    private void MoveToPosition(ToolStrip toolStrip)
    {
        bool isInline;
        toolStrip.Left = GetWidth(toolStrip, out isInline); 

        if (isInline)
            toolStrip.Top = GetTop(toolStrip);
    }

    private int GetWidth(ToolStrip ts, out bool isInline)
    {
        int result = 0;
        isInline = false;
        foreach (var item in _otherStrips)
        {
            if (item.Name == ts.Name)
                continue;

            if (item.Top == ts.Top)
            {
                isInline = true;
                break;
            }
        }

        if (!isInline)
            return result;

        foreach (var item in _otherStrips)
        {
            if (item.Width == ts.Width)
                result += item.Width;
        }

        return result + 22;//hack since the width is out by about 22pixels. Not going to spend any time fixing this
    }

    private int GetTop(ToolStrip ts)
    {
        foreach (var item in _otherStrips)
        {
            if (item.Name == ts.Name)
                continue;

            if (item.Top == ts.Top)
                return item.Top;
        }

        _currentHeight += ts.Height;
        return _currentHeight;
    }
}

struct OtherStrips
{
    public int Top { get; set; }
    public int Width { get; set; }
    public string Name { get; set; }
}
1
On

You can use this to left align your ToolStrip

toolStrip1.Location = new Point(0, toolStrip1.Location.Y);