如何在Windows窗体中强制关注控件 [英] How to force a focus on a control in windows forms
问题描述
我正在尝试在Windows窗体应用程序中关注搜索文本框控件。该文本框位于用户控件内部,该控件位于Windows窗体内部的面板(如果重要)中。
我尝试了3种可以找到的方法:
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();
它们似乎都不起作用。我的意思是,例如,当我尝试第一个控件时,活动控件确实设置为myTextBox,但是当我尝试在键盘上写东西时,文本框不接受它,因此我必须先在文本框内单击以获取焦点。所有方法都是一样的。
我错过了什么吗?
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?
推荐答案
好,终于找到了答案:
正如我所说,我的文本框位于用户控件内部,该控件位于面板内部的窗体内。
当我需要用户控件时,将其添加到面板中。要专注于我的文本框,我必须首先关注用户控件,如下所示:
在我的顶级表单中:
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();
请注意,如果使用:myTextBox.Focus(),它将无法正常工作(不知道为什么)。另外,如果我使用myUserControl.Select()而不是myUserControl.Focus()也不起作用。
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.
这篇关于如何在Windows窗体中强制关注控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!