2011-11-26 67 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. 您可能会对此使用属性更改事件。