2

マウスの位置に基づいて WinForms TextBox の SelectionStart を設定するにはどうすればよいですか? 私は TextBox を拡張しており、ユーザーが TextBox を右クリックしたとき (つまり、左クリックと同じ動作) に、マウス ポイントの下の位置にキャロットを設定したいと考えています。

これまでの私の 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を使用して調査しましたが(eg SetCaretPos(e.Location.X, e.Location.Y);)、機能しませんでした (キャレットが一瞬見えますが、それは単なるフラッシュであり、SelectionStart には影響しません)。

4

1 に答える 1

2

次のようなことを試してください:

this.SelectionStart = this.GetCharIndexFromPosition(e.Location);
于 2012-09-09T16:59:00.277 に答える