我在win表单应用程序中使用了一个富文本框。我正在搜索特定文本并突出显示所选文本。假设我正在搜索字符串“he_llo”,因此突出显示“he_llo”。我纠正它为“你好”。我在按钮单击中调用高亮功能。如果字符串被更正为hello,那么它不应该突出显示。但它突出了。
private void btnValidate_Click(object sender, EventArgs e)
{
Validate();
}
public void Validate() { string [] words; object [] items = chklbErrorlist.CheckedItems.OfType()。ToArray();
for (int i = 0; i < errorList.Count; i++)
{
//errorList.Add(items[i]);
if (rtbFileDisplay.Text.IndexOf((errorList[i].ToString())) != -1)
{
wordToFind = errorList[i].ToString();
index = rtbFileDisplay.Text.IndexOf(wordToFind);
lstErrorList.Items.Add(index.ToString());
while (index != -1)
{
rtbFileDisplay.Select(index, wordToFind.Length);
rtbFileDisplay.SelectionBackColor = Color.Red;
index = rtbFileDisplay.Text.IndexOf(wordToFind, index + wordToFind.Length);
lstErrorList.Items.Add(index.ToString());
}
}
}
#region "Special Char"
foreach (string exp in RegularExpSpChar)
{
int pos = 0;
char ch = exp[1];
words = null;
words = rtbFileDisplay.Text.Split(ch);
pos = words[0].Length;
Regex myregex;
if (ch.Equals('.'))
{
string expr = @"^\.+[a-zA-Z]";
myregex = new Regex(expr);
}
else
{
myregex = new Regex(exp);
}
for (int index = 1; index < words.Length; index++)
{
string line = ch + words[index];
bool isexist = myregex.IsMatch(line);
if (isexist)
{
rtbFileDisplay.Select(pos, 1);
rtbFileDisplay.SelectionBackColor = Color.Red;
}
else
{
rtbFileDisplay.Select(pos, 1);
rtbFileDisplay.SelectionBackColor = Color.White;
}
pos = pos + line.Length;
}
}
#endregion
#region "Special"
foreach (string exp in RegularExpSpecial)
{
int pos = 0;
char ch = exp[2];
words = null;
switch (ch)
{
case 'i': tagtype = "</i>";
highlightlen = 5;
break;
case 'b': tagtype = "</b>";
highlightlen = 5;
break;
case 's':
if(exp[3] == 'u' && exp[4] == 'p')
{
tagtype = "</sup>";
highlightlen = 7;
}
else if (exp[5] == 'n')
{
tagtype = "</span>";
highlightlen = 8;
}
break;
case '8':
if(exp[1] == '#' && exp[4] == '2' && exp[5] == '1')
{
tagtype = "”";
highlightlen = 8;
}
else if (exp[1] == '#' && exp[4] == '1' && exp[5] == '1')
{
tagtype = "’";
highlightlen = 8;
}
break;
default: break;
}
words = Regex.Split(rtbFileDisplay.Text, tagtype);
pos = words[0].Length;
Regex myregex;
myregex = new Regex(exp);
for (int index = 1; index < words.Length; index++)
{
string line = tagtype + words[index];
bool isexist = myregex.IsMatch(line);
if (isexist)
{
rtbFileDisplay.Select(pos,highlightlen);
rtbFileDisplay.SelectionBackColor = Color.Red;
}
pos = pos + line.Length;
}
}
#endregion
其中pos是he_llo的索引,而highlighten是he_llo的长度。
答案 0 :(得分:1)
您可能只需要突出显示所有文本并将selectionbackcolor设置为白色。