Color different parts of a RichTextBox string

前端 未结 9 643
暖寄归人
暖寄归人 2020-11-22 08:10

I\'m trying to color parts of a string to be appended to a RichTextBox. I have a string built from different strings.

string temp = \"[\" + DateTime.Now.ToSh         


        
9条回答
  •  囚心锁ツ
    2020-11-22 08:39

    I created this Function after researching on the internet since I wanted to print an XML string when you select a row from a data grid view.

    static void HighlightPhrase(RichTextBox box, string StartTag, string EndTag, string ControlTag, Color color1, Color color2)
    {
        int pos = box.SelectionStart;
        string s = box.Text;
        for (int ix = 0; ; )
        {
            int jx = s.IndexOf(StartTag, ix, StringComparison.CurrentCultureIgnoreCase);
            if (jx < 0) break;
            int ex = s.IndexOf(EndTag, ix, StringComparison.CurrentCultureIgnoreCase);
            box.SelectionStart = jx;
            box.SelectionLength = ex - jx + 1;
            box.SelectionColor = color1;
            
            int bx = s.IndexOf(ControlTag, ix, StringComparison.CurrentCultureIgnoreCase);
            int bxtest = s.IndexOf(StartTag, (ex + 1), StringComparison.CurrentCultureIgnoreCase);
            if (bx == bxtest)
            {
                box.SelectionStart = ex + 1;
                box.SelectionLength = bx - ex + 1;
                box.SelectionColor = color2;
            }
            
            ix = ex + 1;
        }
        box.SelectionStart = pos;
        box.SelectionLength = 0;
    }
    

    and this is how you call it

       HighlightPhrase(richTextBox1, "<", ">","

提交回复
热议问题