C#中获取RichTextBox的光标所在行 [英] C# Get cursor line in RichTextBox

查看:1762
本文介绍了C#中获取RichTextBox的光标所在行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,我有一个RichTextBox,我想获得光标的当前行。我发现每一个答案说,使用:

In C#, I have a RichTextBox, and I want to get the current line of the cursor. Every answer I've found says to use:

int currentLine = richTextBox1.GetLineFromCharIndex(richTextBox1.SelectionStart);



不过,richTextBox1.SelectionStart只有更新,当您更改文本。如果您将光标移动使用箭头键,它不更新(我已经通过打印SelectionStart我走动验证了这一点)。

However, richTextBox1.SelectionStart only updates when you make changes to the text. If you move the cursor with the arrow keys, it does not update (I've verified this by printing SelectionStart as I move around).

我如何获取当前光标线,在跟踪它,即使你使用箭头键来移动光标的方式?

How do I get the current line of the cursor, in a way that tracks it even if you use the arrow keys to move the cursor around?

我使用Win8的VS2012。

I'm using VS2012 in Win8.

编辑: terrybozzio的回答显示的问题。对于任何人有这个问题,你不能把代码richTextBox1_TextChanged。你需要把它放在richTextBox1_SelectionChanged。

terrybozzio's answer showed the problem. For anyone else with this problem, you can't put the code in richTextBox1_TextChanged. You need to put it in richTextBox1_SelectionChanged.

推荐答案

首先,你需要得到selectionstart,如果没有
任何选定的文本,返回的值是插入符的位置(从文本的起始字符偏移量),然后调用getlinefromcharindex并传递价值,将其放置在SelectionChanged事件,甚至用箭头键移动插入位置它将更新:

First you need to get selectionstart,If there isn't any selected text, the value returned is the position of the caret(with offset in characters from the start of the text),then you call getlinefromcharindex and pass that value,place it in the selectionchanged event and even with arrow keys moving the caret position it will update:

private void richTextBox1_SelectionChanged(object sender, EventArgs e)
{
    int index = richTextBox1.SelectionStart;
    int line = richTextBox1.GetLineFromCharIndex(index);
    label1.Text = "cursor at line " + line.ToString();
}

这篇关于C#中获取RichTextBox的光标所在行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆