树形控件(Tree Control)
[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
补充:软件开发 , C++ ,