我正在使用这个很好的代码,顺便说一下,如果你知道有什么更好的方法来完成这个,我真的很感激让我们知道。所以这里是可以浮动的工具栏:
http://en.csharp-online.net/Tool,_Menu,_and_Status_Strips%E2%80%94Floating_ToolStrips
很好,但是如果我在这个工具栏上只有 4 个按钮,当我让它浮动时,它的大小仍然与之前停靠到表单的大小相同,但我希望它可以自行调整大小,只要它需要是显示它的按钮就可以了。
我正在使用这个很好的代码,顺便说一下,如果你知道有什么更好的方法来完成这个,我真的很感激让我们知道。所以这里是可以浮动的工具栏:
http://en.csharp-online.net/Tool,_Menu,_and_Status_Strips%E2%80%94Floating_ToolStrips
很好,但是如果我在这个工具栏上只有 4 个按钮,当我让它浮动时,它的大小仍然与之前停靠到表单的大小相同,但我希望它可以自行调整大小,只要它需要是显示它的按钮就可以了。
您可以将各个工具条项目的宽度相加,并将其用作表单的宽度。
替换这个:
floatForm.ClientSize = this.Size;
有了这个:
//Adjust min value for your needs. It should account for the width of the
//toolstrip, borders, etc.
int minWidth = 20;
int newWidth = minWidth;
foreach (ToolStripItem item in this.Items)
{
newWidth += item.Size.Width;
}
floatForm.ClientSize = new Size(newWidth, this.Size.Height);
m_floatForm.AutoSize = True
m_floatForm.AutoSizeMode = AutoSizeMode.GrowAndShrink
PreferredSize为我解决了问题。我没想到会在 ToolStip 上工作,但它确实如此,至少在 .Net 4.5 上是这样。
我仍然必须添加一个固定数字来解释我不确定它们来自哪里的几个像素。
this.Width = toolStrip.PreferredSize.Width + toolStrip.Margin.Horizontal + toolStrip.Parent.Margin.Horizontal + toolStrip.Parent.Padding.Horizontal+20;