有没有一种简单的方法来增加WinForms MenuStrip中菜单项文本和其快捷键之间的间距?如下图所示,即使是VS生成的默认模板看起来也很糟糕,文本“Print Preview”甚至超出了其他项目的快捷键:
我正在寻找一种方法,在最长的菜单项和快捷键边缘的开始之间留出一些间距。
// 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;
}
MeasureText
,但我找不到更好的方法。 - casablanca