How to get TextBox's real height?

蓝咒 提交于 2020-01-03 15:18:08

问题


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


回答1:


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.




回答2:


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;


来源:https://stackoverflow.com/questions/9249456/how-to-get-textboxs-real-height

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!