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 に答える