MFC Tree Control
1. First drag the control in the window
2. Set properties:
Has Line: Use dotted lines to link node levels
Has Buton: add collapse and expand buttons
3. Set the collection of pictures
3.1 SetImageList (CImageList *list, normal display macro)
3.1.1 The CImageList object is declared in the .h file and will be recycled if used in the heap
3.2 Create create(30, 30 xx bit color, 4, 4)
3.3 add(HICON)
4. Add node
4.1 InsertItem (node name, display picture, selected picture, parent node)
5. Set the default node SelectItem
//1 set icon //CImageList list;//The icon list should be declared as global, otherwise it will be deleted after being placed in the heap and should be placed in the .h file //1.1 Prepare HICON icon HICON icons[3]; //Load the icon resource specified by nIDResource from the executable file icons[0] = AfxGetApp()->LoadIconW(IDI_ICON2); icons[1] = AfxGetApp()->LoadIconW(IDI_ICON3); icons[2] = AfxGetApp()->LoadIconW(IDI_ICON4); //Create a collection of pictures list.Create(30,30,ILC_COLOR32,4,4); //Add specific pictures for (int i = 0; i < 3; i++) { list.Add(icons[i]); } mTree.SetImageList(&list,TVSIL_NORMAL); //2 Set the name of the node node, the default picture, what is displayed when the picture is selected HTREEITEM root = mTree.InsertItem(TEXT("root node"), 0, 0, 0); HTREEITEM father=mTree.InsertItem(TEXT("parent node"), 1,1, root); HTREEITEM sub1 = mTree.InsertItem(TEXT("child node"), 2,2, father); HTREEITEM sub2 = mTree.InsertItem(TEXT("child node"), 2, 2, father); //Set default options mTree.SelectItem(sub1);
6. Trigger events for switching between nodes
6.1, Get the current item GetSelectedItem
6.2, get the content GetItemText according to the item
void CMFC06TreeControlDlg::OnTvnSelchangedTree1(NMHDR* pNMHDR, LRESULT* pResult) { LPNMTREEVIEW pNMTreeView = reinterpret_cast<LPNMTREEVIEW>(pNMHDR); // TODO: Add control notification handler code here Director * = 0; //Get the handle of the currently selected item HTREEITEM item = mTree.GetSelectedItem(); //Find the content according to the selected item handle CString name = mTree.GetItemText(item); MessageBox(name, _T("name")); }