请问为什么我的代码不起作用?
目前,我能够找到用户输入的单词,但无法在 richTextBoxConversation 中突出显示该单词。
我应该怎么做?
以下是我的代码:
private void buttonTextFilter_Click(object sender, EventArgs e)
{
string s1 = richTextBoxConversation.Text.ToLower();
string s2 = textBoxTextFilter.Text.ToLower();
if (s1.Contains(s2))
{
MessageBox.Show("Word found!");
richTextBoxConversation.Find(s2);
}
else
{
MessageBox.Show("Word not found!");
}
}
最佳答案
您正在使用 Find
方法 - 这只是告诉您单词在文本框中的位置,它不会选择它。
您可以将 Find
的返回值与 Select
一起使用为了“突出”这个词:
if (s1.Contains(s2))
{
MessageBox.Show("Word found!");
int wordPosition = richTextBoxConversation.Find(s2); // Get position
richTextBoxConversation.Select(wordPosition, s2.Length);
}
或者,甚至更好(避免为单词搜索 s1
两次):
int wordPosition = richTextBoxConversation.Find(s2); // Get position
if (wordPosition > -1)
{
MessageBox.Show("Word found!");
richTextBoxConversation.Select(wordPosition, s2.Length);
}
else
{
MessageBox.Show("Word not found!");
}
关于C# find函数问题(不能高亮),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4264471/