提问人:brushymilbil 提问时间:10/22/2023 最后编辑:Jackdawbrushymilbil 更新时间:10/28/2023 访问量:99
如何在 RichTextBox 中为特定文本着色?
How do I color specific text in a RichTextBox?
问:
所以我正在制作一个文本框,我认为如果当用户输入某些单词时,它们会被突出显示,那会很酷。
我用一个 做了一个函数,但它的颜色是它应该的文本的一半。有时它甚至不起作用。RichTextBox
是不是有一种方法可以给一个词的每次出现着色?
我的代码:
private void ColorLines(RichTextBox text)
{
string[] words = { "example","hi" };
foreach (string s in text.Text.Split(' '))
{
int startIndex = text.Text.IndexOf(s);
int length = s.Length;
if (words.Contains(s))
{
text.Select(startIndex, length);
text.SelectionColor = Color.Red;
}
}
}
我把上面的剧本重写了好几次,都比另一个差。 我浏览过其他有相同问题的帖子,但它是 VB 或 WPF 中的,或者是不同的东西。 我正在寻找一种使用 WinForms 的有效方法。
答:
2赞
Nicktrovert
10/22/2023
#1
这也为其他单词中的单词的实例着色。所以,我不知道这是否适用于您需要它,但除此之外,它应该做您想要的。
//I don't usually work with WinForms so idk if this is the correct way
//to do this or if you can use "sender" or "e" instead of "richTextBox1"
private void richTextBox_TextChanged(object sender, EventArgs e)
{
int tempint = richTextBox1.SelectionStart;
richTextBox1.Select(0, richTextBox1.TextLength);
richTextBox1.SelectionColor = Color.Black;
richTextBox1.Select(tempint, 0);
ColorLines(richTextBox1);
}
private void ColorLines(RichTextBox text)
{
string[] words = { "example", "hi"};
foreach (string word in words)
{
if (text.Text.Contains(word))
{
int index = -1;
int curselected = text.SelectionStart;
while ((index = text.Text.IndexOf(word, (index + 1))) != -1)
{
text.Select(index, word.Length);
text.SelectionColor = Color.Red;
text.Select(curselected, 0);
text.SelectionColor = Color.Black;
}
}
}
}
灵感来自这个传说答案
这是另一个版本,它不会在其他单词中为单词的实例着色,但当单词之前或之后有一个符号(如“,”或“.”)而没有空格时,它不起作用。
private void richTextBox_TextChanged(object sender, EventArgs e)
{
int tempint = richTextBox1.SelectionStart;
richTextBox1.Select(0, richTextBox1.TextLength);
richTextBox1.SelectionColor = Color.Black;
richTextBox1.Select(tempint, 0);
ColorLines(richTextBox1);
}
private void ColorLines(RichTextBox text)
{
string[] words = { "example", "hi" };
int startindex = 0;
foreach (string word2 in text.Text.Split(' ').ToArray())
{
foreach (string word in words)
{
if (word == word2)
{
int curselected = text.SelectionStart;
int length = word2.Length;
text.Select(startindex, length);
text.SelectionColor = Color.Red;
text.Select(curselected, 0);
text.SelectionColor = Color.Black;
}
}
startindex += word2.Length + 1;
}
}
评论