WinForm richtextbox 关键字变红色

时间:2022-01-15 02:09:20


        private void HilightRichText(RichTextBox control, string hilightString)
        {
            int nSelectStart = control.SelectionStart;  
            int nSelectLength = control.SelectionLength;
            int nIndex = 0;
            while (nIndex < control.Text.Length)
            {
                nIndex = control.Find(hilightString, nIndex, RichTextBoxFinds.WholeWord); //整个文档查找
                if (nIndex < 0)
                {
                    break;                     
                }
                control.Select(nIndex, hilightString.Length);      //选择文本
                control.SelectionColor = Color.Red;
                nIndex += hilightString.Length;
            }
            control.Select(nSelectStart, nSelectLength);
        }

WinForm richtextbox 关键字变红色