Search code examples
winformsmenustrip

MenuStrip shortcut key spacing


Is there a simple way to increase the spacing between the menu item text and its shortcut key in a WinForms MenuStrip? As seen below, even the default template generated by VS looks bad, with the text "Print Preview" extending beyond the shortcut keys of other items:

MenuStrip

I'm looking for a way to have some spacing between the longest menu item and the start of the shortcut key margin.


Solution

  • An easy way to do it is to space out the shorter menu items. For example, pad the Text property of your "New" menu item to be "New               " so that it has all the extra spaces at the end and that will push over the shortcut.

    Update

    I suggested automating this in code to help you out. Here's the result of letting the code do the work for you:

    enter image description here

    I wrote the following code that you can call that will go through all the main menu items under your menu strip and resize all the menu items:

    // 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);
        }
    }
    

    And these are the methods that do the work:

    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;
    }