如何在RichTextBox控件中获取当前行?

问题描述 投票:3回答:5

假设我单击了RichTextBox控件内的某个位置。如何获得插入符号当前所在的当前行?

顺便说一下,这是检索该行的整个文本字符串。

c# .net winforms richtextbox
5个回答
11
投票

这就是RichTextBox.GetLineFromCharIndex()所做的。传递SelectionStart属性值。


12
投票

这对我有用:

this.WordWrap = false;
int cursorPosition = this.SelectionStart;
int lineIndex = this.GetLineFromCharIndex(cursorPosition);
string lineText = this.Lines[lineIndex];
this.WordWrap = true;

1
投票

一种方法是将其发送给EM_LINEFROMCHAR Message。我敢肯定还有其他方法。


0
投票

我的回答比文森特的回答还要厉害,因为在获得正确的行号之后,我发现它闪烁得非常可怕。因此,我添加了一个内存丰富的文本框来完成该工作。

private int GetCharacterIndexOfSelection()
{
    var wordWrappedIndex = this.SelectionStart;

    RichTextBox scratch = new RichTextBox();
    scratch.Lines = this.Lines;
    scratch.SelectionStart = wordWrappedIndex;
    scratch.SelectionLength = 1;
    scratch.WordWrap = false;
    return scratch.SelectionStart;
}

private int GetLineNumberOfSelection()
{
    var selectionStartIndex = GetCharacterIndexOfSelection();

    RichTextBox scratch = new RichTextBox();
    scratch.Lines = this.Lines;
    scratch.SelectionStart = selectionStartIndex;
    scratch.SelectionLength = 1;
    scratch.WordWrap = false;
    return scratch.GetLineFromCharIndex(selectionStartIndex);
}

-1
投票

如果要从现在要调试的编辑器控件中获取当前行号,则>]

int lineNumber = (new StackTrace()).GetFrame(1).GetFileLineNumber();

我认为这对您的问题很有帮助。

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