2013-08-06 9 views
5

Czy istnieje sposób dostosowania rozmiaru formularza do rozmiaru jego tytułu/tekstu napisu?Dostosuj rozmiar formularza do tekstu tytułu w języku C#

Na przykład urzędnik C# Wiadomość formy Box będzie dostosować do wielkości jej tytuł tekstu (Uwaga Lorem Ipsum):

Normal Message Box

Inne formy nie będzie dostosowanie ich rozmiaru do swoich tytuł tekstu:

Other form

Zamiast wielokropek zostanie dodany na końcu do rozmiaru wymienione w „rozmiar” własności t on projektant.

Czy istnieje sposób dostosowania formularza do rozmiaru tytułu zamiast wymiaru, o którym wspominamy? Jeśli nie, czy istnieje sposób uzyskania pełnej długości tekstu, abyśmy mogli przypisać go do formularza?

Próbowałem ustawienie szerokości formy korzystania

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

Ale this.Font najwyraźniej odnosi się do innego rozmiaru czcionki.

+5

Prawdopodobnie chcesz użyć 'SystemFonts.CaptionFont'. Należy również pamiętać, że 'Width' musi uwzględniać granice, ikonę, przyciski minimalizacji/maksymalizacji/zamknięcia oraz dopełnienie/marginesy między nimi. – JosephHirn

+1

Dzięki za podpowiedź.Wiem, że są sposoby w języku C#, aby znać szerokość przycisku X i wypełnienie wokół niego. Napiszę odpowiedź, gdy tylko poznam odpowiedź. – CydrickT

Odpowiedz

7

Dla tych, którzy chcą pełnej odpowiedzi, oto ona.

Rzeczywista linia, która zmienia rozmiar formularza według tekstu napisów jest następujący:

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

AllButtonsAndPadding zawiera szerokość wszystkich przycisków (minimalizacji, maksymalizacji i zamykania) granice okna i ikony. Uzyskanie tych informacji wymaga nieco kodowania. Oto pełny przykład formularza, który zmienia się sam, bez względu na to, jakie przyciski lub ikony umieścisz.

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

Dzięki @CydrickT, to było pomocne. Mam pewne modyfikacje, które były potrzebne przy zastosowaniu tego do okna z FormBorderStyle z FixedDialog i jeśli ControlBox == false w formularzu (trzeba spróbować złapać, aby obsłużyć błąd).

Również pomimo, że i ikony są określone, niektóre FormBorderStyle nie wyświetlają ich (nawet jeśli ShowIcon == true, który opiera się na niektórych kodach), więc ta wersja kodu dostosowuje się do tego.

Dodałem również nową prywatną właściwość, która zawiera minimalną szerokość okna ustawionego w konstruktorze na minimalną szerokość, jeśli została określona lub szerokość czasu projektu, jeśli nie została podana. Pozwala to na skrócenie szerokości okna, jeśli ma zostać zmieniony jego tekst (tytuł) w kodzie, a następnie ponownie wyświetlony formularz.

Dodałem zmienioną tekstowo metodę dla tekstu formularza: , dzięki czemu w dowolnym momencie tekst tytułu formularza zostanie zmieniony, szerokość formularza dostosuje się (ponownie, w przypadku ponownego użycia instancji formularza). Oczywiście projektant formularza musiałby to ustawić dla zdarzenia Text Changed, które ma zostać użyte.

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; 
      } 
     } 
    } 
} 
Powiązane problemy