How to get the current line in a RichTextBox control?
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.
This worked for me:
this.WordWrap = false;
int cursorPosition = this.SelectionStart;
int lineIndex = this.GetLineFromCharIndex(cursorPosition);
string lineText = this.Lines[lineIndex];
this.WordWrap = true;
That's what RichTextBox.GetLineFromCharIndex() does. Pass the SelectionStart property value.
One way is to send it the EM_LINEFROMCHAR Message. I'm sure there are other ways.
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);
}
This works by counting from the beginning of the document.
var startlinenumber = FindLineNumber(RichText, RichText.Selection.Start);
var endlinenumber = FindLineNumber(RichText, RichText.Selection.End);
Here is the actual function.
int FindLineNumber(RichTextBox rtb, TextPointer p)
{
var findStart = p?.GetLineStartPosition(0);
if (findStart == null) return 0;
var startLinePosition = rtb.Document.ContentStart.GetLineStartPosition(0);
if (startLinePosition == null) return 0;
var foundLineNumber = 0;
while (true)
{
if (startLinePosition.CompareTo(findStart) >= 0)
{
break;
}
startLinePosition = startLinePosition.GetLineStartPosition(1, out var result);
if (result == 0)
{
break;
}
foundLineNumber++;
}
return foundLineNumber;
}
If you want to get current Line Number from the editor Control where you are debugging now then
int lineNumber = (new StackTrace()).GetFrame(1).GetFileLineNumber();
I think it is helpful for your problem.
精彩评论