I would like to determine what the best method is for determining the number of displayed (visible due to scrolling) lines on a multiline winforms TextBox
control.
The current method I am using is grossly inaccurate (as are other methods I have tried):
var size = TextRenderer.MeasureText(
textBox.Text, textBox.Font, textBox.ClientSize, TextFormatFlags.TextBoxControl);
int lines = textBox.Lines.Length;
int lineHeight = (size.Height / lines);
// Value assigned to 'lines' does not reflect number of lines displayed:
int lines = (textBox.Height / lineHeight);
The method to calculate number of lines visible must take into account things such as the scroll bars of the text box, and nuances of text box display including lines that would only be partially visible are not displayed.
Any solution will be greatly appreciated!
Update:
Tried the following calculation as suggested, but still remain with inaccurate result:
int lines = (textBox.Height / textBox.Font.Height);
I've made a simple test program, here is a screenshot, both examples above produce similar results:
The calculated number of lines using the either method often does not reflect number of actual lines displayed as the height is increased or decreased.