在WinForms MenuStrip中,有没有一种简单的方法可以增加菜单项文本及其快捷键之间的间距?如下所示,即使是VS生成的默认模板看起来也很糟糕,文本"Print Preview“超出了其他项目的快捷键:

我正在寻找一种方法来在最长的菜单项和快捷键边距的开头之间留出一些间距。
发布于 2012-04-03 04:43:23
要做到这一点,一个简单的方法是将较短的菜单项隔开。例如,将"New“菜单项的Text属性填充为”New“、”“,以便在末尾有所有额外的空格,这将推送快捷方式。
更新
我建议在代码中自动执行此操作,以帮助您解决问题。下面是让代码为您完成工作的结果:

我编写了以下代码,您可以调用这些代码来遍历菜单条下的所有主菜单项,并调整所有菜单项的大小:
// put in your ctor or OnLoad
// Note: the actual name of your MenuStrip may be different than mine
// go through each of the main menu items
foreach (var item in menuStrip1.Items)
{
if (item is ToolStripMenuItem)
{
ToolStripMenuItem menuItem = (ToolStripMenuItem)item;
ResizeMenuItems(menuItem.DropDownItems);
}
}以下是完成这项工作的方法:
private void ResizeMenuItems(ToolStripItemCollection items)
{
// find the menu item that has the longest width
int max = 0;
foreach (var item in items)
{
// only look at menu items and ignore seperators, etc.
if (item is ToolStripMenuItem)
{
ToolStripMenuItem menuItem = (ToolStripMenuItem)item;
// get the size of the menu item text
Size sz = TextRenderer.MeasureText(menuItem.Text, menuItem.Font);
// keep the longest string
max = sz.Width > max ? sz.Width : max;
}
}
// go through the menu items and make them about the same length
foreach (var item in items)
{
if (item is ToolStripMenuItem)
{
ToolStripMenuItem menuItem = (ToolStripMenuItem)item;
menuItem.Text = PadStringToLength(menuItem.Text, menuItem.Font, max);
}
}
}
private string PadStringToLength(string source, Font font, int width)
{
// keep padding the right with spaces until we reach the proper length
string newText = source;
while (TextRenderer.MeasureText(newText, font).Width < width)
{
newText = newText.PadRight(newText.Length + 1);
}
return newText;
}https://stackoverflow.com/questions/9969664
复制相似问题