0

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}.

silviubogan
  • 3,343
  • 3
  • 31
  • 57
  • Probably I am missing something here, but the TextBox has a Lines property that is an array and gives you the number of lines present in the textbox. What's wrong with that? – Steve Feb 09 '19 at 10:52
  • I really don't understand why you keep on trying to get something like a *line* number. Scrollbars work on Pixels measures, not on lines. You, usually (always?), need to measure the height of the text (with `TextRenderer:MeasureText`) or using the height returned by `GetPositionFromCharIndex`, which gives you, give or take, the same measure in a specific container (you may need to add the Font height, in pixels, of one line). When the text doesn't fit in the container, you need the show a vertical scrollbar, with offsets determined by the difference between container and text height. – Jimi Feb 09 '19 at 12:28
  • @Jimi The problem with MeasureString and MeasureText is that they do not take in account the white space (spaces, tabs and new lines) at the beginning and at the end of the text. – silviubogan Feb 09 '19 at 12:54
  • As a note, TextRenderer does measure both the standard space separator (char 32) and Tab (char 9) characthers and also their *implications*: [TextFormatFlags](https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.textformatflags). See, specifically, `ExpandTabs` and `TextBoxControl` flags. But you don't even need to use that class (and its flags, you can't do much without them). You just need the measure returned by `GetPositionFromCharIndex` to know how much, in pixels (the unit of measure you actually need), the text overflows the container. Your precision can be ±1 Pixel. – Jimi Feb 09 '19 at 13:35

0 Answers0