您应该能够使用以下内容(其中 rtb 是 RichTextBox)将鼠标在 RichTextBox 中的当前位置作为 TextPointer 获取:
var mousePosition = Mouse.GetPosition(rtb);
var textPointer = rtb.GetPositionFromPoint(mousePosition, false);
给定指针,您可以使用以下方法在指定位置获取和替换单词(但您可能希望更改将字符计为单词的规则)
private string GetWordAtPointer(TextPointer textPointer)
{
return string.Join(string.Empty, GetWordCharactersBefore(textPointer), GetWordCharactersAfter(textPointer));
}
private void ReplaceWordAtPointer(TextPointer textPointer, string replacementWord)
{
textPointer.DeleteTextInRun(-GetWordCharactersBefore(textPointer).Count());
textPointer.DeleteTextInRun(GetWordCharactersAfter(textPointer).Count());
textPointer.InsertTextInRun(replacementWord);
}
private string GetWordCharactersBefore(TextPointer textPointer)
{
var backwards = textPointer.GetTextInRun(LogicalDirection.Backward);
var wordCharactersBeforePointer = new string(backwards.Reverse().TakeWhile(c => !char.IsSeparator(c) && !char.IsPunctuation(c)).Reverse().ToArray());
return wordCharactersBeforePointer;
}
private string GetWordCharactersAfter(TextPointer textPointer)
{
var fowards = textPointer.GetTextInRun(LogicalDirection.Forward);
var wordCharactersAfterPointer = new string(fowards.TakeWhile(c => !char.IsSeparator(c) && !char.IsPunctuation(c)).ToArray());
return wordCharactersAfterPointer;
}