MFC 单选框

发布时间 2023-11-28 00:10:25作者: double64

  1. Ctrl+D 调整 CheckBox 为顺序的。

  2. 设定排第一个位置的属性:GroupTRUE.

  3. BOOL CMFCApplication4Dlg::OnInitDialog()函数中可以初始化某一个选中。

// 默认选中
CheckRadioButton(IDC_RADIO_APPLE, IDC_RADIO_OTHER, IDC_RADIO_APPLE);  // 第一个参数,排序的第一个ID;第二个参数,排序的最后一个参数;第三个参数,需要选中的对象ID。

其实,这个 RadioButton是个特殊的按钮。也可以用点击的消息事件。

  1. 判断谁被选中了:

按钮消息事件:

void CMFCApplication4Dlg::OnBnClickedButtonSel()
{
    CString str_role;
    if (IsDlgButtonChecked(IDC_RADIO_APPLE)) {
        str_role = "苹果";
    }
    if (IsDlgButtonChecked(IDC_RADIO_LI)) {
        str_role = "梨子";
    }
    if (IsDlgButtonChecked(IDC_RADIO_OTHER)) {
        str_role = "其他";
    }

    MessageBox(TEXT("选择的是\"") + str_role + TEXT("\""));
}

也可以直接用对象的方式拿到控件的字符串:

void CMFCApplication4Dlg::OnBnClickedButtonSel2()
{
    CString str_role;
    // 判断是否选中
    if (m_RadioBtn_App.GetCheck()) {
        m_RadioBtn_App.GetWindowTextW(str_role);
    }
    if (m_RadioBtn_Li.GetCheck()) {
        m_RadioBtn_Li.GetWindowTextW(str_role);
    }
    if (m_RadioBtn_Other.GetCheck()) {
        m_RadioBtn_Other.GetWindowTextW(str_role);
    }
    MessageBox(TEXT("选择的是\"") + str_role + TEXT("\""));
}


▲ 点击事件


也可以通过变量关联控件,以对象的方式进行访问控件方法。

关联变量的方式:

CButton m_RadioBtn_App;
CButton m_RadioBtn_Li;
CButton m_RadioBtn_Other;

默认设定选中:

// 关联变量对象的方式访问
m_RadioBtn_App.SetCheck(1); // 选中   这样的代码方式,好像 RadioButton 对象之间不会互斥,代码可以出现多选的方式。

按钮点击消息事件:

void CMFCApplication4Dlg::OnBnClickedButtonSel2()
{
    CString str_role;
    // 判断是否选中
    if (m_RadioBtn_App.GetCheck()) {
        str_role = "苹果";
    }
    if (m_RadioBtn_Li.GetCheck()) {
        str_role = "梨子";
    }
    if (m_RadioBtn_Other.GetCheck()) {
        str_role = "其他";
    }
    MessageBox(TEXT("选择的是\"") + str_role + TEXT("\""));
}


▲点击