向文本框里输入一段字符串,文本框可以根据输入的单词自动判断该字体是什么颜色。
比如:输入“SELECT * FROM Student”,然后SELECT ,FROM 会显示兰色,而其他的单词都是黑色的。怎么办?
请大家多多指教。

解决方案 »

  1.   

    private void richTextBox_CodeArea_TextChanged(object sender, EventArgs e)
        {
            RichTextBox rbx = (RichTextBox)sender;
            int start, length;
            int ins = this.richTextBox_CodeArea.SelectionStart;        char c = ' ';
            string word = "";
            if (ins > 0)
            {
                c = this.richTextBox_CodeArea.Text[ins - 1];
            }
            else
            {
                if (this.richTextBox_CodeArea.Text.Length > 0)
                {
                    c = this.richTextBox_CodeArea.Text[0];
                }
            }        //取得插入点两边的两个单词,并判断这两个单词是否是关键字.
            if (!char.IsLetter(c) && !Char.IsDigit(c) && c != '_')
            {
                //将字符c染色
                this.Dye(ins - 1, 1, this.textColor, this.textColor);            word = this.GetCurrentWord(ins - 1, out start, out length);            Color cl = IsKey(word) ? this.keyColor : this.textColor;
                this.Dye(start, length, cl, this.textColor);            word = this.GetCurrentWord(ins + 1, out start, out length);
                cl = IsKey(word) ? this.keyColor : this.textColor;
                this.Dye(start, length, cl, this.textColor);        }
            else//取得插入点处的单词并判断其是否是关键字
            {
                word = this.GetCurrentWord(ins, out start, out length);
                Color cl = IsKey(word) ? this.keyColor : this.textColor;
                this.Dye(start, length, cl, this.textColor);
            }    }
      

  2.   

    转自  http://www.cnblogs.com/zhouyinhui/archive/2006/06/10/422045.aspx
      

  3.   

    用RichTextBox处理,参考如下代码private void richTextBox1_TextChanged(object sender, EventArgs e)
    {
        int vSelectionStart = richTextBox1.SelectionStart; // 记忆光标位置
        int vSelectionLength = richTextBox1.SelectionLength;
        richTextBox1.SelectAll(); // 设置整体颜色
        richTextBox1.SelectionColor = SystemColors.WindowText;
        string[] vWords = new string[] { "select", "from", "where", "and",
            "or", "order", "by" };
        foreach (string vWord in vWords)
        {
            int j = richTextBox1.Find(vWord, 0, -1, RichTextBoxFinds.WholeWord); // 查询关键字的位置并选中
            int i = -1;
            while (j > i) // 没有找到下一个
            {
                richTextBox1.SelectionColor = Color.Blue;
                i = j;
                j = richTextBox1.Find(vWord, i + vWord.Length,
                    -1, RichTextBoxFinds.WholeWord); // 查询下一个
            }
        }
        richTextBox1.SelectionStart = vSelectionStart; // 恢复光标位置
        richTextBox1.SelectionLength = vSelectionLength;
    }
      

  4.   

    http://www.codeproject.com/cs/miscctrl/SyntaxRichTextBox.asp