按代码左对齐工具栏

时间:2013-05-14 10:18:13

标签: .net winforms toolbars

有没有办法通过代码左对齐工具栏(不留下“空格”)? enter image description here

(例如,点击按钮2时) enter image description here

PS
还有这种情况

enter image description here
“左对齐”意味着:
enter image description here

2 个答案:

答案 0 :(得分:0)

<强>更新

根据您的标准变化非常显着,这里有一些代码可以帮助您。它并不完美,也不接近完美!

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 :(得分:0)

您可以使用它来左对齐ToolStrip

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