MFC: How to set the focus of CEdit boxes?

2.4k Views Asked by At

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

There are 1 best solutions below

2
On

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.