changing the background color of the selected text in an RTB

njuneardave

Newcomer
Joined
Sep 22, 2006
Messages
3
Hey,

I want to change the background color of the selected text in an rtb (not the WHOLE rtb background... just the background of the selection). I can't find any methods to do so in the C# library. Any ideas?


Thanks so much!
 
It's been a while since I dug into this so please bear with me. As I remember, you'll need to look into the RTF code and do some string manipulation to set the selected RTF backcolor. Here's the code that I adapted for setting and de-setting a highlight to the selected RTF.

Visual Basic:
    Private Sub Add_Highlight(rtf As RichTextBox)
        If rtf.SelectedText.Length <= 0 Then Exit Sub

        Try
            Dim strRTF As String = rtf.SelectedRtf
            Dim startpos As Integer = strRTF.IndexOf("\uc1") - 1
            Dim nextpos As Integer = strRTF.IndexOf("\pard\") + 6
            Dim strResult As String

            If strRTF.IndexOf("highlight1\") < 0 Then
                strResult = strRTF.Insert(nextpos, "highlight1\").Insert(startpos, HighlightBlackRtf(Color.Yellow))
                rtf.SelectedRtf = strResult
            Else 'if the text is already highlighted
                strResult = strRTF.Replace("{\colortbl;\red255\green255\blue0;}", "")
                strResult = strRTF.Replace("highlight1\", "")
                rtf.SelectedRtf = strResult
            End If

        Catch ex As Exception
            Console.WriteLine(ex.Message)
        End Try
    End Sub

    Private Function HighlightBlackRtf(ByVal c As Color) As String
        Dim strcol As String = "{\colortbl ;\red" & c.R & "\green" & c.G & "\blue" & c.B & ";}"
        Return strcol
    End Function

I hope this will help you.
 
Back
Top