MFC Tree Control
1,先拖拽控件在窗口中
2,设置属性:
Has Line :用虚线链接节点层次
Has Buton :添加折叠和展开按钮
3,设置图片的集合
3.1 SetImageList(CImageList *list,正常显示的宏)
3.1.1 CImageList 对象声明在.h文件中,在堆中使用过会被回收
3.2 创建create(30,30 xx位色,4,4)
3.3 add(HICON)
4,添加节点
4.1 InsertItem(节点名称,显示图片,选中后显示的图,父节点)
5,设置默认节点 SelectItem
//1 设置图标 //CImageList list;//图标列表要声明为全局的,否则放在堆中使用后会被删除掉,应放在.h文件中 //1.1准备HICON图标 HICON icons[3]; //从可执行文件加载 nIDResource 指定的图标资源 icons[0] = AfxGetApp()->LoadIconW(IDI_ICON2); icons[1] = AfxGetApp()->LoadIconW(IDI_ICON3); icons[2] = AfxGetApp()->LoadIconW(IDI_ICON4); //创建图片的集合 list.Create(30,30,ILC_COLOR32,4,4); //添加具体的图片 for (int i = 0; i < 3; i++) { list.Add(icons[i]); } mTree.SetImageList(&list,TVSIL_NORMAL); //2 设置节点节点名称,默认图片,选中图片时显示什么 HTREEITEM root = mTree.InsertItem(TEXT("根节点"), 0, 0, 0); HTREEITEM father=mTree.InsertItem(TEXT("父节点"), 1,1, root); HTREEITEM sub1 = mTree.InsertItem(TEXT("子节点"), 2,2, father); HTREEITEM sub2= mTree.InsertItem(TEXT("子节点"), 2, 2, father); //设置默认选项 mTree.SelectItem(sub1);
6,节点间切换触发事件
6.1,获取当前项GetSelectedItem
6.2,根据项获取内容GetItemText
void CMFC06TreeControlDlg::OnTvnSelchangedTree1(NMHDR* pNMHDR, LRESULT* pResult) { LPNMTREEVIEW pNMTreeView = reinterpret_cast<LPNMTREEVIEW>(pNMHDR); // TODO: 在此添加控件通知处理程序代码 *pResult = 0; //获取当前选中项句柄 HTREEITEM item = mTree.GetSelectedItem(); //根据选中项句柄找到内容 CString name = mTree.GetItemText(item); MessageBox(name, _T("name")); }