为了右对齐一些菜单项,你需要将项目的对齐值设置为右。但是,右对齐仅适用于StackWithOverflow布局样式。如果您使用流程对齐样式,则项目将始终从左到右流动。
此外,当您在StackWithOverflow布局样式右对齐项目,来自外部的项目流程,因此,如果您的原始布局是1 2 3 4 5
,你的右对齐项目将1 2 3 <gap> 5 4
。
你的问题的解决方案由两个部分组成:
轨道的SizeChanged将事件,以确定是否需要流量或StackWithOverflow基于所有菜单项的宽度和可用窗户的宽度。
如果您必须更改布局样式,请交换右对齐的项目,以使它们以任一布局样式以正确的顺序出现。
private void Form1_SizeChanged(object sender, EventArgs e)
{
int width = 0;
// add up the width of all items in the menu strip
foreach (ToolStripItem item in menuStrip1.Items)
width += item.Width;
// get the current layout style
ToolStripLayoutStyle oldStyle = menuStrip1.LayoutStyle;
// determine the new layout style
ToolStripLayoutStyle newStyle = (width < this.ClientSize.Width)
? menuStrip1.LayoutStyle = ToolStripLayoutStyle.StackWithOverflow
: menuStrip1.LayoutStyle = ToolStripLayoutStyle.Flow;
// do we need to change layout styles?
if (oldStyle != newStyle)
{
// update the layout style
menuStrip1.LayoutStyle = newStyle;
// swap the last item with the second-to-last item
int last = menuStrip1.Items.Count - 1;
ToolStripItem item = menuStrip1.Items[last];
menuStrip1.Items.RemoveAt(last);
menuStrip1.Items.Insert(last - 1, item);
}
}
交换右对齐项目的进程将不得不更仔细地适应,如果你有两个以上的项目。上面的代码只需交换它们,但如果您有三个或更多项目,则需要完全颠倒它们的顺序。
哇,谢谢!这工作完美。我非常感谢帮助! – Caleb