Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to see if an MFC checkbox is selected

Tags:

c++

checkbox

mfc

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

like image 569
asgoodas Avatar asked Aug 23 '12 12:08

asgoodas


2 Answers

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.

like image 62
Some programmer dude Avatar answered Sep 25 '22 12:09

Some programmer dude


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.

like image 41
The Forest And The Trees Avatar answered Sep 24 '22 12:09

The Forest And The Trees