MFC Toggle Radio Button Is Delayed

662 views Asked by At

I have a radio button that is a CButton in a CDialog. When the user clicks the radio button, the function OnClickedRadioButton is called.

Inside OnClickedRadioButton I toggle the button by calling this function:

void toggleButton(CButton& theButton)
{
    switch(theButton.GetCheck())
    {
        case BST_UNCHECKED:
        {
            theButton.SetCheck(BST_CHECKED);
            break;
        }
        case BST_CHECKED:
        {
            theButton.SetCheck(BST_UNCHECKED);
            break;
        }
        default:
        {
            theButton.SetCheck(BST_UNCHECKED);
        }
    }
}

When I compile & run the program: (i) if the radio button is checked on, I can click it to clear it. (ii) if the radio button is unchecked, I click it and nothing happens. But if I click on a different program (i.e. visual studio) and then click back on the CDialog, the radio button checks on.

I've looked & tried functions Cwnd::UpdateDialogControls and Cwnd::UpdateData, but I was not able to get these to solve my problem.

1

There are 1 answers

0
user3731622 On

I believe the problem was related to @rrirower comment that SetCheck will cause another OnClickedRadioButton event.

Regardless of the root cause, the quick fix to allow my implementation to toggle a radio button betweenBST_CHECKED and BST_UNCHECKED was to set the radio button's Auto property to False.

To do this: 1) Open the resource in visual studio 2) Right-click on the radio button and select Properties 3) In the Appearance section, set the Auto property to False.

Here is the overall solution to toggle a single radio button in a subclass of CDialog (assuming you already added a Dialog resource with a radio button with ID IDC_RADIO):

1) Add radio button IDC_RADIO to the message map by placing this line

ON_BN_CLICKED(IDC_RADIO, OnBnClickedRadioButton)

between BEGIN_MESSAGE_MAP and END_MESSAGE_MAP.

2) Add the handler function to your subclass of CDialog

void OnBnClickedRadioButton()
{
    toggleButton(*(CButton*)GetDlgItem(IDC_RADIO));
}

3) Add the toggle function to your subclass of CDialog

void toggleButton(CButton& theButton)
{
    switch(theButton.GetCheck())
    {
        case BST_UNCHECKED:
        {
            theButton.SetCheck(BST_CHECKED);
            break;
        }
        case BST_CHECKED:
        {
            theButton.SetCheck(BST_UNCHECKED);
            break;
        }
        default:
        {
            theButton.SetCheck(BST_UNCHECKED);
        }
    }
}