2
votes

Using MFC I have created a dialog, which is having 5 radio buttons. I want to get notification when some other radio-button gets selected.

For now I get notification whenever any of the radio button is clicked. But I need to gets these notification only when there is change in the radio button.

ON_BN_CLICKED(IDC_RADIO1, &CMyDlg::OnRadioButtonClicked)
ON_BN_CLICKED(IDC_RADIO1, &CMyDlg::OnRadioButtonClicked)
ON_BN_CLICKED(IDC_RADIO1, &CMyDlg::OnRadioButtonClicked)
ON_BN_CLICKED(IDC_RADIO1, &CMyDlg::OnRadioButtonClicked)
ON_BN_CLICKED(IDC_RADIO1, &CMyDlg::OnRadioButtonClicked)

Thanks

5

5 Answers

4
votes

If I understand your question correctly, you want to know when the checked state of one particular radio button (IDC_RADIO1) changes.

Then store this state as a member variable in your dialog class. int m_radio1Checked; Initialise in the constructor to 0 or 1 as you want, and use SetCheckRadioButton() appropriately in your OnInitDialog().

Then handle the clicking of each radio button in your message map:

ON_BN_CLICKED(IDC_RADIO1, &CMyDlg::OnRadioButtonClicked)
ON_BN_CLICKED(IDC_RADIO2, &CMyDlg::OnRadioButtonClicked)
ON_BN_CLICKED(IDC_RADIO3, &CMyDlg::OnRadioButtonClicked)
ON_BN_CLICKED(IDC_RADIO4, &CMyDlg::OnRadioButtonClicked)
ON_BN_CLICKED(IDC_RADIO5, &CMyDlg::OnRadioButtonClicked)

and in the handler check for a change.

void CMyDlg::OnRadioButtonClicked()
{
  int oldState = m_radio1Checked;
  int newState = GetDlgItem(IDC_RADIO1)->GetChecked();
  m_radio1Checked = newState;
  if (oldState != newState)
    // do something ...
}
3
votes

One can use ON_CONTROL_RANGE(BN_CLICKED, firstctrlid, lastcntrlid, memberfx)

2
votes

First create group of all radio buttons. Using wizard add member variable of the integer type. In the common handler call UpdateData() and check the value of the variable. It should be set to the value of the button in the group (zero based), starting with THE FIRST BUTTON IN THE GROUP AS 0. Make sure that buttons are set in consecutive Z-order (tab order).

2
votes

Have a separate message map for each radio button, but have a private method that all of them call to check if the selected radio button has changed.

void CDlg::OnRadioBtn1Clicked()
{
    if (!RadioSelectionChanged())
    return;

    //Add other code here
}

//Returns true if the selected radio button has changed
Boolean CDlg::RadioSelectionChanged()
{
    int previousBtnSelected = m_selectedRadioButton;
    UpdateData();

    if (previousBtnSelected != m_selectedRadioButton)
        return true;

    else
        return false;
}
1
votes

I suppose the simplest way to do that is storing the current button status (bool) as a member variable for the dialog class (one for each button) and then in OnRadioButtonClicked just check if the status has changed or not.

If you need to do that in multiple places you can create your own CButton derived class to encapsulate this functionality.