MFC入门示例之树控件(CTreeControl)

MFC入门示例之树控件(CTreeControl)_第1张图片

 1 //增加按钮
 2 void CMFCApplication8Dlg::OnBnClickedButtonAdd()
 3 {
 4     //树中添加节点
 5     CString strText;
 6     GetDlgItemText(IDC_EDIT1, strText);
 7     if (strText.GetLength() == 0) {
 8         AfxMessageBox(TEXT("请输入文本"));
 9         return;
10     }
11     HTREEITEM hItem = m_tree.GetSelectedItem();//获取当前被选中的节点
12     if (hItem == NULL) 
13         hItem = TVI_ROOT;
14     
15     TVINSERTSTRUCT ts = { 0 };
16     ts.hParent = hItem;
17     ts.hInsertAfter = TVI_LAST;
18     ts.item.pszText = strText.GetBuffer();
19     ts.item.mask = TVIF_TEXT;
20     HTREEITEM hNewItem = m_tree.InsertItem(&ts);
21     m_tree.SelectItem(hNewItem);        //选中新加入的节点
22     m_tree.EnsureVisible(hNewItem);        //树太高看不见问题
23 }
24 
25 //删除按钮
26 void CMFCApplication8Dlg::OnBnClickedButtonDel()
27 {
28     //获取当前被选中的节点
29     HTREEITEM hItem = m_tree.GetSelectedItem();//获取当前被选中的节点
30     if (hItem == NULL) {
31         AfxMessageBox(TEXT("请选择一个节点"));
32         return;
33     }
34     HTREEITEM hParent = m_tree.GetParentItem(hItem);
35     m_tree.DeleteItem(hItem);
36     m_tree.SelectItem(hParent);
37 }
38 
39 //修改按钮
40 void CMFCApplication8Dlg::OnBnClickedButtonUpdate()
41 {
42     //获取当前被选中的节点
43     HTREEITEM hItem = m_tree.GetSelectedItem();//获取当前被选中的节点
44     if (hItem == NULL) {
45         AfxMessageBox(TEXT("请选择一个节点"));
46         return;
47     }
48     CString strText;
49     GetDlgItemText(IDC_EDIT1, strText);
50     if (strText.GetLength() == 0) {
51         AfxMessageBox(TEXT("请输入文本"));
52         return;
53     }
54     m_tree.SetItemText(hItem, strText);
55 }
56 
57 //选中新节点事件
58 void CMFCApplication8Dlg::OnTvnSelchangedTree1(NMHDR *pNMHDR, LRESULT *pResult)
59 {
60     LPNMTREEVIEW pNMTreeView = reinterpret_cast(pNMHDR);
61     //获取当前被选中的节点
62     HTREEITEM hItem = m_tree.GetSelectedItem();//获取当前被选中的节点
63     if (hItem != NULL) {
64         CString strText = m_tree.GetItemText(hItem);
65         SetDlgItemText(IDC_EDIT1, strText);        //选中节点文本添加到编辑框中
66     }
67 
68     *pResult = 0;
69 }

 

转载于:https://www.cnblogs.com/runtimeexception/p/9212568.html

你可能感兴趣的:(MFC入门示例之树控件(CTreeControl))