2011-11-26 75 views
2

我找不到確定RTB中插入符號位置的方法,而我正在選擇文本。 SelectionStart不是選項RichTextBox和Caret位置

我想檢測選擇的方向是否其後退或前進。我試圖在SelectionChanged事件中實現此目的。任何提示將不勝感激。

編輯:

我通過註冊鼠標移動方向(X軸)與鼠標按下和MouseUp事件解決它。

代碼:

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; 
} 

什麼其他方法可以做到這一點?

+0

你有什麼試過的?爲什麼SelectionStart不能作爲決定插入位置的選項?洞察可能有所幫助 – aevanko

+0

因爲正如我所說selectionStart在選擇期間沒有改變,或者我失去了一些東西 – user1017258

回答

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. 您可能會對此使用屬性更改事件。