C# – How to force a focus on a control in windows forms

cfocusnetwinforms

I am trying to focus a "search" textbox control in my windows forms application. This textbox is inside a user control, which is inside a panel which is inside a windows form (if it is important).
I tried 3 methods which I could find:

// 1
this.ActiveControl = myTextBox;

// 2
myTextBox.Focus();

// 3
myTextBox.Select();

Neither of them seems to work. I mean for example when I try the first one, active control is really set to myTextBox, but when I try to write something on keyboard, textbox doesn't accept it and I have to first click inside the textbox to get focus. This is same with all of the methods.
Am I missing something?

Best Answer

Ok, finally found the answer:

As I said my textbox is inside user control which is inside panel which is inside a form. When I need my user control I add it to panel. To get focus on my textbox I have to firstly focus my user control so something like this: In my top Form:

panel.Controls.Add(myUserControl);
myUserControl.Focus();

and then in my user control:

myTextBox.Select();

Note that if I used: myTextBox.Focus() it wouldn't work (don't know why). Also if I used myUserControl.Select() instead of myUserControl.Focus() it wouldn't work either.

This seems to be the only combination which works.