How to Set the Initial Focus of the control in the particular window?

karthik picture karthik · Feb 25, 2011 · Viewed 25.2k times · Source

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?

Answer

Cody Gray picture Cody Gray · Feb 25, 2011

There are two ways to set the initial focus to a particular control in MFC.

  1. 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.

  2. 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.