5

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)?

Mike
  • 53
  • 1
  • 5
  • 2
    winform wpf? what? You do know that we don't stand next to you, right? – gdoron Feb 12 '12 at 14:18
  • possible duplicate of [How can I show scrollbars on a System.Windows.Forms.TextBox only when the text doesn't fit?](http://stackoverflow.com/questions/73110/how-can-i-show-scrollbars-on-a-system-windows-forms-textbox-only-when-the-text-d) – Hans Passant Feb 12 '12 at 14:38
  • Hans Passant, maybe partly it is, but all the answers there besides this one http://stackoverflow.com/a/4147348/1205147 are wrong, and answer by b8adamson looks pretty long and bold to me. I would expect there is a nicer and better workaround :) – Mike Feb 12 '12 at 15:41
  • @gdoron I think it's "winform" it's in the Tags... – DayTimeCoder Feb 12 '12 at 16:32
  • @OwaisQureshi. It's there now... It was edited! – gdoron Feb 12 '12 at 16:34

2 Answers2

7

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.

LarsTech
  • 80,625
  • 14
  • 153
  • 225
  • 3
    TextFormatFlags.TextBoxControl makes it a bit less goofy. – Hans Passant Feb 12 '12 at 18:32
  • Yea, thank you, Lars. I already made something up from this: http://stackoverflow.com/a/4147348/1205147 – Mike Feb 13 '12 at 21:33
  • 1
    Great! I tried to use Graphics.MeasureText in combination with number of lines (no word-wrap needed in my case). This method calculated slightly too high for each line, so when many lines, my method looked strange with extra space. Your method calculated exactly on the spot! Perfect!! – awe Aug 21 '12 at 13:40
0

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;
user1027167
  • 4,320
  • 6
  • 33
  • 40