C# 如何强制将焦点放在 Windows 窗体中的控件上
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16920786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to force a focus on a control in windows forms
提问by Wolf
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:
我正在尝试将“搜索”文本框控件集中在我的 Windows 窗体应用程序中。此文本框位于用户控件内,该用户控件位于 Windows 窗体内的面板内(如果它很重要)。我尝试了 3 种我能找到的方法:
// 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?
它们似乎都不起作用。我的意思是,例如,当我尝试第一个时,活动控件确实设置为 myTextBox,但是当我尝试在键盘上写东西时,文本框不接受它,我必须先在文本框内单击才能获得焦点。这与所有方法相同。我错过了什么吗?
采纳答案by Wolf
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.
请注意,如果我使用: myTextBox.Focus() 它将不起作用(不知道为什么)。此外,如果我使用 myUserControl.Select() 而不是 myUserControl.Focus() 它也不起作用。
This seems to be the only combination which works.
这似乎是唯一有效的组合。
回答by Anonymous Helper
You could do these logic steps to set your control to be the focus:
您可以执行以下逻辑步骤来将控件设置为焦点:
your_control.Select();
your_control.Focus();
Enjoy! :)
享受!:)

