有没有办法通过代码左对齐工具栏(不留下“空格”)?
(例如,单击按钮2时)
PS
也是这种情况
“左对齐”意味着:
更新
根据您的标准变化很大,这里有一些代码可以帮助您前进。它不完美,甚至接近完美!
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; }
}
您可以使用它来左对齐 ToolStrip
toolStrip1.Location = new Point(0, toolStrip1.Location.Y);