Starting from this previous question, I have the following method:
internal static int NumberOfPhysicalLinesInTextBox(TextBox tb)
{
int lc = 0;
while (tb.GetFirstCharIndexFromLine(lc) != -1)
{
++lc;
}
return lc;
}
For a currently unknown reason, it does not work in the context where I need it, so I tried another solution.
I created a new multiline TextBox, with no character in it. I type in it only an Enter (it shows up in the Text property as "\r\n", so 2 chars). The method above, NumberOfPhysicalLinesInTextBox, returns correctly the number of physical lines, 2 (caret is on the second and last physical line).
Using the following method, I cannot get the same result in this specific case (in general, it Works well):
internal static int NumberOfPhysicalLinesInTextBox_2(TextBox tb)
{
string t = tb.Text;
int lines = 1;
int firstCharY = tb.GetPositionFromCharIndex(0).Y;
int lastCharY = tb.GetPositionFromCharIndex(t.Length - 1).Y;
lines += (lastCharY - firstCharY) / tb.Font.Height;
return lines;
}
TextBoxBase.GetPositionFromCharIndex called with parameters 0 and then 1 return the same Point: {X = 1, Y = 1}, and for 2 (inexisting char) it returns the Point: {X = 0, Y = 0}.