问题
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