Highlight (select) the last line of text in a multiline TextBox

我只是一个虾纸丫 提交于 2021-01-05 07:15:48

问题


I want my program to automatically select the last line of text in a multiline TextBox.
I've tried the following code to select the first line in the TextBox:

Private Sub TextBoxLog_TextChanged(sender As Object, e As EventArgs) Handles TextBoxLog.TextChanged
   Dim Line As Integer = TextBoxLog.GetLineFromCharIndex(TextBoxLog.Lines.GetLowerBound(0))
   Dim lineLength As Integer = TextBoxLog.Lines(Line).Length
   TextBoxLog.SelectionStart = TextBoxLog.GetLineFromCharIndex(Line)
   TextBoxLog.SelectionLength = lineLength
End Sub

How can I modify the above code so that the last line is automatically selected when the text is changed?
I think I just need to change the second line in the above code snippet.

Note: The TextBox is set to read-only and is filled with text by Button clicks.


回答1:


You can use:

  • GetLineFromCharIndex() to get the last line index, using the text length as reference
  • GetFirstCharIndexFromLine(), passing the line number you received from the previous call, to get the index of the first char in that line
  • call Select() to select text starting from the first char index of the last line to the length of the text, minus the starting position:

Using this form of selection, you won't have exceptions when the Control doesn't contain any text (i.e., when the text is an empty string).
Also, you avoid to use the Lines property: this value is not cached, so it needs to be evaluated each time you use it, parsing - each time - the whole content of a TextBoxBase control.


Private Sub TextBoxLog_TextChanged(sender As Object, e As EventArgs) Handles TextBoxLog.TextChanged
    Dim tBox = DirectCast(sender, TextBoxBase)
    Dim lastLine As Integer = tBox.GetLineFromCharIndex(tBox.TextLength)
    Dim lineFirstIndex As Integer = tBox.GetFirstCharIndexFromLine(lastLine)
    tBox.Select(lineFirstIndex, tBox.TextLength - lineFirstIndex)
End Sub

► Since you're adding text to the TextBox control using a Button, I suggest to set the TextBox/RichTextBox HideSelection property to False, otherwise you may not actually see the selected text. If you don't like to have HideSelection set to False, then you need to call [TextBox].Focus(), in the Button.Click handler, to see the text highlighted.

Here, I'm casting sender to TextBoxBase (Dim tBox = DirectCast(sender, TextBoxBase)), so you can adapt this method to any other TextBox or RichTextBox without changing the name of the Control.

  • Both the TextBox and RichTextBox classes derive from TextBoxBase, so the code works for both
  • The sender argument represents the Control that raised the event.


来源:https://stackoverflow.com/questions/61775395/highlight-select-the-last-line-of-text-in-a-multiline-textbox

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