4

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

菜单条

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

4

1 回答 1

2

一个简单的方法是隔开较短的菜单项。例如,将“新建”菜单项的 Text 属性填充为“新建”,以便它在末尾有所有额外的空格,这将推动快捷方式。

更新

我建议在代码中自动执行此操作以帮助您。这是让代码为您完成工作的结果:

在此处输入图像描述

我编写了以下代码,您可以调用该代码将遍历菜单条下的所有主菜单项并调整所有菜单项的大小:

// 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;
}
于 2012-04-02T20:43:23.260 回答