获取WPF中RichTextBox中的当前光标位置值

时间:2011-07-27 12:09:09

标签: wpf c#-3.0

如何在WPF中的RichTextBox中获取当前光标位置值?

WPF中的RichTextBox有很多变化。

3 个答案:

答案 0 :(得分:1)

查看CaretPosition属性。

这会获得(或设置)输入插入符号的位置。

此外还有Selection属性。这将返回一个对象,其中包含有关所选文本的信息,包括StartEnd

答案 1 :(得分:1)

希望此代码可以帮助您

代码:

private static int EM_LINEINDEX = 0xbb;
[DllImport("user32.dll")]
extern static int SendMessage(IntPtr hwnd, int message, int wparam, int lparam);
private void UpdateCaretPos()
{
  int line, col, index;
  index = rtfText.SelectionStart;
  line = rtfText.GetLineFromCharIndex(index);
  col = index - SendMessage(rtfText.Handle, EM_LINEINDEX, -1, 0);
  panCaret.Text = (++line).ToString() + ", " + (++col).ToString();
}
private void rtfText_TextChanged(object sender, EventArgs e)
{
  UpdateCaretPos();
}
private void rtfText_KeyDown(object sender, EventArgs e)
{
  UpdateCaretPos();
}

private void rtfText_KeyUp(object sender, EventArgs e)
{
  UpdateCaretPos();
}

此致

Karan Shah

答案 2 :(得分:0)

   private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Back)
    {
        var z = this.richTextBox1.SelectionStart;
        var r = richTextBox1.Find(" ", 0, z, RichTextBoxFinds.None | RichTextBoxFinds.Reverse);
        var q = this.richTextBox1.Text.Substring(r + 1, z - r - 1);
        switch (q)
        {
            case "test":
                this.richTextBox1.SelectionStart = r + 1;
                this.richTextBox1.SelectionLength = z - r - 1;
                this.richTextBox1.SelectionColor = Color.Black;
                this.richTextBox1.SelectionStart += this.richTextBox1.SelectionLength;
                this.richTextBox1.SelectionLength = 0;
                //e.Handled = true;
                break;
            default:
                this.richTextBox1.SelectionStart = z;
                break;
        }
    }
}