首页 > 解决方案 > 如何使用特定字符连接 RichTextBox 中的选定行并替换现有行?

问题描述

我想加入 RichTextBox 中的选定行并将这两行与特定字符分开。

The situation is dire
But momma raised up a fighter
It's all come down to the wire
But the come-up is higher

结果:

The situation is dire - But momma raised up a fighter

或者

It's all come down to the wire - But the come-up is higher

生成的新行应替换控件中的现有行。

标签: vb.netwinformsrichtextbox

解决方案


尝试这个:

Dim StartSelection As Integer = RichTextBox1.SelectionStart
    Dim EndSelection As Integer = RichTextBox1.SelectionStart + RichTextBox1.SelectionLength
    Dim StartLine As Integer = 0
    Dim EndLine As Integer = 0
    Dim Position As Integer = 0
    Dim Pos As Integer = 0
    Dim Index As Integer = 0

    For i = 0 To RichTextBox1.Lines.Length - 1
        Position += RichTextBox1.Lines(i).Length
        If StartSelection <= Position Then
            StartLine = i
            Exit For
        End If
    Next
    Position = 0
    For i = 0 To RichTextBox1.Lines.Length - 1
        Position += RichTextBox1.Lines(i).Length
        If Position >= EndSelection Then
            EndLine = i
            Exit For
        End If
    Next
    If EndLine = 0 Then
        EndLine = RichTextBox1.Lines.Length - 1
    Else
        EndLine -= 1
    End If
    If Not StartLine = EndLine Then
        Do
            Pos += RichTextBox1.Lines(Index).Length

            If Index = StartLine Then
                Exit Do
            Else
                Index += 1
            End If
        Loop
        Pos -= RichTextBox1.Lines(Index).Length
        For i = StartLine To EndLine - 1
            If i = StartLine Then
                RichTextBox1.Text = RichTextBox1.Text.Remove(Pos + RichTextBox1.Lines(Index).Length + i, 1).Insert(Pos + RichTextBox1.Lines(Index).Length + i, " - ")
                RichTextBox1.Refresh()
            Else
                RichTextBox1.Text = RichTextBox1.Text.Remove(Pos + RichTextBox1.Lines(Index).Length + StartLine, 1).Insert(Pos + RichTextBox1.Lines(Index).Length + StartLine, " - ")
                RichTextBox1.Refresh()
            End If
        Next
    End If

我建议将代码放在 Textbox 或 RichTextbox 的鼠标向上事件中。


推荐阅读