How do I move the caret a certain number of positions in a WPF RichTextBox?

后端 未结 3 1261
梦如初夏
梦如初夏 2021-01-05 04:44

I want to move the caret 4 positions to the right of where my caret currently is. I\'m registered for PreviewKeyDown, and calling InsertTextInRun()

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-05 05:23

    I've just bumped into the same problem. It seems final caret position depends on which way it was moving right before the insert.

    Following code makes sure (3.5sp1) that after insert, the cursor will be to the right of the inserted text:

     rtb.CaretPosition = rtb.CaretPosition.GetPositionAtOffset(0, LogicalDirection.Forward);
    rtb.CaretPosition.InsertTextInRun(text);
    

    Note that caret's LogicalDirection property may (and has to) be changed by this; it is not enough to simply create correct TextPointer.

提交回复
热议问题