Chapter 20: List-Based Controls Visual C++ and MFC Fundamentals
// TODO: Add extra initialization here
CButton *btnSmall = new CButton;
CButton *btnMedium = new CButton;
btnSmall->Create("&Small",
WS_CHILD | WS_VISIBLE | BS_RADIOBUTTON,
CRect(130, 40, 200, 50), this, 0x12);
btnMedium->Create("&Medium",
WS_CHILD | WS_VISIBLE | BS_RADIOBUTTON,
CRect(130, 70, 200, 80), this, 0x14);
return TRUE; // return TRUE unless you set the focus to a control
}
If you want the radio button to get filled with a dot when it has been selected and to
remove the dot from the other radio buttons of the same group, create it with the
BS_AUTORADIOBUTTON style.
While using the radio buttons, the user is presented with the controls and requested to
select one. To make a selection, the user must click the desired choice. The control
selected fills its circle with a (big) dot ?. To programmatically change the state of a radio
button, you have various options.
The easiest way to select a radio button consists of calling the
CWnd::CheckRadioButton() method (actually, you should call this method as
CDialog::CheckRadioButton()). Its syntax is:
void CheckRadioButton(int nIDFirstButton, int nIDLastButton, int nIDCheckButton);
To use this method, you must know the identifiers of the radio buttons involved. The
nIDFirstButton is the identifier of the first radio button of the group. The nIDLastButton
is the identifier of the last radio button of the group. The last argument, nIDCheckButton
is the identifier of the radio button that must be selected. Here is an example:
void CDialog12Dlg::OnBtnSelect2()
{
// TODO: Add your control notification handler code here
CheckRadioButton(IDC_RADIO1, IDC_RADIO3, IDC_RADIO3);
}
To change the state of a radio button, you can call the CButton::SetCheck() method. Its
syntax is:
void SetCheck(int nCheck);
The nCheck value indicates how to fill the control’s circle. To fill it with the selection
dot, pass the value of 0. To deselect a radio button, pass the argument as 1. Here is an
example:
void CDialog12Dlg::OnBtnSelect2()
{
// TODO: Add your control notification handler code here
CButton *btnSecond;
btnSecond = reinterpret_cast<CButton *>(GetDlgItem(IDC_RADIO2));
btnSecond->SetCheck(1);