【问题标题】:C# Richtextbox font and color for special characters特殊字符的 C# Richtextbox 字体和颜色
【发布时间】:2015-10-08 08:44:00
【问题描述】:

我想知道如何更改富文本框中某些字符的颜色。

我想给四个关键词改颜色:"CONDITION","FIRSTCONDITION","SECONDCONDITION","ACTION"

这是我在 Richtextbox 中的文本

"If (CONDITION) then"
"And (FIRSTCONDITION)&(SECONDCONDITION)"
"While (CONDITION) do(ACTION)"

最后是我的代码

public Form1()
{
    InitializeComponent();


}

private void MyRichTextBox(object sender, EventArgs e)
{
    richTextBox1.Font = new Font("Arial", 12f, FontStyle.Bold);
    string[] words =
    {  "If (CONDITION) then","And (FIRSTCONDITION)&(SECONDCONDITION)",
"While (CONDITION) do(ACTION)"
    };

    for (int i = 0; i < words.Length; i++)
    {
    string word = words[i];
    {
        richTextBox1.AppendText(word);
    }
    }
MyRichTextBox.Settings.Keywords.Add("CONDITION");
MyRichTextBox.Settings.Keywords.Add("FIRSTCONDITION");
MyRichTextBox.Settings.Keywords.Add("SECONDCONDITION");
MyRichTextBox.Settings.Keywords.Add("ACTION");
MyRichTextBox.Settings.KeywordColor = Color.Blue;
}

感谢您的帮助。

【问题讨论】:

    标签: c# fonts richtextbox


    【解决方案1】:

    这应该可行,

    using System.Text.RegularExpressions;
    
    List<string> l = new List<string>();
            l.Add("CONDITION");
            l.Add("FIRSTCONDITION");
            l.Add("SECONDCONDITION");
            l.Add("ACTION");
    
                foreach (var v in l)
                {
                    int count = Regex.Matches(rtbxTest.Text, v).Count;//count occurrences of string
                    int WordLen = v.Length;
                    int startFrom=0;
                    for (int i = 0; i < count; i++)    
                    {
                        rtbxTest.SelectionStart = rtbxTest.Text.IndexOf(v, startFrom);
                        rtbxTest.SelectionLength = WordLen;
                        rtbxTest.SelectionColor = Color.Red;
                        startFrom = rtbxTest.Text.IndexOf(v, startFrom) + WordLen;
    
                    }
                }
    

    这会查找特定字符串的所有出现并更改其颜色。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-16
      • 2023-03-09
      • 1970-01-01
      • 2015-12-31
      • 2013-06-15
      • 2022-07-18
      • 2017-03-27
      • 1970-01-01
      相关资源
      最近更新 更多