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

实际效果如下:

相关代码如下:
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
完整源码下载
posted @ 2006-08-25 02:01  Jailu  阅读(1615)  评论(0编辑  收藏  举报