PTh*_*sCS 2 c# richtextbox cursor line-numbers winforms
在C#中,我有一个RichTextBox,我想得到光标的当前行.我发现的每个答案都说使用:
int currentLine = richTextBox1.GetLineFromCharIndex(richTextBox1.SelectionStart);
Run Code Online (Sandbox Code Playgroud)
但是,richTextBox1.SelectionStart仅在您对文本进行更改时更新.如果您使用箭头键移动光标,它不会更新(我已经通过在我移动时打印SelectionStart来验证这一点).
即使使用箭头键移动光标,如何以跟踪它的方式获取光标的当前行?
我在Win8中使用VS2012.
编辑: terrybozzio的答案显示了问题.对于有此问题的其他人,您不能将代码放在richTextBox1_TextChanged中.您需要将它放在richTextBox1_SelectionChanged中.
首先你需要获得selectionstart,如果没有任何选定的文本,返回的值是插入符号的位置(从文本开头的字符偏移量),然后你调用getlinefromcharindex并传递该值,将其放入selectionchanged事件,即使用箭头键移动插入位置,它也会更新:
private void richTextBox1_SelectionChanged(object sender, EventArgs e)
{
int index = richTextBox1.SelectionStart;
int line = richTextBox1.GetLineFromCharIndex(index);
label1.Text = "cursor at line " + line.ToString();
}
Run Code Online (Sandbox Code Playgroud)