MFC Focusing on the first field of my Input Box

Viewed 67

I'm a beginner in MFC and I just want my input box selected by default, ready to input text with the keyboard when the input box pops up.

Here is my C++ .cpp file of the class:

testInputBox::testInputBox(CWnd* pParent /*=nullptr*/)
    : CDialogEx(IDD_INPUT_BOX, pParent)
    , warning(_T(""))
{

}

testInputBox::~testInputBox()
{
}

void testInputBox::DoDataExchange(CDataExchange* pDX)
{
    CDialogEx::DoDataExchange(pDX);
    DDX_Control(pDX, IDC_EDIT_INPUT_BOX, editcedit);

    DDX_Text(pDX, IDC_STATIC_MESSAGE, warning);
    DDV_MaxChars(pDX, warning, 100);
}

BEGIN_MESSAGE_MAP(testInputBox, CDialogEx)
    ON_EN_CHANGE(IDC_EDIT_INPUT_BOX, &testInputBox::OnEnChangeEdit1)
    ON_BN_CLICKED(IDOK, &testInputBox::OnBnClickedOk)
    ON_BN_CLICKED(IDCANCEL, &testInputBox::OnBnClickedCancel)
    ON_STN_CLICKED(IDC_STATIC_MESSAGE, &testInputBox::OnStnClickedStaticMessage)
END_MESSAGE_MAP()
2 Answers

You need to override the OnInitDialog() member of the CDialogEx class and, in that override, set the focus to the desired control. Then, because you have explicitly set the focus, your override function should return zero (or FALSE).

Assuming your editcedit is a pointer to the control you wish to have the focus, then your override will look something like this:

BOOL testInputBox::OnInitDialog()
{
    CDialogEx::OnInitDialog(); // Always call base class function
    // ... anything else you want to do here
    editcedit->SetFocus(); // Or: GetDlgItem(IDC_EDIT_INPUT_BOX)->SetFocus();
    return FALSE;
}

Your override should be declared in the class like this:

class testInputBox : public CDialogEx
{
//...
protected:
    BOOL OnInitDialog() override;
    //...
};

CDialog::GotoDlgCtrl is what you search.

BOOL testInputBox::OnInitDialog()
{
    CDialogEx::OnInitDialog(); 
    // ... 

    GotoDlgCtrl(&editcedit);  

    // alternativ
    CWnd* pWnd = GetDlgItem(IDC_EDIT_INPUT_BOX)
    if(pWnd)
       GotoDlgCtrl(pWnd)
    // ...

}

Related