编辑 1 行时保留 richtextbox 格式

Preserving richtextbox formatting when editing 1 line

我有一个记录到 richtextbox 的程序,日志根据 error/event 进行颜色编码。

以下是我如何使用默认样式向我的日志中添加文本。

rtbLogs.AppendText("Log Text")    

下面是我如何在文本着色时添加文本。

rtbLogs.Select(rtbLogs.TextLength, 0)
rtbLogs.SelectionFont = New Font(rtbLogs.Font, FontStyle.Regular)
rtbLogs.SelectionColor = Color.Red 'Settings the font styles
rtbLogs.AppendText("Error Text")
rtbLogs.SelectionFont = rtbLogs.Font
rtbLogs.SelectionColor = rtbLogs.ForeColor 'reset style to default

现在有时我需要更新日志中的 1 行,编辑后所有格式都消失了。编辑下一个日志后,我添加了我想要的格式,但如果我编辑 1 行又消失了。

下面是我编辑一行的方法。

Dim lines() As String = Me.rtbLogs.Lines
lines(5) = "Updated Text"
Me.rtbLogs.Lines = lines

如何保留格式?

可能是这样的

Me.rtbLogs.Rtf = Me.rtbLogs.Rtf.Replace(Me.rtbLogs.Lines(5), "Updated Text")