How to color a specific string/s in richTextBox TextChanged event ?

sharon glipman 441 Reputation points
2021-08-27T03:26:52.41+00:00

I have this method but it's not working at all in the TextChanged event not sure why.
This method is working fine for richTextBox with static text but it's not working in TextChanged event.

void HighlightPhrase(RichTextBox box, string phrase, Color color)
        {
            int pos = box.SelectionStart;
            string s = box.Text;
            for (int ix = 0; ix < s.Length; ix++)
            {
                int jx = s.IndexOf(phrase, ix, StringComparison.CurrentCultureIgnoreCase);
                if (jx < 0)
                {
                    break;
                }
                else
                {
                    box.SelectionStart = jx;
                    box.SelectionLength = phrase.Length;
                    box.SelectionColor = color;
                    ix = jx + 1;
                    results.Add(jx);
                }
            }
            box.SelectionStart = pos;
            box.SelectionLength = 0;
        }

So I tried to google and tried a lot of methods one of them is this :

This method is more or less working in the TextChanged event but after typing the chars ,, and it's coloring them in red than when I type letters the letters in black but than all the places with the chars ,, are blinking/flickering.

public void HighlightText(RichTextBox myRtb, string word, Color color)
        {

            if (word == string.Empty)
                return;

            int s_start = myRtb.SelectionStart, startIndex = 0, index;

            while ((index = myRtb.Text.IndexOf(word, startIndex)) != -1)
            {
                myRtb.Select(index, word.Length);
                myRtb.SelectionColor = color;

                startIndex = index + word.Length;
            }

            myRtb.SelectionStart = s_start;
            myRtb.SelectionLength = 0;
            myRtb.SelectionColor = Color.Black;
        }

Using it like that :

private void richTextBox2_TextChanged(object sender, EventArgs e)
        {
            if ((richTextBox2.Text != "" && textBoxRootDirectory.Text != "" &&
                Directory.Exists(textBoxRootDirectory.Text)) || richTextBox2.Text != "")
            {
                startButton.Enabled = true;
                Properties.Settings.Default["Setting2"] = richTextBox2.Text;
                Properties.Settings.Default.Save();
            }
            else
            {
                startButton.Enabled = false;
            }

            if (richTextBox2.Text.Contains(",,"))
            {
                CheckKeyword(richTextBox2, ",,", Color.Red,0);
            }
        }

I want the first method HighlightPhrase to work for all cases if just to color static/still text in richTextBox or in TextChanged event.

So far no matter what method I tried for the TextChanged event it didn't work fine. Either blinking/flickering or just not coloring or not coloring the right string/place.

In this case the goal is to color all the places I type the chars ,, and before and after if typing letters the letters should be in black only when typing ,, than only the ,, I typed should be in red. The rest that I type letters or chars that are not ,, to be in black and when I type ,, it should be double , and , like ,, if you type only one , it should be black only if it's two ,, as one string than make it red.

I'm using the chars ,, to separate parts in the richTextBox and it's working fine but no I want to color this chars ,,

Developer technologies Windows Forms
Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.5K Reputation points
    2021-08-27T07:35:23.767+00:00

    If you want to colour all of “,,” in red, then consider this approach:

    bool IsColouring = false;
    
    private void richTextBox1_TextChanged( object sender, EventArgs e )
    {
       if( IsColouring ) return;
    
       IsColouring = true;
    
       try
       {
          Highlight( );
       }
       finally
       {
          IsColouring = false;
       }
    }
    
    
    void Highlight( )
    {
       const int WM_SETREDRAW = 0x000B;
    
       SendMessage( richTextBox1.Handle, WM_SETREDRAW, IntPtr.Zero, IntPtr.Zero );
    
       var sel_start = richTextBox1.SelectionStart;
       var sel_len = richTextBox1.SelectionLength;
    
       richTextBox1.SelectAll( );
       richTextBox1.SelectionColor = Color.Black;
    
       int p = 0;
       while( ( p = richTextBox1.Find( ",,", p, RichTextBoxFinds.None ) ) >= 0 )
       {
          richTextBox1.SelectionStart = p;
          richTextBox1.SelectionLength = 2;
          richTextBox1.SelectionColor = Color.Red;
    
          p += 1;
       }
    
       richTextBox1.SelectionStart = sel_start;
       richTextBox1.SelectionLength = sel_len;
    
       SendMessage( richTextBox1.Handle, WM_SETREDRAW, new IntPtr( 1 ), IntPtr.Zero );
       richTextBox1.Invalidate( );
    }
    
    [DllImport( "user32" )]
    private extern static IntPtr SendMessage( IntPtr hWnd, int msg, IntPtr wp, IntPtr lp );
    

    Adjust the names.

    It also uses a technique described here: https://social.msdn.microsoft.com/Forums/windows/en-US/a6abf4e1-e502-4988-a239-a082afedf4a7.

    2 people found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Castorix31 90,521 Reputation points
    2021-08-27T06:33:44.537+00:00

    Most of samples/methods from Google don't work fine (for example when you cut a colored word)

    But this sample seems to work correctly : Fast Colored TextBox for Syntax Highlighting

    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.