How to set the cursor in front of the found word in richTextBox? I want to do a search with the button "Find more ...". While there is a selection of matches.

if (txtB_Find.Text.Length > 0) { int indexToText = rTB_Result.Find(txtB_Find.Text); if (indexToText >= 0) { int i = 0; MatchCollection allIp = Regex.Matches(rTB_Result.Text, txtB_Find.Text); foreach (Match ip in allIp) { rTB_Result.SelectionStart = ip.Index; rTB_Result.SelectionLength = ip.Length; rTB_Result.SelectionBackColor = Color.FromArgb(255, 160, 122); i = i + 1; } MessageBox.Show("Найдено совпадений: " + i, txtB_Find.Text, MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("Искомый элемент НЕ найден!", txtB_Find.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } 
  • Set rTB_Result.SelectionLength = 0 instead of ip.Length - nick_n_a
  • @nick_n_a if I change to rTB_Result. SelectionLength = 0; then I do not highlight the desired text. The cursor does not appear. - Nataka
  • Probably you need richTextBox.SelectionStart = позиция , and Length is there because rTB_Result is not entirely clear what. - nick_n_a
  • @nick_n_a and how to find out the position? - Nataka
  • I showed you the answer. - nick_n_a

1 answer 1

Replace rTB_Result.SelectionLength = ip.Length; on rTB_Result.SelectionLength = 0; if you need to set the cursor.

Although, for good, I would have done a search cycle like this

 bool ipcatch = false; int ipsel = -1; foreach (Match ip in allIp){ if (ipsel < 0 ) ipsel =ip.Index; if (ipcatch) { ipsel =ip.Index; ipcatch = false; }; if (rTB_Result.SelectionStart == ip.Index) ipcatch = true; i=i+1; rTB_Result.SelectionStart = ip.Index; rTB_Result.SelectionLength = ip.Length; rTB_Result.SelectionBackColor = Color.FromArgb(255, 160, 122); } if (ipsel >=0 ) { richTextBox.SelectionStart = ipsel; richTextBox.SelectionLength = 0; }