突出显示 (select) 多行 TextBox 中的最后一行文本

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

我希望我的程序自动 select 多行文本框中的最后一行文本。
我已经尝试将以下代码添加到 select 文本框中的第一行:

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

如何修改上面的代码,以便在更改文本时自动 select 编辑最后一行?
我想我只需要更改上面代码片段中的第二行。

注意: TextBox 设置为只读,并通过单击 Button 填充文本。

您可以使用:

  • GetLineFromCharIndex()获取最后一行索引,以文本长度为参考
  • GetFirstCharIndexFromLine(),传递您从上次调用中收到的行号,以获取该行中第一个字符的索引
  • 调用Select()到select文本从最后一行的第一个字符索引开始到文本的长度,减去起始位置:

使用这种形式的 selection,当控件不包含任何文本时(即当文本为空字符串时),您不会有异常。
此外,您避免使用 Lines 属性:此值未缓存,因此每次使用时都需要对其进行评估,每次都解析 TextBoxBase 控件的全部内容。


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

► 由于您是使用按钮向 TextBox 控件添加文本,因此我建议将 TextBox/RichTextBox HideSelection 属性 设置为 False,否则您可能实际上没有看到 selected 文本。如果您不喜欢将 HideSelection 设置为 False,那么您需要在 Button.Click 处理程序中调用 [TextBox].Focus(),以查看突出显示的文本。

在这里,我将 sender 转换为 TextBoxBase (Dim tBox = DirectCast(sender, TextBoxBase)),因此您可以将此方法应用于任何其他 TextBox或 RichTextBox 而无需更改控件的名称。

  • TextBox 和 RichTextBox 类 都派生自 TextBoxBase,因此代码适用于两者
  • sender 参数表示引发事件的控件。