根据当前插入符位置选择 RichTextBox 中的整个段落

问题描述 投票:0回答:1

我有一个

RichTextBox
,其中
Multiline
设置为
true
。它可以包含多个值,其中一些值太长并且会拉伸成多行,但在 RTB 中被视为一行。

我试图选择整个值,但是当文本被拉伸时,它总是只选择我单击的行。

这是我正在使用的代码:

private void SelectLine(RichTextBox rtb)
{
    if (rtb.Lines.Length != 0)
    {
        int firstcharindex = rtb.GetFirstCharIndexOfCurrentLine();
        int currentline = rtb.GetLineFromCharIndex(firstcharindex);
        string currentLineText = rtb.Lines[currentline];
        rtb.Select(firstcharindex, currentLineText.Length);
    }
}

我面临的问题是

GetFirstCharIndexOfCurrentLine()
获取我单击的行中第一个字符的索引,而不是实际值的开头索引。然而,在 Lines 数组中,该值表示为一行。

如何修改此代码以选择整个值,无论它如何在“RichTextBox”中扩展到多行?

c# winforms richtextbox
1个回答
4
投票

TextBoxBase 的 Lines[] 属性返回逻辑行(由换行符分隔的文本行,

\n
或回车符 + 换行符,
\r\n
)。
GetLineFromCharIndex() 方法返回物理行(容器内的换行文本)。

如果要选择包含插入符号的整个段落(逻辑行),则必须寻找其边界,即

\n
字符。
RichTextBox 仅使用
\n
(当您添加/粘贴/设置包含任何字符的文本时,
\r
字符将被删除),TextBox 使用
\r\n

例如:

我使用

TextBoxBase
作为 Type 参数,因此您可以将此方法与 RichTextBox 和 TextBox 一起使用(均源自
TextBoxBase
)。你可以把它变成一个扩展方法。

void SelectCurrentParagraph(TextBoxBase tbox) {
    var firstParagraphIndex = tbox.Text.LastIndexOf("\n", tbox.SelectionStart) + 1;

    var trim = tbox is RichTextBox ? 0 : 1;
    var lastParagraphIndex = tbox.Text.IndexOf("\n", tbox.SelectionStart) - trim;

    if (lastParagraphIndex < 0) lastParagraphIndex = tbox.TextLength;
    tbox.Select(firstParagraphIndex, lastParagraphIndex - firstParagraphIndex);
}

顺便说一句,如果您使用按钮来调用此方法,请记住将 RichTextBox / TextBox 的

HideSelection
属性设置为
false

© www.soinside.com 2019 - 2024. All rights reserved.