[Cpp]
/// Response function of the "add" button
Void CTreeCtrlDemoDlg: OnBtnAdd ()
{
// TODO: Add your control notification handler code here
/// Obtain user input
CString strText;
GetDlgItemText (IDC_EDT_TEXT, strText );
If (strText. GetLength () = 0)
{
AfxMessageBox (_ T ("Enter the text! "));
Return;
}
/// Obtain the currently selected node
HTREEITEM hItem = m_tree.GetSelectedItem ();
/// If no node is selected, add the root node
If (hItem = NULL)
{
HItem = TVI_ROOT;
}
/// Node data
TVINSERTSTRUCT ts = {0 };
// Parent node of the new node
Ts. hParent = hItem;
/// Add the new node to the end of the same-level node
Ts. hInsertAfter = TVI_LAST;
/// Text of the new node
Ts. item. pszText = (LPTSTR) (LPCTSTR) strText;
/// Make the text Member valid
Ts. item. mask = TVIF_TEXT;
/// Add a new node
HTREEITEM hNewItem = m_tree.InsertItem (& ts );
/// Select a new node
M_tree.SelectItem (hNewItem );
/// Make sure that the new node is within the visible range
M_tree.EnsureVisible (hNewItem );
}
/// Response function of the delete button
Void CTreeCtrlDemoDlg: OnBtnDelete ()
{
// TODO: Add your control notification handler code here
/// Obtain the currently selected node
HTREEITEM hItem = m_tree.GetSelectedItem ();
If (hItem = NULL)
{
AfxMessageBox (_ T ("select a node! "));
Return;
}
// Obtain the parent node of the current node
HTREEITEM hParent = m_tree.GetParentItem (hItem );
/// Delete a node
M_tree.DeleteItem (hItem );
/// Select its parent node
M_tree.SelectItem (hParent );
}
/// Message response function of the "modify" button
Void CTreeCtrlDemoDlg: OnBtnEdit ()
{
// TODO: Add your control notification handler code here
/// Obtain the selected node
HTREEITEM hItem = m_tree.GetSelectedItem ();
If (hItem = NULL)
{
AfxMessageBox (_ T ("select a node! "));
Return;
}
/// Obtain user input
CString strText;
GetDlgItemText (IDC_EDT_TEXT, strText );
If (strText. GetLength () = 0)
{
AfxMessageBox (_ T ("Enter the text! "));
Return;
}
/// Modify the node text
M_tree.SetItemText (hItem, strText );
}
/// Response function of the notification message in the "TVN_SELCHANGEED" tree control
/// Message processing when the current node of the control changes
Void CTreeCtrlDemoDlg: OnSelchangedTree (NMHDR * pNMHDR, LRESULT * pResult)
{
NM_TREEVIEW * pNMTreeView = (NM_TREEVIEW *) pNMHDR;
// TODO: Add your control notification handler code here
/// Obtain the currently selected node
HTREEITEM hItem = m_tree.GetSelectedItem ();
If (hItem! = NULL)
{
/// Obtain the node text
CString strText = m_tree.GetItemText (hItem );
/// Display the node text in the text box
SetDlgItemText (IDC_EDT_TEXT, strText );
}
* PResult = 0;
}
Interface explanation:
Tree Control ID: IDC_TREE, associated variable m_tree, selected style: has buttons, has lines, lines at root, show selection always;
The buttons are IDC_BTN_ADD, IDC_BTN_EDIT, and IDC_BTN_DELETE.
The text box ID is IDC_EDT_TEXT.