Mike
Mike

Reputation: 53

How to get TextBox's real height?

My first thought was it would be something like this:

int height = textbox.lines.length * lineheight;

But it just counts "\xd\n" and lines can be wrapped. Can i get the number of displayed lines or actual height of textbox when everything is visible(the height of text inside)?

Upvotes: 5

Views: 2867

Answers (2)

user1027167
user1027167

Reputation: 4448

The function GetLineFromCharIndex() gives you the corrent line index, even if the text is wrapped.

int lineCount = textBox1.GetLineFromCharIndex(int.MaxValue) + 1;
int lineHeightPixel = TextRenderer.MeasureText("X", textBox1.Font).Height;

Upvotes: 0

LarsTech
LarsTech

Reputation: 81620

I don't know if you will ever get a perfect measurement, but this gets close:

private int GetTextHeight(TextBox tBox) {
  return TextRenderer.MeasureText(tBox.Text, tBox.Font, tBox.ClientSize,
           TextFormatFlags.WordBreak | TextFormatFlags.TextBoxControl).Height;
}

The TextBox can be goofy. With multi-line turned on, if you press a character that causes the word to word-wrap, hitting backspace does not cause it to "un-word-wrap" unless I resize the TextBox. This was on a Win7-64. I don't think the TextBox control always did that.

Upvotes: 7

Related Questions