3
votes

I'm working on my first simple MFC project, but I'm struggling with one problem: want to set the focus of all CEdit boxes in one of the dialogs. My idea is when open the dialog, the focus to be on the first edit box and then to swap between them with 'tab'.

I saw the method SetFocus(), but I couldn't apply it correctly. Also I couldn't find a solution for implementing the order of the focus with a specific key.

Thanks in advance to everybody who takes time to help me!

1
That's the default behavior. You don't have to write any code to make that happen. The only thing that's required is that your controls are ordered in the way you want TAB to move between them, with your initial Edit control being the first control in your resource script.IInspectable

1 Answers

3
votes

You can set the focus to a given control when your dialog box is first shown by calling SetFocus in your OnInitDialog() function. However, if you do so, your OnInitDialog() must return FALSE:

BOOL MyDialog::OnInitDialog() {
    CDialog::OnInitDialog(); // Call base class member
    GetDlgItem(IDC_MYEDIT)->SetFocus();
    //..
    return FALSE; // Otherwise, the framework will reset the focus to its default
}

From the M/S documentation:

Return Value
Specifies whether the application has set the input focus to one of the controls in the dialog box. If OnInitDialog returns nonzero, Windows sets the input focus to the default location, the first control in the dialog box. The application can return 0 only if it has explicitly set the input focus to one of the controls in the dialog box.