MFC控件之树型控件CTreeCtrl

1、添加内容

	//添加第一层节点
	TV_INSERTSTRUCT tvfirst;
	tvfirst.hParent = NULL;
	tvfirst.item.mask = TVIF_TEXT;
	tvfirst.item.pszText = "一级单位1";
	HTREEITEM firstItem = m_tree.InsertItem(&tvfirst);
	//添加二级单位节点
    TV_INSERTSTRUCT tvsecond;
	tvsecond.hParent = firstItem;
	tvsecond.item.mask = TVIF_TEXT;
	tvsecond.item.pszText = "二级单位1";
	HTREEITEM seconditem = m_tree.InsertItem(&tvsecond);

2、展开节点

m_tree.Expand(firstItem,TVE_EXPAND);

3、获取checkbox选中状态

参考:http://blog.csdn.net/headmaster110/article/details/5097972
//在对话框中添加CTreeCtrl控件并勾选Check Boxes选项,为CTreeCtrl控件添加CTreeCtrl变量m_tree;
//为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;
}
//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);    //获取兄弟的句柄
  }
 }
 
//总结:关键是TVHT_ONITEMSTATEICON,它标志鼠标点击的是树形控件的复选框;


你可能感兴趣的:(MFC控件之树型控件CTreeCtrl)