根据鼠标位置设置WinForms TextBox的SelectionStart

时间:2012-09-09 16:50:09

标签: c# winforms winapi

如何根据鼠标位置设置WinForms TextBox的SelectionStart?我正在扩展TextBox,并且当用户右键单击TextBox时,想要将carot设置在鼠标点下方的位置(即与左键单击相同的行为)。

到目前为止,这是我的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)。

1 个答案:

答案 0 :(得分:2)

尝试这样的事情:

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