2012-04-02 3 views
2

WinForms MenuStripでメニュー項目のテキストとそのショートカットキーの間隔を広げる簡単な方法はありますか?以下から分かるように、VSによって生成されたとしても、デフォルトのテンプレートは、他の項目のショートカットキーを越えて伸びるテキスト「印刷プレビュー」で、悪いなりますMenuStripショートカットキーの間隔

MenuStrip

私はいくつかの間隔を持つ方法を探しています最も長いメニュー項目とショートカットキーマージンの開始点との間にあります。

答えて

2

簡単な方法は、短いメニュー項目のスペースを空けることです。それは最後に、すべての余分なスペースを持っており、それがオーバープッシュしますように、例えば、パッドあなたの「新しい」メニュー項目のTextプロパティには、「                             新」であることをショートカット。

更新

私はあなたを助けるために、コードでこれを自動化する提案。 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; 
} 
これで問題は、それがのrequスペースの数を決定することは困難だということです
+0

固定幅フォントではなく、文字列の長さほど簡単ではありません。それにもかかわらず+1。 – casablanca

+0

私のアップデート@casablancaを見てください。 –

+0

ありがとう、私はこの答えを受け入れている - 私は本当に 'MeasureText'を使用して終了したくないが、私はより良い方法を見つけることができませんでした。 – casablanca