【发布时间】:2011-07-18 07:24:53
【问题描述】:
我想创建一个简单的文本编辑器,但支持像“编译器”这样的多色字体
假设我的程序关键字是:"dog","cow","cat","bird"
我有一个实现 TextChanged 事件的 RichTextBox。
现在,我的问题是遇到关键字时不知道如何更改字体颜色。
示例字符串:A Big Dog and a Cat
狗是红色,猫是绿色。
【问题讨论】:
标签: c# .net winforms richtextbox
我想创建一个简单的文本编辑器,但支持像“编译器”这样的多色字体
假设我的程序关键字是:"dog","cow","cat","bird"
我有一个实现 TextChanged 事件的 RichTextBox。
现在,我的问题是遇到关键字时不知道如何更改字体颜色。
示例字符串:A Big Dog and a Cat
狗是红色,猫是绿色。
【问题讨论】:
标签: c# .net winforms 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);
}
【讨论】: