Selection changed event in CListView based SDI app

2020-04-01 07:54发布

问题:

I am developing MFC SDI application. My view is derived from CListView class. I would like to handle the selection changed event for the list control. I'm not able to add WM_NOTIFY message handler as I don't know how to get the ID of the created listview. Please help me.

回答1:

All you have to do is add the following to your message map:

ON_NOTIFY_REFLECT(LVN_ITEMCHANGED, &OnItemChanged)

And here is your event handler:

void CMyListView::OnItemChanged(NMHDR* pNMHDR, LRESULT* pResult) 
{ 
    NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR; 

    // Did the item state change?
    if (pNMListView->uChanged & LVIF_STATE)
    {
        // Did the item selection change?
        const bool oldSelState = (pNMListView->uOldState & LVIS_SELECTED) != 0x0;
        const bool newSelState = (pNMListView->uNewState & LVIS_SELECTED) != 0x0;
        const bool selStateChanged = oldSelState != newSelState;
        if(selStateChanged)
        {
            // TODO: handle selection change; use newSelState where appropriate
        }
    }
    *pResult = 0; 
}


标签: c++ mfc