我目前正在制作类似记事本的程序,但是我很困惑。
我需要填写“查找字母/单词”表格。我已经弄清楚了,但是似乎无法将RichTextBox
SelectionBackColor
恢复为默认值,例如Color.White;
我当前的代码在这里:
这是Find
的{{1}} Button
:
Form2.cs
不要介意引用(rtb等)
我的问题是:起初工作正常,但是如果您删除原始的“找到的”文本,那么 public static void Find(RichTextBox rtb,String word, Color color)
{
if(word=="")
{
return;
}
int s_start = rtb.SelectionStart, startIndex = 0, index;
while((index=rtb.Text.IndexOf(word,startIndex))!=-1)
{
rtb.Select(index, word.Length);
rtb.SelectionColor = color;
startIndex = index + word.Length;
}
rtb.SelectionStart = s_start;
rtb.SelectionLength = 0;
rtb.SelectionColor = Color.White;
}
private void button1_Click(object sender, EventArgs e)
{
Find(richtext, textBox1.Text, Color.Blue);
}
就会变成“找到的”文本的SelectionColor
,有没有人解决? / p>
答案 0 :(得分:1)
首先,我想提到Richtextbox的默认选择颜色是黑色而不是白色。
第二,您可以尝试以下代码来完成所需的工作。
private void button1_Click(object sender, EventArgs e)
{
Find(richTextBox1, textBox1.Text, Color.Blue);
}
public static void Find(RichTextBox rtb, String word, Color color)
{
rtb.SelectionStart = 0;
rtb.SelectionLength = rtb.TextLength;
rtb.SelectionColor = Color.Black;
if (word == "")
{
return;
}
int s_start = rtb.SelectionStart, startIndex = 0, index;
while ((index = rtb.Text.IndexOf(word, startIndex)) != -1)
{
rtb.Select(index, word.Length);
rtb.SelectionColor = color;
startIndex = index + word.Length;
}
}
private void richTextBox1_SelectionChanged(object sender, EventArgs e)
{
richTextBox1.SelectionColor = Color.Black;
}
答案 1 :(得分:1)
根据您的新描述,建议您添加另一个按钮以将其恢复为原始颜色。
代码:
private void button1_Click(object sender, EventArgs e)
{
Find(richTextBox1, textBox1.Text, Color.Blue);
}
public static void Find(RichTextBox rtb, String word, Color color)
{
rtb.SelectionStart = 0;
rtb.SelectionLength = rtb.TextLength;
rtb.SelectionColor = Color.Black;
if (word == "")
{
return;
}
int s_start = rtb.SelectionStart, startIndex = 0, index;
while ((index = rtb.Text.IndexOf(word, startIndex)) != -1)
{
rtb.Select(index, word.Length);
rtb.SelectionColor = color;
startIndex = index + word.Length;
}
}
private void button2_Click(object sender, EventArgs e)
{
richTextBox1.SelectionStart = 0;
richTextBox1.SelectionLength = richTextBox1.TextLength;
richTextBox1.SelectionColor = Color.Black;
}