c# - 如何在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();
}
}
解决方案
Color color = Color.red;
string result = "Result";
string nonColoredPart = "This is not colored";
string partialResultColored = "<color=#" + ColorUtility.ToHtmlStringRGBA(color) + ">" + result+ "</color>" + nonColoredPart;
然后将文本分配到接受富文本的地方。
推荐阅读
- sql-server - SSMS/SSRS - 从查询中获取 SSRS 数据集使用的存储过程名称
- node.js - MongoDB $addFields 和 $in 合计
- azure - Azure DevOps 如何将自定义内部版本号格式获取到 YAML 构建管道?
- java - Java/Android:验证十进制编辑文本的可接受值的范围
- python - 在 Python 中将元组元素切片和堆叠成矩阵
- shell - 使用嵌入空格加密文件
- python - 为什么我在安装 python-weka-wrapper3 时出错,尽管安装了 Visual C++ 14.0
- javascript - 如何在 Postman 测试中使用 Promise?
- roblox - Roblox:如何通过 if 语句检查玩家所在的团队?
- javascript - 当我在不同页面应用程序的页眉中单击超链接时如何向下滚动到页脚