Color different parts of a RichTextBox string

前端 未结 9 771
暖寄归人
暖寄归人 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:40

    It`s work for me! I hope it will be useful to you!

    public static RichTextBox RichTextBoxChangeWordColor(ref RichTextBox rtb, string startWord, string endWord, Color color)
    {
        rtb.SuspendLayout();
        Point scroll = rtb.AutoScrollOffset;
        int slct = rtb.SelectionIndent;
        int ss = rtb.SelectionStart;
        List ls = GetAllWordsIndecesBetween(rtb.Text, startWord, endWord, true);
        foreach (var item in ls)
        {
            rtb.SelectionStart = item.X;
            rtb.SelectionLength = item.Y - item.X;
            rtb.SelectionColor = color;
        }
        rtb.SelectionStart = ss;
        rtb.SelectionIndent = slct;
        rtb.AutoScrollOffset = scroll;
        rtb.ResumeLayout(true);
        return rtb;
    }
    
    public static List GetAllWordsIndecesBetween(string intoText, string fromThis, string toThis,bool withSigns = true)
    {
        List result = new List();
        Stack stack = new Stack();
        bool start = false;
        for (int i = 0; i < intoText.Length; i++)
        {
            string ssubstr = intoText.Substring(i);
            if (ssubstr.StartsWith(fromThis) && ((fromThis == toThis && !start) || !ssubstr.StartsWith(toThis)))
            {
                if (!withSigns) i += fromThis.Length;
                start = true;
                stack.Push(i);
            }
            else if (ssubstr.StartsWith(toThis) )
            {
                if (withSigns) i += toThis.Length;
                start = false;
                if (stack.Count > 0)
                {
                    int startindex = stack.Pop();
                    result.Add(new Point(startindex,i));
                }
            }
        }
        return result;
    }
    

提交回复
热议问题