C# Resize textbox to fit content

前端 未结 10 706
礼貌的吻别
礼貌的吻别 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:14

    I am adding this answer as I do not see the fixed width aspect of a textbox being discussed in any of the other. If you have a fixed width for your textbox, and you want to adjust only its height you can do something like the following:

    Something like this gives the height of the text as how it is drawn in the multiline wordwrapped textbox itself:

    SizeF MessageSize = MyTextBoxControl.CreateGraphics()
                                    .MeasureString(MyTextBoxControl.Text,
                                                    MyTextBoxControl.Font,
                                                    MyTextBoxControl.Width, 
                                                    new StringFormat(0));
    

    I am not sure what StringFormat should be but the values StringFormatFlags do not seem to apply to a default TextBox make up.

    Now with MessageSize.Height you know the height of the text in the textbox.

提交回复
热议问题