How to use TextBox.GetPositionFromCharIndex to show the vertical scrollbar only when needed?

陌路散爱 提交于 2020-02-07 05:59:35

问题


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

来源:https://stackoverflow.com/questions/54605400/how-to-use-textbox-getpositionfromcharindex-to-show-the-vertical-scrollbar-only

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