c# - 有选择地为 RichTextBox 中的文本着色

标签 c# format richtextbox

如何在 RichTextBox 中每次遇到字母“A”时都涂成红色?

最佳答案

试试这个:

static void HighlightPhrase(RichTextBox box, string phrase, Color color) {
  int pos = box.SelectionStart;
  string s = box.Text;
  for (int ix = 0; ; ) {
    int jx = s.IndexOf(phrase, ix, StringComparison.CurrentCultureIgnoreCase);
    if (jx < 0) break;
    box.SelectionStart = jx;
    box.SelectionLength = phrase.Length;
    box.SelectionColor = color;
    ix = jx + 1;
  }
  box.SelectionStart = pos;
  box.SelectionLength = 0;
}

...

private void button1_Click(object sender, EventArgs e) {
  richTextBox1.Text = "Aardvarks are strange animals";
  HighlightPhrase(richTextBox1, "a", Color.Red);
}

关于c# - 有选择地为 RichTextBox 中的文本着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/455713/

相关文章:

c# - 接口(interface)继承在这里是正确的做法吗?为什么它不起作用?

c# - PIxelFormat之间如何相互转换?

mysql - 更改 MYSQL 日期格式

c# - 高效存储和显示富文本

c# - 提取和转换

c# - 在 appSettings 中为一个键使用多个值

c# - 如何仅在 Windows 应用程序中验证网站地址输入的文本框

c++ - 正确读取文本文件

c++ - 在 C/C++ scanf() 扫描集中指定 ']' 字符

c# - 如何将一个文件夹的内容分别打开到不同的富文本框?