winfrom 查询某字符串 找到它在 richTextbox 的位置 定位 并高亮 并且滚动定位到所查询的字符串所在的行
如图:
代码:
//查找关键字private void buttonSearch_Click(object sender, EventArgs e){string searchText = textBoxSearch.Text;if (!string.IsNullOrEmpty(searchText)){TextBoxFinds(txtJSON, searchText);TextBoxFinds(txtSQL, searchText);}}//查找关键字,关键字高亮,并且定位到关键字处public void TextBoxFinds(RichTextBox richTextBox, string searchText){try{// 清除之前的高亮显示richTextBox.SelectAll();richTextBox.SelectionBackColor = Color.White;richTextBox.SelectionColor = Color.Black;// 查找字符串int index = richTextBox.Find(searchText);if (index != -1){// 高亮显示找到的字符串richTextBox.Select(index, searchText.Length);richTextBox.SelectionBackColor = Color.Yellow;richTextBox.SelectionColor = Color.Black;// 获取找到的字符串所在的行int line = richTextBox.GetLineFromCharIndex(index);// 滚动到该行int firstCharIndex = richTextBox.GetFirstCharIndexFromLine(line);richTextBox.SelectionStart = firstCharIndex;richTextBox.ScrollToCaret();}}catch { }}