将此答案用作结果的参考:
How to color different words with different colors in a RichTextBox
此类对象用于跟踪要着色的单词以及在写入或更改其中一个单词时要使用的相关颜色:
(链接的答案解释了如何用单词和相关颜色填充列表)
public class ColoredWord
{
public string Word { get; set; }
public Color WordColor { get; set; }
}
public List<ColoredWord> ColoredWords = new List<ColoredWord>();
在RichTextBoxKeyUp()事件中,检查列表中的单词是否被插入或修改:
这里我使用了KeyUp() 事件,因为在它被引发的那一刻,这个词已经被插入/修改了。
private void richTextBox1_KeyUp(object sender, KeyEventArgs e)
{
if ((e.KeyCode >= Keys.Left & e.KeyCode <= Keys.Down)) return;
if (e.KeyCode == Keys.ShiftKey || e.KeyCode == Keys.Alt || e.KeyCode == Keys.ControlKey) return;
int CurrentPosition = richTextBox1.SelectionStart;
int[] WordStartEnd;
string word = GetWordFromPosition(richTextBox1, CurrentPosition - 1, out WordStartEnd);
ColoredWord result = ColoredWords.FirstOrDefault(s => s.Word == word.ToUpper());
SetSelectionColor(richTextBox1, result, CurrentPosition, WordStartEnd);
if (e.KeyCode == Keys.Space && result == null)
{
word = GetWordFromPosition(richTextBox1, CurrentPosition + 1, out WordStartEnd);
result = ColoredWords.FirstOrDefault(s => s.Word == word.ToUpper());
SetSelectionColor(richTextBox1, result, CurrentPosition, WordStartEnd);
}
}
这些是用于在单词包含在列表中时为单词着色以及从当前插入符号位置提取单词的辅助方法。
当一个已经着色的单词被空格字符分割,因此两端失去它们的颜色,在KeyUp()事件中处理(代码部分是:if (e.KeyCode == Keys.Space && result == null)。
private void SetSelectionColor(RichTextBox ctl, ColoredWord word, int Position, int[] WordStartEnd)
{
ctl.Select(WordStartEnd[0], WordStartEnd[1]);
if (word != null)
{
if (ctl.SelectionColor != word.WordColor)
ctl.SelectionColor = word.WordColor;
}
else
{
if (ctl.SelectionColor != ctl.ForeColor)
ctl.SelectionColor = ctl.ForeColor;
}
ctl.SelectionStart = Position;
ctl.SelectionLength = 0;
ctl.SelectionColor = richTextBox1.ForeColor;
}
private string GetWordFromPosition(RichTextBox ctl, int Position, out int[] WordStartEnd)
{
int[] StartEnd = new int[2];
StartEnd[0] = ctl.Text.LastIndexOf((char)Keys.Space, Position - 1) + 1;
StartEnd[1] = ctl.Text.IndexOf((char)Keys.Space, Position);
if (StartEnd[1] == -1) StartEnd[1] = ctl.Text.Length;
StartEnd[1] -= StartEnd[0];
WordStartEnd = StartEnd;
return ctl.Text.Substring(StartEnd[0], StartEnd[1]);
}