This还会在其他单词中显示某个单词的实例.因此,我不知道这是否适用于您需要它的目的,但除此之外,它应该能实现您想要的效果.
//I don't usually work with WinForms so idk if this is the correct way
//to do this or if you can use "sender" or "e" instead of "richTextBox1"
private void richTextBox_TextChanged(object sender, EventArgs e)
{
int tempint = richTextBox1.SelectionStart;
richTextBox1.Select(0, richTextBox1.TextLength);
richTextBox1.SelectionColor = Color.Black;
richTextBox1.Select(tempint, 0);
ColorLines(richTextBox1);
}
private void ColorLines(RichTextBox text)
{
string[] words = { "example", "hi"};
foreach (string word in words)
{
if (text.Text.Contains(word))
{
int index = -1;
int curselected = text.SelectionStart;
while ((index = text.Text.IndexOf(word, (index + 1))) != -1)
{
text.Select(index, word.Length);
text.SelectionColor = Color.Red;
text.Select(curselected, 0);
text.SelectionColor = Color.Black;
}
}
}
}
灵感来自this legends answer
这是另一个版本,它不会在其他单词中显示单词的实例,但当单词前面或后面有符号时,如","或"",则不起作用.没有空位.
private void richTextBox_TextChanged(object sender, EventArgs e)
{
int tempint = richTextBox1.SelectionStart;
richTextBox1.Select(0, richTextBox1.TextLength);
richTextBox1.SelectionColor = Color.Black;
richTextBox1.Select(tempint, 0);
ColorLines(richTextBox1);
}
private void ColorLines(RichTextBox text)
{
string[] words = { "example", "hi" };
int startindex = 0;
foreach (string word2 in text.Text.Split(' ').ToArray())
{
foreach (string word in words)
{
if (word == word2)
{
int curselected = text.SelectionStart;
int length = word2.Length;
text.Select(startindex, length);
text.SelectionColor = Color.Red;
text.Select(curselected, 0);
text.SelectionColor = Color.Black;
}
}
startindex += word2.Length + 1;
}
}