Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force a focus on a control in windows forms

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?

like image 922
Wolf Avatar asked Jun 04 '13 14:06

Wolf


People also ask

What does focus () do C#?

The Focus method returns true if the control successfully received input focus. The control can have the input focus while not displaying any visual cues of having the focus.

How do I focus a TextBox in Winforms?

C# Winforms textbox focus with Focus method. Select the "Event" icon, enter Form1_Activated on the right of Activated, click anywhere to open the code file of Form. In this way, open the Form1, the focus will automatically appear in textbox.


2 Answers

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.

like image 61
Wolf Avatar answered Sep 21 '22 09:09

Wolf


You could do these logic steps to set your control to be the focus:

your_control.Select();
your_control.Focus();

Enjoy! :)

like image 23
Anonymous Helper Avatar answered Sep 19 '22 09:09

Anonymous Helper