开发者

How to set the cursor position of a text box on click

开发者 https://www.devze.com 2022-12-18 03:01 出处:网络
I\'m required to have a textbox pre-filled with some text, and want the cursor to default to the beginning of the textbox when it is focused.

I'm required to have a textbox pre-filled with some text, and want the cursor to default to the beginning of the textbox when it is focused.

private void txtBox_Enter(object sender, EventArgs e)
{
    if (this.txtBox.Text == "SOME PREFILL TEXT")
    {
        this.txtBox.Select(0, 0);
    }
}

I'm capturing _Enter as above 开发者_如何学Goand it actually does work if I tab into the text box, but if I mouse-click into the text box, the cursor appears wherever the mouse click was performed, indicating that it is handled after the _Enter event, effectively "overwriting" what I did. To combat this, I hooked in the _Click event to call the txtBox_Enter handler as well, but no luck.

Is there any work around for this?

Thanks, -Ben


What is it the you are trying to accomplish - changing default functionality (such as a click which would normally select the cursor location) is asking for User Experience problems..

Perhaps something along the lines of SETCUEBANNER is what you are trying for?


Perhaps you could extract your if block to it's own method.

Then call this from the txtBox_Enter() as well as either the _Click or, if it exists, _AfterClick()

You could also investigate using the _Focus() events, although I'm not sure where they fall in the order of events fired.


I solved this issue by also handling the _MouseClick event. I used the _Enter event to handle the tab into the control case and added the same code to the _MouseClick:

private void txtBox_MouseClick(object sender, EventArgs e)
{
    if (this.txtBox.Text == "SOME PREFILL TEXT")
    {
        this.txtBox.Select(0, 0);
    }
}

Using both the _Enter and _MouseClick events should cover your needs.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号