首页 > 解决方案 > 如何在richTextBox 中仅将结果文本而不是所有文本着色为红色?

问题描述

private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
    if (results.Count > 0)
    {
        richTextBox1.SelectionStart = results[(int)numericUpDown1.Value - 1];
        richTextBox1.ScrollToCaret();
        richTextBox1.SelectionColor = Color.Red;
    }
}

我希望在更改 numericUpDown 时它会像只突出显示结果一样着色:

results[(int)numericUpDown1.Value - 1]

执行 ForeColor 是为richTextBox 中的所有文本着色。

我忘了提到在此之前我有一个功能可以突出显示 richTextBox 中的特定文本:

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;
                }
                else
                {
                    box.SelectionStart = jx;
                    box.SelectionLength = phrase.Length;
                    box.SelectionColor = color;
                    ix = jx + 1;
                    results.Add(jx);
                }
            }
            box.SelectionStart = pos;
            box.SelectionLength = 0;
        }

并使用它:

string word = textBox1.Text;
                    string[] test = word.Split(new string[] { ",," }, StringSplitOptions.None);
                    foreach (string myword in test)
                    {
                        HighlightPhrase(richTextBox1, myword, Color.Yellow);
                        label16.Text = results.Count.ToString();
                        label16.Visible = true;
                        if (results.Count > 0)
                        {
                            numericUpDown1.Maximum = results.Count;
                            numericUpDown1.Enabled = true;
                            richTextBox1.SelectionStart = results[(int)numericUpDown1.Value - 1];
                            richTextBox1.ScrollToCaret();
                        }
                    }

标签: c#winforms

解决方案


Color color = Color.red;    
string result = "Result";
string nonColoredPart = "This is not colored";
string partialResultColored = "<color=#" + ColorUtility.ToHtmlStringRGBA(color) + ">" + result+ "</color>" + nonColoredPart;

然后将文本分配到接受富文本的地方。


推荐阅读