如何设置特定窗口中控件的初始焦点?
我创建了一个应用程序,在其中使用窗口过程来跟踪窗口中的所有控件。
我的问题是,如何最初将焦点设置到窗口中第一个创建的控件?
I created an application in which I use window procedure to keep track of all the controls in the window.
My question is, how do I initially set the focus to the first created control in the window?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有两种方法可以将初始焦点设置到 MFC 中的特定控件。
第一种也是最简单的方法是利用控件的 Tab 键顺序。当您使用 Visual Studio 中的资源编辑器布置对话框时,可以为每个控件分配一个选项卡索引。选项卡索引最低的控件将自动获得初始焦点。要设置控件的 Tab 键顺序,请从“格式”菜单中选择“Tab 键顺序”,或按 Ctrl+D。
第二种稍微复杂一点的方法是重写
OnInitDialog代表对话框的类中的
函数。在该函数中,您可以将输入焦点设置为您想要的任何控件,然后返回FALSE
以指示您已将输入焦点显式设置为对话框中的控件之一。如果返回TRUE
,框架会自动将焦点设置到默认位置,即上面描述的对话框中的第一个控件。要将焦点设置到特定控件,请调用GotoDlgCtrl
方法并指定您的控件。例如:请注意,您不应该通过简单地调用特定控件的
SetFocus
方法来在对话框中设置焦点。雷蒙德·陈 在他的博客上解释了为什么它比这更复杂,以及为什么首选GotoDlgCtrl
函数(或其等效的WM_NEXTDLGCTRL
消息)。There are two ways to set the initial focus to a particular control in MFC.
The first, and simplest, method is to take advantage of your controls' tab order. When you use the Resource Editor in Visual Studio to lay out a dialog, you can assign each control a tab index. The control with the lowest tab index will automatically receive the initial focus. To set the tab order of your controls, select "Tab Order" from the "Format" menu, or press Ctrl+D.
The second, slightly more complicated, method is to override the
OnInitDialog
function in the class that represents your dialog. In that function, you can set the input focus to any control you wish, and then returnFALSE
to indicate that you have explicitly set the input focus to one of the controls in the dialog box. If you returnTRUE
, the framework automatically sets the focus to the default location, described above as the first control in the dialog box. To set the focus to a particular control, call theGotoDlgCtrl
method and specify your control. For example:Note that you should not set focus in a dialog box by simply calling the
SetFocus
method of a particular control. Raymond Chen explains here on his blog why it's more complicated than that, and why theGotoDlgCtrl
function (or its equivalent, theWM_NEXTDLGCTRL
message) is preferred.