一:范例代码:
//树控件使用 //1 、设置图标 //准备HICON图标 HICON icons[4]; icons[0] = AfxGetApp()->LoadIconW(IDI_ICON1); icons[1] = AfxGetApp()->LoadIconW(IDI_ICON2); icons[2] = AfxGetApp()->LoadIconW(IDI_ICON3); icons[3] = AfxGetApp()->LoadIconW(IDI_ICON4); //CImageList list; //必须保存住这个集合 写到.h做成员属性 //创建图片集合 list.Create(30, 30, ILC_COLOR32, 4, 4); //添加具体的图片 for (int i = 0; i < 4;i++) { list.Add(icons[i]); } m_tree.SetImageList(&list, TVSIL_NORMAL); //2 、设置节点 HTREEITEM root = m_tree.InsertItem(TEXT("根节点"), 0, 0, NULL); HTREEITEM parent = m_tree.InsertItem(TEXT("父节点"), 1, 1, root); HTREEITEM sub1 = m_tree.InsertItem(TEXT("子节点1"), 2, 2, parent); HTREEITEM sub2 = m_tree.InsertItem(TEXT("子节点2"), 3, 3, parent); //设置默认选项 m_tree.SelectItem(sub1);
运行结果:
二:常用函数
遍历树节点相关函数: HTREEITEM GetRootItem() const; HTREEITEM GetNextItem(HTREEITEM hItem, UINT nCode) const HTREEITEM GetChildItem(HTREEITEM hItem) const HTREEITEM GetNextSiblingItem(HTREEITEM hItem) const HTREEITEM GetPrevSiblingItem(HTREEITEM hItem) const HTREEITEM GetParentItem(HTREEITEM hItem) const HTREEITEM GetFirstVisibleItem() const HTREEITEM GetNextVisibleItem(HTREEITEM hItem) const HTREEITEM GetPrevVisibleItem(HTREEITEM hItem) const HTREEITEM GetLastVisibleItem() const 获取设置节点标题: CString GetItemText(_In_ HTREEITEM hItem) const; BOOL SetItemText(_In_ HTREEITEM hItem, _In_z_ LPCTSTR lpszItem); 获得或设置选择的节点: HTREEITEM GetSelectedItem() const BOOL SelectItem(HTREEITEM hItem) 是否有子节点:BOOL ItemHasChildren(_In_ HTREEITEM hItem) const; 检測点是否在树节点区域:HTREEITEM HitTest(_In_ CPoint pt, _In_opt_ UINT* pFlags = NULL)const; 推断是否是否最顶层节点用GetParentItem(hItem)== NULL