2

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?

Andy
  • 3,997
  • 2
  • 19
  • 39
  • Try using your own class that is derived from TextBox. Then override OnClick and do what you want. If you do this, then the default OnClick behavior will not occur. – Mike May 06 '13 at 14:11
  • possible duplicate of [Automatically select all text on focus in WinForms TextBox](http://stackoverflow.com/questions/97459/automatically-select-all-text-on-focus-in-winforms-textbox) – Mike Perrenoud May 06 '13 at 14:13
  • @MichaelPerrenoud I don't want to select all text. Read it again. – Andy May 06 '13 at 14:17
  • @Andy, obviously, but you could easily infer that you don't need to issue a `SelectAll` but rather `Select` -so please think a bit more abstractly. The answer to that question resolved the quirky nature of the text box and selection. – Mike Perrenoud May 06 '13 at 14:19
  • @Mike Very good idea but unfortunately it didn't work. – Andy May 06 '13 at 14:19
  • @MichaelPerrenoud I tried it but didn't work. Looked exactly the same. – Andy May 06 '13 at 14:27
  • 2
    Try overriding OnMouseDown and OnMouseUp? See if you can isolate where the default selection is being done. This might work if don't ever want the default mouse up, down, click, etc. behavior. – Mike May 06 '13 at 14:35
  • @Mike Thank you very much. Added your suggestions as answer. Have a nice day! – Andy May 06 '13 at 14:44

1 Answers1

0

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!

Andy
  • 3,997
  • 2
  • 19
  • 39