先添加一个树形控件,再增加控件类型变量m_ctltree, 然后修改树形控件的3个风格has lines和lines at root, has buttons为true以便美观。然后映射右键消息。再添加一个菜单资源IDR_MENU1。再添加下面的代码
void XXXDLG::OnNMRClickTree1(NMHDR *pNMHDR, LRESULT *pResult)
{
// TODO: 在此添加控件通知处理程序代码
CPoint point;
GetCursorPos(&point); // 当前鼠标坐标
CPoint PointInTree = point;
POINT pt;
GetCursorPos(&pt);
UINT uFlags;
//将屏幕坐标转化为客户区坐标
ScreenToClient(&pt);
MapWindowPoints(&m_ctltree, &pt,1);
//获取鼠标点中位置的item
HTREEITEM hItem = m_ctltree.HitTest(pt,&uFlags);
if ((hItem != NULL) && (TVHT_ONITEM & uFlags))
{
//选中点中的item
m_ctltree.Select(hItem, TVGN_CARET);
}
//必不可少,将客户区坐标转化为屏幕坐标
ClientToScreen(&pt);
//弹出右键菜单
CMenu menu;
CMenu *ptrMenu;
int nResult = menu.LoadMenu(IDR_MENU1);
if ( 0 == nResult)
return;
ptrMenu= menu.GetSubMenu(0);
ptrMenu->TrackPopupMenu
(
TPM_LEFTALIGN|TPM_RIGHTBUTTON,
point.x,
point.y,
this,
NULL);
*pResult = 0;
}
//判断选取的节点在第几层
HTREEITEM hItem = m_ctltree.GetSelectedItem();
int nCount = 0;
while(hItem)
{
nCount ++;
hItem = m_ctltree.GetParentItem(hItem);
}