RichtextBox中的颜色​​特定单词

我怎么能做到,当用户在富文本框中键入“while”或“if”等特定单词时,单词会变成紫色而没有任何问题? 我尝试了不同的代码,但没有一个是可用的。 代码如下:

if (richTextBox.Text.Contains("while")) { richTextBox.Select(richTextBox.Text.IndexOf("while"), "while".Length); richTextBox.SelectionColor = Color.Aqua; } 

此外,我希望当用户删除单词或从单词中删除一个字母时,单词将恢复为默认颜色。 我正在制作一个带有代码编辑器的程序。

我正在使用Visual c#。

谢谢。

将事件添加到您更改的富文本框中,

  private void Rchtxt_TextChanged(object sender, EventArgs e) { this.CheckKeyword("while", Color.Purple, 0); this.CheckKeyword("if", Color.Green, 0); } private void CheckKeyword(string word, Color color, int startIndex) { if (this.Rchtxt.Text.Contains(word)) { int index = -1; int selectStart = this.Rchtxt.SelectionStart; while ((index = this.Rchtxt.Text.IndexOf(word, (index + 1))) != -1) { this.Rchtxt.Select((index + startIndex), word.Length); this.Rchtxt.SelectionColor = color; this.Rchtxt.Select(selectStart, 0); this.Rchtxt.SelectionColor = Color.Black; } } } 

这是你可以做的事情,我建议使用正则表达式来查找单词的所有匹配,以防它多次出现。 还要记住,字符串查找可以是for循环的一个字符串列表,以考虑多个单词,但这应该让你开始。

 //dont foget to use this at the top of the page using System.Text.RegularExpressions; private void richTextBox1_TextChanged(object sender, EventArgs e) { string find = "while"; if (richTextBox1.Text.Contains(find)) { var matchString = Regex.Escape(find); foreach (Match match in Regex.Matches(richTextBox1.Text, matchString)) { richTextBox1.Select(match.Index, find.Length); richTextBox1.SelectionColor = Color.Aqua; richTextBox1.Select(richTextBox1.TextLength, 0); richTextBox1.SelectionColor = richTextBox1.ForeColor; }; } } 

您可以使用richTextBox1_KeyDown事件

 private void richTextBox1_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Space) { String abc = this.richTextBox1.Text.Split(' ').Last(); if (abc == "while") { int stIndex = 0; stIndex = richTextBox1.Find(abc, stIndex, RichTextBoxFinds.MatchCase); richTextBox1.Select(stIndex, abc.Length); richTextBox1.SelectionColor = Color.Aqua; richTextBox1.Select(richTextBox1.TextLength, 0); richTextBox1.SelectionColor = richTextBox1.ForeColor; } } }