2012-09-09 69 views
2

如何根据鼠标位置设置WinForms文本框的SelectionStart?我在扩展TextBox并想在用户右键单击TextBox时(即与左键单击相同的行为)将鼠标置于鼠标点下的位置。根据鼠标位置设置WinForms文本框的SelectionStart

这里是我的onmousedown事件到目前为止覆盖:

protected override void OnMouseDown(MouseEventArgs e) { 
    if (e.Button == System.Windows.Forms.MouseButtons.Right) { 
     this.Focus(); 
     //if we have a range of text selected, leave it 
     if (this.SelectionLength == 0) { 
      //set the SelectionStart here based on the mouse location in the MouseEventArgs e   
     } 
     //... 
    } else 
     base.OnMouseDown(e); 
} 

我已经使用调查SetCaretPos(如SetCaretPos(e.Location.X, e.Location.Y);),但不能使它工作(我看到了一会儿插入符号,但它仅仅是闪光灯并且不会影响SelectionStart)。

回答

2

尝试这样:

this.SelectionStart = this.GetCharIndexFromPosition(e.Location); 
+0

完美,谢谢! –