[cpp]
///"添加"按鈕的響應函數
void CTreeCtrlDemoDlg::OnBtnAdd()
{
// TODO: Add your control notification handler code here
///獲取用戶的輸入
CString strText;
GetDlgItemText(IDC_EDT_TEXT, strText);
if(strText.GetLength() == 0)
{
AfxMessageBox(_T("請輸入文本!"));
return ;
}
///獲取當前所選結點
HTREEITEM hItem = m_tree.GetSelectedItem();
///如果當前沒有選中節點,則添加根節點
if(hItem== NULL)
{
hItem = TVI_ROOT;
}
///節點數據
TVINSERTSTRUCT ts = {0};
//新節點的父節點
ts.hParent = hItem;
///新節點添加在同級節點最後
ts.hInsertAfter = TVI_LAST;
///新節點的文本
ts.item.pszText = (LPTSTR)(LPCTSTR)strText;
///讓文本成員有效
ts.item.mask = TVIF_TEXT;
///添加新節點
HTREEITEM hNewItem = m_tree.InsertItem(&ts);
///選中新節點
m_tree.SelectItem(hNewItem);
///確保新節點在可視范圍內
m_tree.EnsureVisible(hNewItem);
}
///"刪除"按鈕的響應函數
void CTreeCtrlDemoDlg::OnBtnDelete()
{
// TODO: Add your control notification handler code here
///獲取當前所選結點
HTREEITEM hItem = m_tree.GetSelectedItem();
if(hItem ==NULL)
{
AfxMessageBox(_T("請選擇一個結點!"));
return ;
}
//取得當前結點的父節點
HTREEITEM hParent = m_tree.GetParentItem(hItem);
///刪除結點
m_tree.DeleteItem(hItem);
///選中其父節點
m_tree.SelectItem(hParent);
}
///"修改"按鈕的消息響應函數
void CTreeCtrlDemoDlg::OnBtnEdit()
{
// TODO: Add your control notification handler code here
///獲取當前選中的結點
HTREEITEM hItem = m_tree.GetSelectedItem();
if(hItem == NULL)
{
AfxMessageBox(_T("請選擇一個節點!"));
return ;
}
///獲取用戶的輸入
CString strText;
GetDlgItemText(IDC_EDT_TEXT , strText);
if(strText.GetLength() == 0)
{
AfxMessageBox(_T("請輸入文本!"));
return ;
}
///修改結點文本
m_tree.SetItemText(hItem,strText);
}
///樹形控件“TVN_SELCHANGEED”通知消息的響應函數
///控件當前結點改變時的消息處理
void CTreeCtrlDemoDlg::OnSelchangedTree(NMHDR* pNMHDR, LRESULT* pResult)
{
NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR;
// TODO: Add your control notification handler code here
///獲取當前所選結點
HTREEITEM hItem = m_tree.GetSelectedItem();
if(hItem != NULL)
{
///獲取結點文本
CString strText= m_tree.GetItemText(hItem);
///將結點文本顯示在文本框中
SetDlgItemText(IDC_EDT_TEXT , strText);
}
*pResult = 0;
}
界面解釋:
樹形控件ID為IDC_TREE,關聯變量m_tree ,選中style:has buttons 、has lines 、lines at root 、show selection always;
按鈕ID為IDC_BTN_ADD、IDC_BTN_EDIT、 IDC_BTN_DELETE
文本框ID為IDC_EDT_TEXT