前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >在RichTextBox中对关键字进行高亮显示

在RichTextBox中对关键字进行高亮显示

作者头像
跟着阿笨一起玩NET
发布2018-09-18 15:28:18
2.2K0
发布2018-09-18 15:28:18
举报

实际效果如下:

相关代码如下:

代码语言:javascript
复制
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;

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

        private void HighLightText()
        {
            string[] keywords =   {"select","distinct","from","where","order","by","group","null"};
            string[] functions =   { "isnull", "count", "sum" };
            string[] strings =   { @"'((.|\n)*?)'" };
            string[] whiteSpace =   { "\t", "\n", "   " };

            rtbSql.SelectAll();
            rtbSql.SelectionColor = Color.Black;

            HighLightText(keywords, Color.Blue);
            HighLightText(functions, Color.Magenta);
            HighLightText(strings, Color.Red);
            HighLightText(whiteSpace, Color.Black);
        }

        private void HighLightText(string[] wordList, Color color)
        {
            foreach (string word in wordList)
            {
                Regex r = new Regex(word, RegexOptions.IgnoreCase);

                foreach (Match m in r.Matches(rtbSql.Text))
                {
                    rtbSql.Select(m.Index, m.Length);
                    rtbSql.SelectionColor = color;
                }
            }
        }   

        private void btnHighLight_Click(object sender, EventArgs e)
        {
            HighLightText();
        }
    }
}

若要实现更复杂的功能,可以研究一下这个C#的IDE编辑器的代码。http://www.icsharpcode.net/OpenSource/SD/Default.aspx

完整源码下载

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2006-08-25 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档