Selectively coloring text in RichTextBox

后端 未结 4 1854
深忆病人
深忆病人 2020-11-28 14:50

How can I paint in red every time I meet the letter \"A\" in RichTextBox?

4条回答
  •  孤街浪徒
    2020-11-28 15:26

    Try this:

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

    ...

    private void button1_Click(object sender, EventArgs e) {
      richTextBox1.Text = "Aardvarks are strange animals";
      HighlightPhrase(richTextBox1, "a", Color.Red);
    }
    

提交回复
热议问题