Search code examples
c#eventsselectproperties

Select Text from TextBox in Click event


That you can follow me, it's the best you create a small application containing the following code:

public Form1()
{
    InitializeComponent();

    textBox1.Text = "Any Text";
    textBox1.Click += delegate
                            {
                                textBox1.Select(0, 0);
                            };
}

private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
    linkLabel1.Focus();
}

The linkLabel1 is only there that you can leave the focus from the textBox1.

And now, just click on the textBox. The Select Method works and the first position of the Text is selected. The problem is, first the clicked position is selected. Just for a short time but still pretty annoying.

I already tried this.SuspendLayout() in the GotFocus Event (because this gets fired before Click) and this.ResumeLayout() in the Click Event, but no success.

Do you have any idea?


Solution

  • Thank you very much Mike.

    I figured it out through creating a class deriving from TextBox and overriding OnMouseDown:

    protected override void OnMouseDown(MouseEventArgs e)
    {
        this.Select(0, 0);
    
        base.OnMouseDown(e);
    }
    

    Works perfectly now!