首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >MenuStrip快捷键间距

MenuStrip快捷键间距
EN

Stack Overflow用户
提问于 2012-04-02 08:40:06
回答 1查看 1.5K关注 0票数 4

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

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-04-03 04:43:23

要做到这一点,一个简单的方法是将较短的菜单项隔开。例如,将"New“菜单项的Text属性填充为”New“、”“,以便在末尾有所有额外的空格,这将推送快捷方式。

更新

我建议在代码中自动执行此操作,以帮助您解决问题。下面是让代码为您完成工作的结果:

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

代码语言:javascript
复制
// 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);
    }
}

以下是完成这项工作的方法:

代码语言:javascript
复制
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;
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9969664

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档