VB.NET search in richtextbox

manuel angeli 40 Reputation points
2023-09-19T15:03:17.3333333+00:00

Hello everyone!!!

Do you know if there is a way, within a richtextbox, to select all text with a particular formatting?

For example I would like to select all text in bold or all text in red ... (and after remove formatting)

Thanks in advance to everyone.

Developer technologies VB
0 comments No comments
{count} votes

Accepted answer
  1. Jiachen Li-MSFT 34,221 Reputation points Microsoft External Staff
    2023-09-21T03:50:38.55+00:00

    Hi @manuel angeli ,

    After my tests, Color.Aqua and Color.Cyan are both the same color #FF00FFFF, and use txt_note.SelectionBackColor always gets Color.Aqua when getting the background color, so you should use the following code to determine the background color.

                If txt_note.SelectionBackColor = Color.Aqua Then
                    txt_note.Select(i + 1, 1)
                    txt_note.SelectionBackColor = Color.Green
                End If
    

    Best Regards.

    Jiachen Li


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

4 additional answers

Sort by: Most helpful
  1. Anonymous
    2023-09-19T20:01:28.7133333+00:00

    Hi

    Here is some code that may be helpful. This is a stand alone example and you need to try it before using it. To try it, start a new test Project, on Form1 put a RichTextBox named RTB, a default ComboBox1, Button1 and a ContextMenuStrip with "RED, LIGHT BLUE, GREEN and WHITE" items on it.

    The idea here is: user selects a word and a colour from the ComboBox then clicks the 'CUT" button. With luck, all words matching selected word and matching selected colour will disappear.

    There are lots of variations possible, this being one of them.

    There is also a ContextMenu to enable a colour selection (just a simple choice) for testing purposes. Just select a word or some text and then right click for the colour choices. (colour options would normally be much more comprehensive in a real world application)

    111

    Option Strict On
    Option Explicit On
    Public Class Form1
    	Dim path As String = IO.Path.Combine(Application.StartupPath, "RTB.rtf")
    	Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
    
    		' if you want to save on close - uncomment
    		RTB.SaveFile(path, RichTextBoxStreamType.RichText)
    	End Sub
    	Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    		With RTB
    			' to load previously saved text - uncomment
    			'If IO.File.Exists(path) Then
    			'	.LoadFile(path)
    			'End If
    
    			.ContextMenuStrip = ContextMenuStrip1
    			.ShowSelectionMargin = True
    			.ZoomFactor = 2.5
    
    			' some sample text for testing with
    			.Text = "This Is some example text To illustrate the slow unreliable way To Select And delete all words which have a given text colour.
    
    There may well be other ways To Do this which may also be far better than this way, but I have never noticed them in the past."
    		End With
    
    		With ComboBox1
    			.Items.AddRange({"RED", "LIGHT BLUE", "GREEN", "WHITE"})
    			.SelectedIndex = 0
    		End With
    	End Sub
    
    	Private Sub ContextMenu_Click(sender As Object, e As EventArgs) Handles REDToolStripMenuItem.Click, LIGHTBLUEToolStripMenuItem.Click, GREENToolStripMenuItem.Click, WHITEToolStripMenuItem.Click
    
    		Dim cm As ToolStripMenuItem = DirectCast(sender, ToolStripMenuItem)
    
    		Select Case cm.Text
    			Case "RED"
    				RTB.SelectionColor = Color.Red
    			Case "LIGHT BLUE"
    				RTB.SelectionColor = Color.LightBlue
    			Case "GREEN"
    				RTB.SelectionColor = Color.Green
    			Case "WHITE"
    				RTB.SelectionColor = Color.White
    		End Select
    	End Sub
    
    	Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    		Dim s As String = ComboBox1.SelectedItem.ToString
    
    		Select Case ComboBox1.SelectedItem.ToString
    			Case "RED"
    				CutWords(Trim(RTB.SelectedText), Color.Red)
    			Case "LIGHT BLUE"
    			Case "GREEN"
    			Case "WHITE"
    
    		End Select
    	End Sub
    	Sub CutWords(s As String, c As Color)
    
    		Dim words() As String = RTB.Text.Split(New String() {" ", ".", ",", vbLf, vbCr}, StringSplitOptions.RemoveEmptyEntries)
    
    		Dim inx As Integer = 0
    		For Each w As String In words
    			If w = s Then
    				inx = RTB.Text.IndexOf(w, inx + 1)
    				RTB.Select(inx, w.Length)
    				If RTB.SelectionColor = c Then
    					RTB.Cut()
    				End If
    			End If
    		Next
    	End Sub
    End Class
    
    0 comments No comments

  2. manuel angeli 40 Reputation points
    2023-09-20T07:50:02.0333333+00:00

    Hi Les, thank's for your replay!
    I'll try starting by showing you the code I started with (it works pretty well), look for all bold text and change the background color to red.

    For i As Integer = 0 To txt_note.Text.Length - 1
        txt_note.Select(i, 1)
        If txt_note.SelectionFont.Bold Then
            txt_note.Select(i + 1, 1)
            txt_note.SelectionBackColor = Color.Green
        End If
    Next
    

    Now I simply tried to replace this line:

    If txt_note.SelectionFont.Bold Then
    

    By changing the code in this way:

    For i As Integer = 0 To txt_note.Text.Length - 1
        txt_note.Select(i, 1)
        If txt_note.SelectionBackColor = Color.Cyan Then
            txt_note.Select(i + 1, 1)
            txt_note.SelectionBackColor = Color.Green
        End If
    Next
    

    ... but it doesn't work...

    as you can tell from the code, what I need to do is look for text with background color (highlighted) cyan and change it to another color.

    can this be a right approach what I am doing?


  3. Dewayne Basnett 1,381 Reputation points
    2023-09-20T14:02:35.1566667+00:00

    I have a form with a RTB and a button. Here is the code I used to setup the RTB to have some bold text.

        ' RTB contents
        ' Lorem ipsum dolor sit amet, appetere senserit voluptaria cu mei. Vel everti repudiandae ne, mel eu ignota malorum! 
        ' Te voluptua prodesset pro, nostrum offendit ad per. Iisque invenire assentior usu in, et simul populo labitur ius! 
        ' Eos et reque eleifend eloquentiam.
    
        Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
            'random setup for testing, bold some text
            Dim bf As New Font(RichTextBox1.Font.Name, RichTextBox1.Font.Size, FontStyle.Bold)
            Dim bold() As String = {"ipsum", "nostrum"}
            For Each wd As String In bold
                Dim i As Integer = 0
                Do
                    i = RichTextBox1.Find(wd, i, RichTextBoxFinds.None)
                    If i >= 0 Then
                        RichTextBox1.Select(i, wd.Length)
                        RichTextBox1.SelectionFont = bf
                        i += 1
                    End If
                Loop While i >= 0
            Next
        End Sub
    
    

    The button code highlights the bold text in yellow.

        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim strtBold As Integer = -1
            Dim lenBold As Integer = 0
            For x As Integer = 0 To RichTextBox1.TextLength - 1
                RichTextBox1.Select(x, 1)
                If RichTextBox1.SelectionFont.Bold Then
                    If strtBold < 0 Then
                        strtBold = x
                    End If
                    lenBold += 1
                ElseIf strtBold >= 0 Then
                    RichTextBox1.Select(strtBold, lenBold)
                    RichTextBox1.SelectionBackColor = Color.Yellow
                    strtBold = -1
                    lenBold = 0
                End If
            Next
        End Sub
    
    
    0 comments No comments

  4. Dewayne Basnett 1,381 Reputation points
    2023-09-21T13:51:38.1133333+00:00

    Another approach that can be used for numerous conditions. I have shown bold and italic, but could be adapted for color.

        Public Class RTBSpec
            Public Property isBold As Boolean = False
            Public Property isItalic As Boolean = False
            Public Property StartPos As Integer = -1
            Public Property Length As Integer = 0
        End Class
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim Specs As New List(Of RTBSpec)
            Dim curBold As RTBSpec
            Dim curItal As RTBSpec
            For x As Integer = 0 To RichTextBox1.TextLength - 1
                RichTextBox1.Select(x, 1)
                If RichTextBox1.SelectionFont.Bold Then 'bold
                    If curBold Is Nothing Then
                        curBold = New RTBSpec
                        curBold.isBold = True
                        curBold.StartPos = x
                        Specs.Add(curBold)
                    End If
                    curBold.Length += 1
                ElseIf curBold IsNot Nothing Then
                    curBold = Nothing
                End If
                If RichTextBox1.SelectionFont.Italic Then 'italic
                    If curItal Is Nothing Then
                        curItal = New RTBSpec
                        curItal.isItalic = True
                        curItal.StartPos = x
                        Specs.Add(curItal)
                    End If
                    curItal.Length += 1
                ElseIf curItal IsNot Nothing Then
                    curItal = Nothing
                End If
            Next
            For Each rtbS As RTBSpec In Specs
                RichTextBox1.Select(rtbS.StartPos, rtbS.Length)
                If rtbS.isItalic Then
                    RichTextBox1.SelectionColor = Color.Green
                ElseIf rtbS.isBold Then
                    RichTextBox1.SelectionBackColor = Color.Yellow
                End If
            Next
        End Sub
    
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.