0

I have been trying to move the caret in a RichTextBox to another paragraph just like how Ctrl+Down arrow is pressed on the keyboard. I use SendKeys.Send("^{DOWN}") but it is not consistent, at times it seems it pressed twice i.e. skip some lines. But when pressing it directly from the keyboard, to move smoothly without jumping.

How do I make the SendKeys stable or is there another way around for this?

1 Answers1

1

You may use:

Dim nextParagraphPos = RichTextBox1.Text.IndexOf(vbLf, RichTextBox1.SelectionStart) + 1
If nextParagraphPos > 0 Then
    RichTextBox1.SelectionStart = nextParagraphPos
Else
    RichTextBox1.SelectionStart = RichTextBox1.TextLength
End If

This uses IndexOf() to get the position of the next Line-Feed character, which reveals the position of the next paragraph. If IndexOf() returns -1, we set the position at the end of the string to simulate the behavior of Ctrl+.

You may also replace the If statement with this shorter version:

RichTextBox1.SelectionStart = 
    If(nextParagraphPos > 0, nextParagraphPos, RichTextBox1.TextLength)
  • @yinkajewole Not really. `IIf()` only exists for backward compatibility. You should always use `If()` because it uses short-circuit evaluation (while `IIf()` [evaluates both sides](https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/iif-function#remarks)). You can read more about the difference between `If()` and `IIf()` in these posts: [1](https://stackoverflow.com/q/1220411/8967612), [2](https://stackoverflow.com/q/28377/8967612), [3](https://stackoverflow.com/q/31280285/8967612) – 41686d6564 stands w. Palestine Sep 08 '20 at 14:25