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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With