2013-08-06 2 views
5

フォームのサイズをタイトル/キャプションテキストのサイズに合わせる方法はありますか?Cのタイトルテキストにフォームのサイズを適合させる

例えば、公式C#メッセージボックスフォームはそのタイトルテキストのサイズに調整されますが(Loremのイプサム注):

Normal Message Box

他の形態は、そののものに自分のサイズを調整しません。タイトルテキスト:

Other form

代わりに、省略記号をtの「サイズ」プロパティに記載されたサイズに合うように最後に追加されます彼はデザイナー。

サイズの代わりにタイトルのサイズに合わせてフォームを調整する方法はありますか?そうでない場合は、フォームに割り当てることができるようにテキストの全長を取得する方法はありますか?私は

int topTextWidth = TextRenderer.MeasureText(this.Text, this.Font).Width; 
this.Width = topTextWidth; 

しかしthis.Fontを使用してフォームの幅を設定しようとした

は明らかに別のフォントサイズを参照します。

+5

「SystemFonts.CaptionFont」を使用します。 'Width'はボーダー、アイコン、最小化/最大化/閉じるボタン、それらの間のパディング/マージンも考慮しなければならないことにも留意してください。 – JosephHirn

+1

ヒントをありがとう。私はC#でXボタンの幅とその周りのパディングを知る方法があることを知っています。私は答えがわかるとすぐに回答を投稿します。 – CydrickT

答えて

7

完全な回答がほしい人のために、ここにあります。

キャプションテキストに応じてフォームのサイズを変更し、実際の行は以下の通りである

this.Width = TextRenderer.MeasureText(this.Text, SystemFonts.CaptionFont).Width + AllButtonsAndPadding; 

AllButtonsAndPaddingはすべてのボタン(最小化、最大化、および閉じる)、ウィンドウ境界とアイコンの幅を含んでいます。これらの情報を取得するには、少しのコードが必要です。ここでは、どのボタンやアイコンを置いても、サイズを変更するフォームの完全な例を示します。

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using System.Windows.Forms.VisualStyles; 

namespace WindowAutoAdapt 
{ 
public partial class Form1 : Form 
{ 
    //A default value in case Application.RenderWithVisualStyles == false 
    private int AllButtonsAndPadding = 0; 
    private VisualStyleRenderer renderer = null; 

    public Form1() 
    { 
     InitializeComponent(); 
     this.Text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit."; //A big text in the title 
     GetElementsSize(); 
     ResizeForm(); 
    } 

    //This gets the size of the X and the border of the form 
    private void GetElementsSize() 
    { 
     var g = this.CreateGraphics(); 

     // Get the size of the close button. 
     if (SetRenderer(VisualStyleElement.Window.CloseButton.Normal)) 
     { 
      AllButtonsAndPadding += renderer.GetPartSize(g, ThemeSizeType.True).Width; 
     } 

     // Get the size of the minimize button. 
     if (this.MinimizeBox && SetRenderer(VisualStyleElement.Window.MinButton.Normal)) 
     { 
      AllButtonsAndPadding += renderer.GetPartSize(g, ThemeSizeType.True).Width; 
     } 

     // Get the size of the maximize button. 
     if (this.MaximizeBox && SetRenderer(VisualStyleElement.Window.MaxButton.Normal)) 
     { 
      AllButtonsAndPadding += renderer.GetPartSize(g, ThemeSizeType.True).Width; 
     } 

     // Get the size of the icon. 
     if (this.ShowIcon) 
     { 
      AllButtonsAndPadding += this.Icon.Width; 
     } 

     // Get the thickness of the left, bottom, 
     // and right window frame. 
     if (SetRenderer(VisualStyleElement.Window.FrameLeft.Active)) 
     { 
      AllButtonsAndPadding += (renderer.GetPartSize(g, ThemeSizeType.True).Width) * 2; //Borders on both side 
     } 
    } 

    //This resizes the form 
    private void ResizeForm() 
    { 
     this.Width = TextRenderer.MeasureText(this.Text, SystemFonts.CaptionFont).Width + AllButtonsAndPadding; 
    } 

    //This sets the renderer to the element we want 
    private bool SetRenderer(VisualStyleElement element) 
    { 
     bool bReturn = VisualStyleRenderer.IsElementDefined(element); 

     if (bReturn && renderer == null) 
      renderer = new VisualStyleRenderer(element); 
     else 
      renderer.SetParameters(element); 

     return bReturn; 
    } 
} 
} 
0

ありがとう@CydrickT、それは役に立ちました。 FormBorderStyleFixedDialogで、ControlBox == falseがフォームにある場合は(do catch catch to errorの処理が必要です)、これをウィンドウに適用するときに必要な修正があります。

FormBorderStyleでもアイコンが指定されていても、このバージョンのコードで調整されるように、特定のロジックに基づいてShowIcon == trueであっても表示されません。

また、指定されていればコンストラクタで最小幅に設定されているウィンドウの最小幅、そうでない場合はデザイン時間幅を保持する新しいプライベートプロパティを追加しました。これにより、テキスト(タイトル)をコードで変更してからフォームを再表示すると、ウィンドウの幅の縮小が可能になります。

フォームのテキストに変更されたテキストメソッドを追加しました。フォームのタイトルテキストが変更されるたびに、フォームの幅が調整されるように(フォームインスタンスを再利用する場合は再び)調整されます。フォームのデザイナーはもちろん、Text Changedイベントを使用するためにこれを設定する必要があります。

using System; 
using System.Drawing; 
using System.Windows.Forms; 
using System.Windows.Forms.VisualStyles; 

namespace WindowAutoAdapt 
{ 
    public partial class Form1: Form 
    { 
     private int AllButtonsAndPadding = 10;//seems things are coming up about this amount short so. . . 
     private VisualStyleRenderer renderer = null; 
     private int minWidth = 0;//will hold either the minimum size width if specified or the design time width of the form. 

     public Form1() 
     { 
      InitializeComponent(); 

      //Capture an explicit minimum width if present else store the design time width. 
      if (this.MinimumSize.Width > 0) 
      { 
       minWidth = this.MinimumSize.Width;//use an explicit minimum width if present. 
      } 
      else 
      { 
       minWidth = this.Size.Width;//use design time width 
      } 

      GetElementsSize(); 
      ResizeForm(); 
     } 

    /// <summary> 
    /// 
    /// </summary> 
    /// <param name="sender"></param> 
    /// <param name="e"></param> 
    private void Form1_TextChanged(object sender, EventArgs e) 
    { 
     GetElementsSize(); 
     ResizeForm(); 
    } 

     //This gets the size of the X and the border of the form 
     private void GetElementsSize() 
     { 
      var g = this.CreateGraphics(); 

      // Get the size of the close button. 
      if (SetRenderer(VisualStyleElement.Window.CloseButton.Normal)) 
      { 
       AllButtonsAndPadding += renderer.GetPartSize(g, ThemeSizeType.True).Width; 
      } 

      // Get the size of the minimize button. 
      if (this.MinimizeBox && SetRenderer(VisualStyleElement.Window.MinButton.Normal)) 
      { 
       AllButtonsAndPadding += renderer.GetPartSize(g, ThemeSizeType.True).Width; 
      } 

      // Get the size of the maximize button. 
      if (this.MaximizeBox && SetRenderer(VisualStyleElement.Window.MaxButton.Normal)) 
      { 
       AllButtonsAndPadding += renderer.GetPartSize(g, ThemeSizeType.True).Width; 
      } 

      // Get the size of the icon only if it is actually going to be displayed. 
      if (this.ShowIcon && this.ControlBox && (this.FormBorderStyle == FormBorderStyle.Fixed3D || this.FormBorderStyle == FormBorderStyle.Sizable || this.FormBorderStyle == FormBorderStyle.FixedSingle)) 
      { 
       AllButtonsAndPadding += this.Icon.Width; 
      } 

      // Get the thickness of the left and right window frame. 
      if (SetRenderer(VisualStyleElement.Window.FrameLeft.Active)) 
      { 
       AllButtonsAndPadding += (renderer.GetPartSize(g, ThemeSizeType.True).Width) * 2; //Borders on both side 
      } 
     } 

     //This resizes the form 
     private void ResizeForm() 
     { 
      //widen window if title length requires it else contract it to the minWidth if required. 
      int newWidth = TextRenderer.MeasureText(this.Text, SystemFonts.CaptionFont).Width + AllButtonsAndPadding; 
      if (newWidth > minWidth) 
      { 
       this.Width = newWidth; 
      } 
      else 
      { 
       this.Width = minWidth; 
      } 
     } 

     //This sets the renderer to the element we want 
     private bool SetRenderer(VisualStyleElement element) 
     { 
      try 
      { 
       bool bReturn = VisualStyleRenderer.IsElementDefined(element); 
       if (bReturn && renderer == null) 
       { 
        renderer = new VisualStyleRenderer(element); 
       } 
       else 
       { 
        renderer.SetParameters(element); 
       } 
       return bReturn; 
      } 
      catch (Exception) 
      { 
       return false; 
      } 
     } 
    } 
}