所以我正在制作一个文本框,我认为如果当用户输入某些单词时,它们会被突出显示,那就太酷了。 所以我使用富文本框创建了一个函数,但它的颜色是它应该的文本的一半。 有时它甚至不起作用。 所以我在想是否有一种方法可以为每个出现的单词着色? 我的旧代码:
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 中,或者是不同的东西。 我正在寻找一种使用 Windows 窗体的有效方法。
这也会为其他单词中的单词实例着色(),所以我不知道这是否适合您需要的功能,但除此之外它应该做您想要的事情。
//i dont 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;
}
}
}
}