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?
The Focus method attempts to give the specified element keyboard focus. The returned element is the element that has keyboard focus, which might be a different element than requested if either the old or new focus object block the request.
Focus is a low-level method intended primarily for custom control authors. Instead, application programmers should use the Select method or the ActiveControl property for child controls, or the Activate method for forms.
To set focus on an ASP.NET Web server controlCall the control's Focus method. Call the page's SetFocus method, passing it the ID of the control on which you want to set focus. Security Note: This example has a text box that accepts user input, which is a potential security threat.
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 return FALSE
to indicate that you have explicitly set the input focus to one of the controls in the dialog box. If you return TRUE
, 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 the GotoDlgCtrl
method and specify your control. For example:
BOOL CMyDialog::OnInitDialog() { CDialog::OnInitDialog(); // Add your initialization code here // ... // Set the input focus to your control GotoDlgCtrl(GetDlgItem(IDC_EDIT)); // Return FALSE because you manually set the focus to a control return FALSE; }
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 the GotoDlgCtrl
function (or its equivalent, the WM_NEXTDLGCTRL
message) is preferred.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With