问题描述
在 Windows 窗体应用程序中,何时我应该在应用程序启动时以及随后调用函数后编写代码以将焦点设置到控件?
In a Windows Forms application, when do I write the code to set the focus to a control both while the application is launched and subsequently after I call a function?
例如,如果我有一个 DropDownList、一个 TextBox 和四个按钮,并且我希望将焦点设置为 DropDownList,那么在哪里我要编写我的代码?
For instance, if I have a DropDownList, a TextBox and four buttons and I want the Focus to be set to the DropDownList, where do I write my code?
要在应用程序启动时将焦点设置到特定控件,我可以将选项卡索引设置为该 DropDown(具有最小值,假设 TabStop 属性设置为 True).
To set the focus to a particular control on application launch, I can set the tab index to that DropDown (with a minimum value, under the assumption TabStop property is set to True).
现在,如果用户完成了一项操作(例如,任何单击按钮事件),然后我更新 DropDown,然后如果我想设置焦点...我可以这样做
Now, if the user completes an operation (say, any of the Click Button Events) and then I update the DropDown and after that if I want to set the focus...I can do it as
MyDropDownList.Focus()
问题
注意:问题更多是关于在哪里,而不是如何?
NB: The question is more about where, not how?
推荐答案
到目前为止,最简单的解决方案是正确设置 TabIndex 属性,以便您的MyDropDownList"控件具有最低索引.下一种方法是在构造函数中进行.但是您必须使用 Select(),Focus() 方法还不能工作,因为该控件直到稍后才会变得可见.
By far the simplest solution is to set the TabIndex property correctly so that your 'MyDropDownList' control has the lowest index. The next approach is to do it in the constructor. But you have to use Select(), the Focus() method cannot work yet because the control doesn't become visible until later.
Public Sub New()
InitializeComponent()
MyDropDownList.Select()
End Sub
也适用于 Load 事件.Focus() 在 Shown 事件中开始工作.
Works in the Load event as well. Focus() starts working in the Shown event.
这篇关于如何将焦点设置到 Windows 窗体应用程序中的控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!