简体   繁体   中英

How to handle events for dynamically created objects in MFC?

I am wondering how I can handle an event for a dynamically created variable, eg a list control.

CListCtrl* pList = new CListCtrl();<br/>
pList->Create(...);

How can I handle the event LVN_ITEMCHANGED for pList?

OnLvnItemchangedList(NMHDR *pNMHDR, LRESULT *pResult)
{
   //do stuff
}

Do I have to create an extended CListCtrl or is there some other way? I would prefer not creating a extended class.

LVN_ITEMCHANGED is sent through WM_NOTIFY message from control to its parent so you just need to add LVN_ITEMCHANGE handler function in parent's class (eg CMyDlg):

In header file:

class CMyDlg : public CDialog
{
   ...
protected:
   afx_msg void OnLvnItemChanged(NMHDR *pNMHDR, LRESULT *pResult);
   ...
}

In source file:

BEGIN_MESSAGE_MAP(CMyDlg, CDialog)
   ...
   ON_NOTIFY(LVN_ITEMCHANGED, IDC_LIST, &CMyDlg::OnLvnItemChanged)  
   ...
END_MESSAGE_MAP()

...

void CMyDlg::OnLvnItemchanged(NMHDR *pNMHDR, LRESULT *pResult)
{
   LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR); 
   *pResult = 0;
   ... // examine *pNMLV members for item's information
}

It does not matter how CListCtrl control is created (through resource editor or dynamically), approach is the same. Just make sure you are using correct control ID in ON_NOTIFY message map entry. ( ID passed to Create / CreateEx or defined in Properties in resource editor).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM