How to see if an MFC checkbox is selected

35,566

Solution 1

CButton's GetState gets the current state of the dialog object. What you want to be using is CButton's 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.

Solution 2

If you read the manual page on GetState you will see that it returns a bitmask.

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, GetCheck might be more appropriate in your case.

Solution 3

From MSDN Forum:

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"));
Share:
35,566
asgoodas
Author by

asgoodas

Updated on July 09, 2022

Comments

  • asgoodas
    asgoodas almost 2 years

    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.

    Many thanks