c++mfcsetfocuscdialogcbutton

How to SetFocus to a CButton so that the border and focus dotted line are visible?


I created a simple dialog-based application, and in the default CDialog added three buttons (by drag-and-dropping them) using the Visual Studio editor.

The default OK and Cancel buttons are there too.

I want to set the focus to button 1 when I click button 3.

I set the property Flat to true in the properties for muy buttons.

I coded this:

void CbuttonfocusDlg::OnBnClickedButton3()
{
    // TODO: Add your control notification handler code here
    GetDlgItem(IDC_BUTTON1)->SetFocus();

    Invalidate();

}

But the boder in button1 is never drawn. The caret (the dotted line indicating focus) is only drawn if I pressed TAB any time before clicking button 3.

I want the button to look exactly as it looks after I click it. Showing the dotted line inside the button programatically, would be a plus.

What I want:

http://i33.tinypic.com/11t8pkl.png

What I get:

http://i37.tinypic.com/160q5hw.png


Solution

  • This draws the thick border around the button:

    static_cast<CButton*>(GetDlgItem(IDC_BUTTON1))->SetButtonStyle(BS_DEFPUSHBUTTON);
    

    A more elegant way to do this would be to define a CButton member variable in CbuttonfocusDlg and associate it to the IDC_BUTTON1 control, and then calling

    this->m_myButton.SetButtonStyle(BS_DEFPUSHBUTTON);
    

    This makes the button to which I'm setting the focus the default button, but note that when the focus goes to a control (inside the dialog) that is not a button, the default button is once more the original default button set in the dialog resource, in this case the "Ok" button.