如果我在RichTextBox控件内的某个位置点击,如何获取插入符当前所在的行?
顺便说一下,这是为了检索该行的整个文本字符串。
如果我在RichTextBox控件内的某个位置点击,如何获取插入符当前所在的行?
顺便说一下,这是为了检索该行的整个文本字符串。
这个方法对我可行:
this.WordWrap = false;
int cursorPosition = this.SelectionStart;
int lineIndex = this.GetLineFromCharIndex(cursorPosition);
string lineText = this.Lines[lineIndex];
this.WordWrap = true;
我的答案比Vincent的更好,因为在获取正确的行号后,我注意到它会闪烁,非常恶心。所以我添加了一个内存富文本框来完成这项工作。
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);
}
这个功能是通过从文档开头开始计数来实现的。
var startlinenumber = FindLineNumber(RichText, RichText.Selection.Start);
var endlinenumber = FindLineNumber(RichText, RichText.Selection.End);
这就是实际的函数。
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;
}
int lineNumber = (new StackTrace()).GetFrame(1).GetFileLineNumber();
我认为这对你的问题有帮助。