MenuStrip快捷键间距

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

MenuStrip

我正在寻找一种方法,在最长的菜单项和快捷键边缘的开始之间留出一些间距。

1个回答

2
一种简单的方法是将较短的菜单项间隔开。例如,将“新建”菜单项的Text属性填充为“New               ”,这样它就有了额外的空格,并将推动快捷键。 更新 我建议通过代码自动化来帮助您完成此操作。以下是让代码为您完成工作的结果: enter image description here 我编写了以下代码,您可以调用该代码,它将遍历菜单栏下的所有主菜单项并调整所有菜单项的大小:
// 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;
}

问题在于在非等宽字体中确定所需的空格数量很困难——这不像字符串长度那样容易。+1 无论如何。 - casablanca
谢谢,我接受这个答案——我真的不想使用MeasureText,但我找不到更好的方法。 - casablanca

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接