【问题标题】:How to append lines of text into a Richtextbox at specific location/index?如何在特定位置/索引处将文本行附加到 Richtextbox 中?
【发布时间】:2020-06-08 21:14:43
【问题描述】:

我有一个 lua 脚本文件,我想在其中的特定位置添加一些新行。 因此,假设我们有以下文本作为示例:

line 1
line 2
line 3

line 8
line 9
line 10

我想在 第 3 行 之后插入一些新行,并在 第 8 行 之前插入几行 到目前为止,我已经尝试为这些行编制索引,但没有找到一种方法来使用这些索引来编写新的文本行。

 For i As Integer = 0 To textbox.Lines.Count - 1
    Dim x As Integer = i + 1
    Dim y As Integer = i - 1
    If textbox.Lines(i).Contains("line 3") Then
        textbox.Lines(x).Append("Line 4")
    End If
 Next

【问题讨论】:

  • textbox.GetFirstCharIndexFromLine 可能是您想要查看的内容。只需在您的字符串中添加 Environment.NewLine,使用 textbox.Select(range) 方法,然后使用 textbox.SelectedText = "something" 在循环遍历文本时小心修改文本。向后循环可能会更安全,以避免索引混乱。

标签: vb.net winforms richtextbox


【解决方案1】:

如果其他人遇到同样的障碍,我发现使用输入/输出库和线程库Imports System.IO,Imports System.Threading,结合以下for循环可以获得所需的结果:

For i As Integer = 0 To textbox.Lines.Length - 1
        Dim s As String = textbox.Lines(i)
        Dim index As Integer = s.IndexOf("line 3")
        If index > -1 Then
            Dim length As Integer = s.Length - index
            index += textbox.GetFirstCharIndexFromLine(i)
            textbox.Select(index + length, 1)
            Thread.Sleep(1)
            SendKeys.SendWait("{ENTER}")
            textbox.Text = textbox.Text.Insert(textbox.GetFirstCharIndexOfCurrentLine,
                                       "line 4" & vbCrLf &
                                       "line 5 " & vbCrLf &
                                       "line 6" & vbCrLf &
                                       "line 7" & vbCrLf)
        End If
    Next

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-22
    • 1970-01-01
    • 2020-10-30
    • 1970-01-01
    • 1970-01-01
    • 2011-08-18
    • 1970-01-01
    相关资源
    最近更新 更多