Ben
Ben

Reputation: 7802

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

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 and 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

Upvotes: 0

Views: 3799

Answers (3)

G. Maniatis
G. Maniatis

Reputation: 131

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.

Upvotes: 0

Ruddy
Ruddy

Reputation: 1754

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?

Upvotes: 2

taylonr
taylonr

Reputation: 10790

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.

Upvotes: 1

Related Questions