WPF RichTextBox 控件中获取单词光标的方法是打开的

Shi*_*chi 5 c# wpf richtextbox cursor selection



我想知道如何在 WPF RichTextBox 中获取当前光标所在的单词。我知道 RichTextBox 具有 Selection 属性。但是,这只会给我在 RichTextBox 中突出显示的文本。相反,即使没有突出显示整个单词,我也想知道光标所在的单词。

任何提示表示赞赏。

非常感谢。

Bal*_*ázs 5

将此函数附加到任意 RichTextBox,现在称为 testRTB,并查看输出窗口以获取结果:

private void testRTB_MouseUp(object sender, MouseButtonEventArgs e)
{
        TextPointer start = testRTB.CaretPosition;  // this is the variable we will advance to the left until a non-letter character is found
        TextPointer end = testRTB.CaretPosition;    // this is the variable we will advance to the right until a non-letter character is found

        String stringBeforeCaret = start.GetTextInRun(LogicalDirection.Backward);   // extract the text in the current run from the caret to the left
        String stringAfterCaret = start.GetTextInRun(LogicalDirection.Forward);     // extract the text in the current run from the caret to the left

        Int32 countToMoveLeft = 0;  // we record how many positions we move to the left until a non-letter character is found
        Int32 countToMoveRight = 0; // we record how many positions we move to the right until a non-letter character is found

        for (Int32 i = stringBeforeCaret.Length - 1; i >= 0; --i)
        {
            // if the character at the location CaretPosition-LeftOffset is a letter, we move more to the left
            if (Char.IsLetter(stringBeforeCaret[i]))
                ++countToMoveLeft;
            else break; // otherwise we have found the beginning of the word
        }


        for (Int32 i = 0; i < stringAfterCaret.Length; ++i)
        {
            // if the character at the location CaretPosition+RightOffset is a letter, we move more to the right
            if (Char.IsLetter(stringAfterCaret[i]))
                ++countToMoveRight;
            else break; // otherwise we have found the end of the word
        }



        start = start.GetPositionAtOffset(-countToMoveLeft);    // modify the start pointer by the offset we have calculated
        end = end.GetPositionAtOffset(countToMoveRight);        // modify the end pointer by the offset we have calculated


        // extract the text between those two pointers
        TextRange r = new TextRange(start, end);
        String text = r.Text;


        // check the result
        System.Diagnostics.Debug.WriteLine("[" + text + "]");
}
Run Code Online (Sandbox Code Playgroud)

将 Char.IsLetter(...) 更改为 Char.IsLetterOrDigit(...) 或其他任何适当的内容,具体取决于您是否还希望保留数字。

提示:将其提取到单独程序集中的扩展方法中,以便在需要时访问它。


ikh*_*ikh 1

您可以通过 获取光标的当前位置CaretPosition

不幸的是,没有简单的方法可以将字符置于插入符位置的左侧/右侧。我知道从 RichTextBox 中获取文本的唯一方法是在这个答案中,这有点令人费解。但它会完成必要的事情。