How can I scroll to a specified line in a WinForms TextBox using C#?

后端 未结 4 1292
花落未央
花落未央 2020-12-17 17:24

How can I scroll to a specified line in a WinForms TextBox using C#?

Thanks

4条回答
  •  轮回少年
    2020-12-17 17:31

    Here's how you scroll to the selection:

    textBox.ScrollToCaret();
    

    To scroll to a specified line, you could loop through the TextBox.Lines property, total their lengths to find the start of the specified line and then set TextBox.SelectionStart to position the caret.

    Something along the lines of this (untested code):

    int position = 0;
    
    for (int i = 0; i < lineToGoto; i++)
    {
        position += textBox.Lines[i].Length;
    }
    
    textBox.SelectionStart = position;
    
    textBox.ScrollToCaret();
    

提交回复
热议问题