How to get the current line in a RichTextBox control?

18,388

Solution 1

That's what RichTextBox.GetLineFromCharIndex() does. Pass the SelectionStart property value.

Solution 2

This worked for me:

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

Solution 3

My answer is even more awesome than Vincent's because after getting the right line number I noticed it was flickering, horribly. So I added an in memory rich text box to do the work there.

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);
}
Share:
18,388
Joan Venge
Author by

Joan Venge

Professional hitman.

Updated on June 04, 2022

Comments

  • Joan Venge
    Joan Venge almost 2 years

    Say I clicked somewhere inside a RichTextBox control. How can I get the current line the caret is currently on?

    Btw this is to retrieve the whole text string of that line.