C# Resize textbox to fit content

前端 未结 10 723
礼貌的吻别
礼貌的吻别 2020-12-05 13:39

I\'m writing a program where the user should be able to write text in a textbox. I\'d like the textbox to resize itself, so it fit the content. I\'ve tried the following:

10条回答
  •  余生分开走
    2020-12-05 14:01

    Try this:

    using System.Drawing;
    ...
    
    private void textBoxTitle_TextChanged(object sender, TextChangedEventArgs e)
    {
        // Determine the correct size for the text box based on its text length   
    
        // get the current text box safely
        TextBox tb = sender as TextBox;
        if (tb == null) return;
    
        SizeF stringSize;
    
        // create a graphics object for this form
        using(Graphics gfx = this.CreateGraphics())
        {
            // Get the size given the string and the font
            stringSize = gfx.MeasureString(tb.Text, tb.Font);
        }
    
        // Resize the textbox 
        tb.Width = (int)Math.Round(stringSize.Width, 0);
    
    }
    

    Essentially you create your own Graphics object for the form, then measure it based on the text and font of the TextBox. The using will properly dispose the Graphics object - your previous code would have leaked horribly!

提交回复
热议问题