gpt4 book ai didi

c# - word cursor is on的获取方式,在WPF RichTextBox控件中

转载 作者:太空狗 更新时间:2023-10-30 00:54:47 25 4
gpt4 key购买 nike

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

如有任何提示,我们将不胜感激。

最佳答案

将此函数附加到任意 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 + "]");
}

根据您是否希望保留数字,将 Char.IsLetter(...) 更改为 Char.IsLetterOrDigit(...) 或其他适当的内容。

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

关于c# - word cursor is on的获取方式,在WPF RichTextBox控件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11732081/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com