我想创建一个简单的文本编辑器,但像“编译器”一样支持多色字体
假设我的程序关键字是:“狗”,“牛”,“猫”,“鸟”
我有一个实现 TextChanged 事件的 RichTextBox。
现在,我的问题是我不知道如何在遇到关键字时更改字体颜色。
示例字符串:一只大狗和一只猫
狗是红色的,而猫是绿色的。
最佳答案
我不确定当你有大量文本时这会有多有效,但在我测试过的范围内它工作得相当好。
private void CheckKeyword(string word, Color color, int startIndex)
{
if (this.richTextBox1.Text.Contains(word))
{
int index = -1;
int selectStart = this.richTextBox1.SelectionStart;
while ((index = this.richTextBox1.Text.IndexOf(word, (index + 1))) != -1)
{
this.richTextBox1.Select((index + startIndex), word.Length);
this.richTextBox1.SelectionColor = color;
this.richTextBox1.Select(selectStart, 0);
this.richTextBox1.SelectionColor = Color.Black;
}
}
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
this.CheckKeyword("dog", Color.Red, 0);
this.CheckKeyword("cat", Color.Green, 0);
}
关于c# - 当用户在 RichTextBox 中键入时更改字体颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6729787/