How to force a focus on a control in windows forms

余生颓废 提交于 2020-03-13 07:13:12

问题


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?


回答1:


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.




回答2:


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

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

Enjoy! :)



来源:https://stackoverflow.com/questions/16920786/how-to-force-a-focus-on-a-control-in-windows-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!