在CTreeCtrl中捕获复选框选中消息,父子节点选中状态联动

转自:http://apps.hi.baidu.com/share/detail/22849017

void CMyDlg::OnClickTree1(NMHDR* pNMHDR, LRESULT* pResult) 
{
// TODO: Add your control notification handler code here
NM_TREEVIEW* pHdr = (NM_TREEVIEW*)pNMHDR;
*pResult = 0;

CPoint point;
UINT uFlag;
GetCursorPos(&point);
ScreenToClient(&point);

HTREEITEM item = m_ctrlTree.HitTest(point, &uFlag);
if((item) && (TVHT_ONITEMSTATEICON & uFlag))   
{   
BOOL bCheck = m_ctrlTree.GetCheck(item);
SetItemCheckState(item, !bCheck);}   
}

/************************************************************************/
/* 根据选择的节点选中状态,设置相关节点的选中状态                   */
/************************************************************************/
void CHistoryDlg::SetItemCheckState(HTREEITEM item, BOOL bCheck)
{
SetChildCheck(item, bCheck);
SetParentCheck(item, bCheck);
}

/************************************************************************/
/* 设置子节点的选中状态                                              */
/************************************************************************/
void CHistoryDlg::SetChildCheck(HTREEITEM item, BOOL bCheck)
{
HTREEITEM child = m_ctrlTree.GetChildItem(item);
while(child)
{
m_ctrlTree.SetCheck(child, bCheck);
SetChildCheck(child, bCheck);
child = m_ctrlTree.GetNextItem(child, TVGN_NEXT);
}
}

/************************************************************************/
/* 设置父节点选中状态                                                 */
/************************************************************************/
void CHistoryDlg::SetParentCheck(HTREEITEM item, BOOL bCheck)
{
HTREEITEM parent = m_ctrlTree.GetParentItem(item);
if(parent == NULL)
return;

if(bCheck)
m_ctrlTree.SetCheck(parent, bCheck);
else
{
HTREEITEM bro = m_ctrlTree.GetNextItem(item, TVGN_NEXT);
BOOL bFlag = false;
while(bro)
{
if(m_ctrlTree.GetCheck(bro))
{
bFlag = true;
break;
}
bro = m_ctrlTree.GetNextItem(bro, TVGN_NEXT);
}
if(!bFlag)
{
bro = m_ctrlTree.GetNextItem(item, TVGN_PREVIOUS);
while(bro)
{
if(m_ctrlTree.GetCheck(bro))
{
bFlag = true;
break;
}
bro = m_ctrlTree.GetNextItem(bro, TVGN_PREVIOUS);
}
}
if(!bFlag)
m_ctrlTree.SetCheck(parent, false);
}

SetParentCheck(parent, GetCheck(parent));


你可能感兴趣的:(在CTreeCtrl中捕获复选框选中消息,父子节点选中状态联动)