树形控件(CTreeCtrl和CTreeView)

时间:2024-07-05 23:04:50

插入数据项

通过InsertItem()方法,有四种重载样式:

HTREEITEM InsertItem(LPTVINSERTSTRUCT lpInsertStruct);
HTREEITEM InsertItem(UINT nMask, LPCTSTR lpszItem, int nImage,int nSelectedImage, UINT nState, UINT nStateMask, LPARAM lParam,HTREEITEM hParent, HTREEITEM hInsertAfter);
HTREEITEM InsertItem(LPCTSTR lpszItem, HTREEITEM hParent = TVI_ROOT,HTREEITEM hInsertAfter = TVI_LAST);
HTREEITEM InsertItem(LPCTSTR lpszItem, int nImage, int nSelectedImage,HTREEITEM hParent = TVI_ROOT, HTREEITEM hInsertAfter = TVI_LAST);

索引

lpInsertStruct TVINSERTSTRUCT结构指针,TVINSERTSTRUCT结构中包含了插入操作的详细信息
nMask 节点的哪些信息被设置
lpszItem 节点的文本
nImage 节点的图像索引
nSelectedImage 节点选中时的图像索引
nState 节点的哪些状态被设置
lParam 指定关联节点的附加信息
hParent 父节点句柄
hInsertAfter 新插入节点后面的节点句柄

示例:

    CString userTreeHeader[]={"医生","售药员","管理员"};

    HTREEITEM userItem[];
for(int i=;i<;i++)
{
userItem[i]=m_theTreeCtrl->InsertItem(userTreeHeader[i],,,TVI_ROOT,TVI_LAST);
m_theTreeCtrl->SetItemData(userItem[i],(DWORD)i);
}

如何添加鼠标右击事件?

控件中添加NM_RCLICK事件。
示例:

void CMyDlg::OnRclickTree1(NMHDR* pNMHDR, LRESULT* pResult)
{
CPoint cp;
GetCursorPos(&cp);
m_Tree.ScreenToClient(&cp);
HTREEITEM titem = m_Tree.HitTest(cp, NULL);
// 以上很关键,保证右键点击的位置是树叶或树枝
if(titem)
{
AfxMessageBox(m_Tree.GetItemText(titem));
}
*pResult=0;
}