簡體   English   中英

RichTextBox和插入位置

[英]RichTextBox and Caret Position

我選擇文字時,找不到在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;
}

還有什么其他方法可以做到?

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

在此處輸入圖片說明

  1. 我不知道為什么,但是即使禁用了AutoWordSelection,我的鼠標也會選擇整個單詞。 不幸的是,對於我的解決方案,這導致選擇方向的改變。
  2. 您可能為此使用屬性更改事件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM