为树形控件添加弹出式菜单,并跟踪所选择的项
动态弹出式菜单
//获取当前右键的位置 CPoint pt; GetCursorPos(&pt); m_tree.ScreenToClient(&pt); //判断右键的位置处是否是树形控件的一个节点 //若有,则弹出右键菜单 HTREEITEM hItem = m_tree.HitTest(pt); if(m_tree.GetParentItem(m_tree.GetParentItem(hItem))!=NULL&&m_tree.GetChildItem(hItem)!=NULL) bShouldPop=TRUE; if(hItem != NULL && bShouldPop) { m_tree.SelectItem(hItem); //弹出菜单的位置,为后面的 TrackPopupMenu() 使用 GetCursorPos(&pt); CMenu popupmenu; //生成一个弹出菜单 popupmenu.CreatePopupMenu(); ASSERT(popupmenu!=NULL); //添加菜单项 popupmenu.AppendMenu(MF_STRING|MF_ENABLED,IDM_ITEM_SHOW,_T("show")); popupmenu.AppendMenu(MF_SEPARATOR); popupmenu.AppendMenu(MF_STRING|MF_ENABLED,IDM_ITEM_HIDE,_T("hide")); //弹出 int nCmd=(int)popupmenu.TrackPopupMenu(TPM_LEFTALIGN|TPM_LEFTBUTTON, pt.x,pt.y,this); } 也可以用已有的菜单资源弹出一个菜单的子项
void CLeaveDlg::OnRclickTree(NMHDR* pNMHDR, LRESULT* pResult) { // TODO: Add your control notification handler code here CMenu menu; menu.LoadMenu(IDR_MENU_SHOW);
CBitmap bitmap; //为菜单子项添加图标 bitmap.LoadBitmap(IDB_BITMAP_BIG); deviceTreeMenu.SetMenuItemBitmaps(IDC_MENU_DEVICE_RENAME,MF_BYCOMMAND/*|MF_BYPOSITION*/, &bitmap,&bitmap);
//获取当前右键的位置 CPoint pt; GetCursorPos(&pt); m_tree.ScreenToClient(&pt); HTREEITEM hSelTree = m_tree.HitTest(pt); if ( hSelTree != NULL && m_tree.GetParentItem(hSelTree) != NULL ) { m_tree.SelectItem(hSelTree); m_tree.ClientToScreen(&pt); menu.GetSubMenu(1)->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, pt.x, pt.y, this); } *pResult = 0; }
动态创建菜单步骤: