Расстояние между горячими клавишами MenuStrip - PullRequest
3 голосов
/ 02 апреля 2012

Есть ли простой способ увеличить расстояние между текстом пункта меню и его сочетанием клавиш в WinForms MenuStrip? Как видно ниже, даже шаблон по умолчанию, сгенерированный VS, выглядит плохо, с текстом «Предварительный просмотр», выходящим за пределы сочетаний клавиш других элементов:

MenuStrip

Я ищу способ получить некоторый интервал между самым длинным элементом меню и началом поля сочетания клавиш.

1 Ответ

2 голосов
/ 03 апреля 2012

Простой способ сделать это - выделить короткие пункты меню.Например, добавьте свойство «Текст» вашего элемента меню «Новый», чтобы оно было «Новое», чтобы у него были все лишние пробелы в конце, и это переместит ярлык.

Обновить

Я предложил автоматизировать это в коде, чтобы помочь вам.Вот результат, позволивший коду выполнить всю работу за вас:

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