C++ 如何查看是否选中了 MFC 复选框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12091887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 15:52:13  来源:igfitidea点击:

How to see if an MFC checkbox is selected

c++mfccheckbox

提问by asgoodas

I have checked many places for the answer to this, and they recommend the way I have done it, but it doesn't seem to work for me, so any help would be greatly appreciated.

我已经检查了很多地方的答案,他们推荐我这样做的方式,但它似乎对我不起作用,所以任何帮助将不胜感激。

I have a check box and I would like it to enable an edit box when it is check and disable it when unchecked.

我有一个复选框,我希望它在选中时启用编辑框,在未选中时禁用它。

The following code is what I have created:

以下代码是我创建的:

void CMFCApplication1Dlg::OnBnClickedCheck1()
{
    UINT nCheck = CheckBox.GetState();
    if (nCheck == BST_CHECKED)
    {
        EditBox.EnableWindow(TRUE);
    }
    else if (nCheck == BST_UNCHECKED)
    {
        EditBox.EnableWindow(FALSE);
    }
    else
    {
        EditBox.EnableWindow(TRUE);
    }

nCheck is 520 when I run it in debug, so goes straight to the else option.

当我在调试中运行它时,nCheck 是 520,所以直接转到 else 选项。

Many thanks

非常感谢

回答by The Forest And The Trees

CButton's GetState gets the current state of the dialog object. What you want to be using is CButton's GetCheck.

CButton 的 GetState 获取对话框对象的当前状态。您想要使用的是 CButton 的 GetCheck。

Alternatively, you can, as indicated on MSDN, do a bitwise mask on the return value to get the current Check state - but GetCheck is right there, so you might as well use it.

或者,您可以按照 MSDN 上的指示,对返回值执行位掩码以获取当前 Check 状态 - 但 GetCheck 就在那里,因此您不妨使用它。

回答by Some programmer dude

If you read the manual pageon GetStateyou will see that it returns a bitmask.

如果您阅读手册页GetState您将看到它返回一个位掩码。

This means you can't use it directly in comparisons, you have to check it like a mask:

这意味着你不能直接在比较中使用它,你必须像掩码一样检查它:

if ((nCheck & BST_CHECKED) != 0)
{
    // Button is checked
}
else
{
    // Button is unchecked
}

However, GetCheckmight be more appropriate in your case.

但是,GetCheck可能更适合您的情况。

回答by SAAD

From MSDN Forum:

来自MSDN 论坛

CButton *m_ctlCheck = (CButton*) GetDlgItem(IDC_CHECKBOX);
int ChkBox = m_ctlCheck->GetCheck();
CString str;

if(ChkBox == BST_UNCHECKED)
  str.Format(_T("Un Checked"));
else if(ChkBox == BST_CHECKED)
  str.Format(_T("Checked"));

回答by Michael Haephrati

To read the state of a checkbox named IDC_CHECK1 into a variable:

要将名为 IDC_CHECK1 的复选框的状态读入变量:

bool IsCheck1Checked;

use the following code:

使用以下代码:

CButton *m_ctlCheck1 = (CButton*)GetDlgItem(IDC_CHECK1);
IsCheck1Checked = (m_ctlCheck1->GetCheck() == 1) ? true : false;