且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

突出显示(选择)多行文本框中的最后一行文本

更新时间:2023-12-04 13:27:46

您可以使用:

  • GetLineFromCharIndex()获取最后一行索引,使用文本长度作为参考
  • GetFirstCharIndexFromLine(),传递您从上次调用中收到的行号,以获取该行中第一个字符的索引
  • 调用 Select() 选择从最后一行的第一个字符索引开始到文本长度减去起始位置的文本:
  • 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:

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

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

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

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

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

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.

  • TextBox 和 RichTextBox 类都从 TextBoxBase 派生,因此代码适用于两者
  • sender 参数表示引发事件的控件.
  • 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.