DevExpress RichEditControl 文本高亮显示

DevExpress-RichEditControl文本高亮显示

  • 使用方法
  • 效果图:

使用方法

这里不废话了,创建winform窗体,添加RichEditControl控件(需要实现安装DevExpress),直接上代码:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using DevExpress.XtraRichEdit.API.Native;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

    private void Form1_Load(object sender, EventArgs e)
    {
        //修改默认字体
        DocumentRange range = richEditControl1.Document.Range;
        CharacterProperties cp = this.richEditControl1.Document.BeginUpdateCharacters(range);
        cp.FontName = "新宋体";
        cp.FontSize = 12;           
        this.richEditControl1.Document.EndUpdateCharacters(cp);
         //加载文件
        string filePath = @"D:\桌面\C#开发人员应该知道的13件事情.docx";  //这里换成自己的文件
        if (!string.IsNullOrEmpty(filePath))
        {
            richEditControl1.LoadDocument(filePath);//, DocumentFormat.Doc);
        }


        string a = "文件";
        //richEditControl1.Text = "11111111113333333333331111string111122222222欧阳23333333333333222string交警";
        List list = new List { "C#", "标准", "注意" };
        Showy(richEditControl1, a);
        Showy(richEditControl1, list);

    }


    //针对单个关键字
    private void Showy(DevExpress.XtraRichEdit.RichEditControl re, List strList)
    {
        string str = "";//要高亮的字段
        foreach (string item in strList)
        {
            if (strList.IndexOf(item) == 0)
                str = item;
            else
                str += "|" + item;
        }

        DocumentRange[] list = re.Document.FindAll(new System.Text.RegularExpressions.Regex(str));

        for (int i = 0; i < list.Length; i++)
        {
            CharacterProperties cp = re.Document.BeginUpdateCharacters(list[i]);

            cp.ForeColor = Color.Red;
            cp.BackColor = Color.Yellow;

            re.Document.EndUpdateCharacters(cp);

        }
    }

    //列表中多个关键字
    private void Showy(DevExpress.XtraRichEdit.RichEditControl re, string strList)
    {
        DocumentRange[] list = re.Document.FindAll(new System.Text.RegularExpressions.Regex(strList));

        for (int i = 0; i < list.Length; i++)
        {
            CharacterProperties cp = re.Document.BeginUpdateCharacters(list[i]);

            cp.ForeColor = Color.Red;

            re.Document.EndUpdateCharacters(cp);

        }
    }

}

}

效果图:

DevExpress RichEditControl 文本高亮显示_第1张图片

你可能感兴趣的:(.net,devexpress)