【问题标题】:Highlight (select) the last line of text in a multiline TextBox突出显示(选择)多行文本框中的最后一行文本
【发布时间】:2020-05-13 13:03:58
【问题描述】:

我希望我的程序自动选择多行文本框中的最后一行文本。
我尝试了以下代码来选择 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

如何修改上面的代码,以便在文本更改时自动选择最后一行?
我想我只需要更改上面代码 sn -p 中的第二行。

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

【问题讨论】:

    标签: vb.net winforms textbox


    【解决方案1】:

    你可以使用:

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

    使用这种选择形式,当控件不包含任何文本时(即文本为空字符串时),您将不会出现异常。
    此外,您避免使用 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
    

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-27
      • 2023-04-04
      • 2014-08-15
      • 2013-09-10
      • 2013-09-30
      • 2012-02-22
      • 2020-01-15
      • 2012-09-19
      相关资源
      最近更新 更多