简单的代码高亮

    技术2022-05-19  20

    参考自http://www.360doc.com/content/07/1012/20/39836_806447.shtml

    在上面添加了注释,并且做了改进。

    改进点:

    1. 由keydown事件改为keyup事件。这样输入完就可以高亮,不需要输入完再敲空格之后才高亮

    2. 考虑到高亮之后,如果字符被修改。需要取消高亮。

     

      public partial class Form1 : Form

        {

            List<string> list = new List<string>();

     

            /// <summary>

            /// 初始化高亮关键字

            /// </summary>

            public void KeyWords()

            {

                list.Add("function");

                list.Add("return");

            }

     

            public Form1()

            {

                KeyWords();

                InitializeComponent();

            }

     

            private void richTextBox1_KeyUp(object sender, KeyEventArgs e)

            {

                string text = richTextBox1.Text;

                Regex regex = new Regex(@"/s*[a-zA-Z]+/s*", RegexOptions.RightToLeft); ///s代表空白字符,[a-zA-Z]代表a-z和A-Z中间的任意字符,因为字符输入是从左到右,所以

                //搜索的时候需要从右到左的搜索前面的字符

     

                string str = regex.Match(text, richTextBox1.SelectionStart).Value;//当前修改的最后一个词

     

                Regex regex2 = new Regex(@"/s*");

                str = regex2.Replace(str, ""); //把空格部分过滤掉

     

                int i = richTextBox1.SelectionStart; //记录当前位置

                if (list.IndexOf(str) > -1) //如果这个词属于高亮关键字

                {

                    richTextBox1.Select(richTextBox1.SelectionStart - str.Length, str.Length);

                    richTextBox1.SelectionColor = Color.Blue; //将关键词部分高亮置为蓝色

     

                    richTextBox1.Select(i, 0); //回到当前位置并重新回到黑色

                    richTextBox1.SelectionColor = Color.Black;

                }

                else //考虑到高亮之后,如果字符被修改则需要取消高亮。所以统一改背景色为黑

                {

                    richTextBox1.Select(richTextBox1.SelectionStart - str.Length, str.Length);

                    richTextBox1.SelectionColor = Color.Black;

                    richTextBox1.Select(i, 0);

                }

            }

        }

     

     


    最新回复(0)