RichTextBox和Caret Position

时间:2011-11-26 07:40:33

标签: c# winforms richtextbox caret

在选择文字时,我无法找到确定RTB中插入位置的方法。 SelectionStart 不是一个选项

我想检测选择方向是向后还是向前。我正在尝试在SelectionChanged 事件中实现这一目标。任何提示将不胜感激。

修改

我通过使用mouseDown和mouseUp事件注册鼠标移动方向(X轴)来解决它。

代码:

bool IsMouseButtonPushed = false;
int selectionXPosition = 0, sDirection=0;

private void richTextBox_SelectionChanged(object sender, EventArgs e)
{
    if (sDirection==2)//forward
    {
        //dosomething
    }
}

private void richTextBox_MouseMove(object sender, MouseEventArgs e)
{
    if (IsMouseButtonPushed && (selectionXPosition - e.X) > 0)//backward
    {
        sDirection = 1;
    }
    else if (IsMouseButtonPushed && (selectionXPosition - e.X) < 0)//forward
    {
        sDirection = 2;
    }
}

private void richTextBox_MouseDown(object sender, MouseEventArgs e)
{
    IsMouseButtonPushed = true;
    selectionXPosition = e.X;
}

private void richTextBox_MouseUp(object sender, MouseEventArgs e)
{
    IsMouseButtonPushed = false;
}

有什么其他方法可以做到这一点?

1 个答案:

答案 0 :(得分:0)

SelectionStart和SelectionLength属性在左侧选择期间更改,而SelectionLength属性在右侧选择期间更改。

简单的解决方案:

int tempStart;
int tempLength;

private void richTextBox1_SelectionChanged(object sender, EventArgs e)
{
    if (richTextBox1.SelectionType != RichTextBoxSelectionTypes.Empty)
    {
        if (richTextBox1.SelectionStart != tempStart)
            lblSelectionDesc.Text = "Left" + "\n";
        else if( richTextBox1.SelectionLength != tempLength)
            lblSelectionDesc.Text = "Right" + "\n";
    }
    else
    {
        lblSelectionDesc.Text = "Empty" + "\n";
    }

    tempStart = richTextBox1.SelectionStart;
    tempLength = richTextBox1.SelectionLength;

    lblSelectionDesc.Text += "Start: " + richTextBox1.SelectionStart.ToString() + "\n";
    lblSelectionDesc.Text += "Length: " + richTextBox1.SelectionLength.ToString() + "\n";
}

控制:

RitchTextBox + 2xLabels

enter image description here

  1. 我不确定为什么,但即使在禁用AutoWordSelection后,我的鼠标也会选择整个单词。不幸的是,对于我的解决方案,这会导致选择方向改变。
  2. 您可能会为此使用属性更改事件。