带复选框的CTreeCtrl响应复选消息

1.在对话框中添加CTreeCtrl控件并勾选Check Boxes选项,为CTreeCtrl控件添加CTreeCtrl变量m_tree;

2.为CTreeCtrl控件添加NM_CLICK消息响应函数OnClickTree();代码如下:

OnClickTree(NMHDR* pNMHDR, LRESULT* pResult) 

{
    CPoint point;
    UINT uFlag;   //接收有关点击测试的信息的整数
    HTREEITEM hTree;
    BOOL bCheck;
    GetCursorPos(&point);    //获取屏幕鼠标坐标
    m_tree.ScreenToClient(&point);           //转化成客户坐标
    hTree = m_tree.HitTest(point,&uFlag);    //返回与CtreeCtrl关联的光标的当前位置和句柄

    if (hTree && (TVHT_ONITEMSTATEICON & uFlag))  //点中复选框
     {

          bCheck = m_treeSsid.GetCheck(hTree);      //获取当前复选状态
          SetChildCheck(hTree,!bCheck);                  //设置子项复选状态
      }
 
     *pResult = 0;
}

3.SetChildCheck()函数为自定义的处理函数(响应点击复选框后的具体处理函数):

下面的函数功能为:父项选中或取消选中,子项跟住选中或取消选中;

SetChildCheck(HTREEITEM hTree,BOOL bCheck)
{
  hTree = m_tree.GetChildItem(hTree);  //获取子项句柄
  while (hTree)
  {

      m_tree.SetCheck(hTree, bCheck);
      SetChildCheck(hTree,bCheck);     //递归调用
      hTree = m_tree.GetNextSiblingItem(hTree);    //获取兄弟的句柄
  }
 }

4.总结:关键是TVHT_ONITEMSTATEICON,它标志鼠标点击的是树形控件的复选框;

 

你可能感兴趣的:(C++文章)