How to catch the click event of checkbox which is in a listctrl cell?

1.2k Views Asked by At

Insert checkbox column on a listctrl

I made a list with a checkbox column consulting the answer above.

enter image description here

Now my superior asks me to disable the OK button at first, enable it when at least there is one line is checked.

I looked up seems there is easy way to catch the click event when a checkbox is in a listctrl.

1

There are 1 best solutions below

0
Barmak Shemirani On BEST ANSWER

Add LVN_ITEMCHANGED to the message map. This will notify the dialog when changes are made to the list item:

BEGIN_MESSAGE_MAP(CMyDialog, CDialogEx)
    ON_NOTIFY(LVN_ITEMCHANGED, IDC_LIST1, OnItemChanged)
    ...
END_MESSAGE_MAP()

Next, handle the message and respond each time a list item is checked or unchecked. Then you have to go through all the items in the list box and use CListCtrl::GetCheck. Example:

void CMyDialog::OnItemChanged(NMHDR* pNMHDR, LRESULT*)
{
    NMLISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR;
    if(pNMListView->uChanged & LVIF_STATE)
    {
        if(pNMListView->uNewState & LVIS_STATEIMAGEMASK && pNMListView->iItem >= 0)
        {
            BOOL checked_once = FALSE;
            for(int i = 0; i < m_list.GetItemCount(); i++)
                if(m_list.GetCheck(i))
                    checked_once = TRUE;
            GetDlgItem(IDOK)->EnableWindow(checked_once);
        }
    }
}

You can add GetDlgItem(IDOK)->EnableWindow(FALSE); in OnInitDialog so that the OK button is initially disabled.

Side note, your dialog is using the old style look. See this link on using the modern style UI: Upgraded MFC application still looks old