Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the size of the displayed Text in a TextBox

Tags:

c#

winforms

I need a way to determine the size of displayed text in a multi-column TextBox to set the Scrollbars property to the correct value.

Since it is some sort of enhanced MessageBox what I work on, the size of the MessageBox should be determined from the height and the width of the text sourced by strings with newlines in it.

Currently I use this code to determine the size of the MessageBox depending on the text to be entered. But you see the MessageBox has a MaximiumSize determined. The TextBox for the text itself has WordWrap enabled, too. So the only thing undefined is the Height of the text after inserting it to TextBox.Text.

SizeF textSize = this.tbxText.CreateGraphics().MeasureString(message, this.tbxText.Font);

int frmWidth = picWidth + (int)textSize.Width;
if (frmWidth > this.MaximumSize.Width)
{
    frmWidth = this.MaximumSize.Width;
}
else if (frmWidth < this.MinimumSize.Width)
{
    frmWidth = this.MinimumSize.Width;
}

int frmHeight = picHeight + (int)textSize.Height + pnlButtons.Height + pnlInput.Height;
if (frmHeight > this.MaximumSize.Height)
{
    frmHeight = this.MaximumSize.Height;
}
else if (frmHeight < this.MinimumSize.Height)
{
    frmHeight = this.MinimumSize.Height;
}

Setting the TextBox.Scrollbars Property to Both as default lets a disabled Scrollbar on the screen that is not really nice nor wanted. Sadly, the Graphics.MeasureString does not help really, since it does not consider WordWrap behaviour.

So, how can I determine if the TextBox.Text is leaving the visible area making a vertical Scrollbar needed?

like image 399
Oliver Friedrich Avatar asked Sep 17 '25 15:09

Oliver Friedrich


1 Answers

I would continue to use Graphics.MeasureString, but you need to add logic that will simulate a word wrap by dividing the resulting string width with the control width (ie, you calculate how textbox widths fit in your string width) to get your rows and then multply the string height by this.

Note however that Graphics.MeasureString is not entirely accurate, however as a rough guess for scrolling support it might suffice - as always, test this out.

like image 159
Adam Houldsworth Avatar answered Sep 20 '25 05:09

Adam Houldsworth