- <span style="font-size:24px;color:#ff0000;">为树形控件添加弹出式菜单,并跟踪所选择的项</span>
-
- 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);
-
-
- 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)
- {
-
- CMenu menu;
- menu.LoadMenu(IDR_MENU_SHOW);
- CBitmap bitmap;
- bitmap.LoadBitmap(IDB_BITMAP_BIG);
-
- deviceTreeMenu.SetMenuItemBitmaps(IDC_MENU_DEVICE_RENAME,MF_BYCOMMAND,
- &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;
- }
动态创建菜单步骤:
1创建一个基于对话框的应用程序
2在对话框的头文件中声明一个CMenu类对象m_Menu;
3打开Resource.h,在此文件中定义命令ID。代码为:#define
ID_MENUCAT
1001
4在对话框的OnInitDialog方法中创建菜单。代码如下:
m_Menu.CreateMenu();
//创建菜单窗口
CMenu m_PopMenu;
//定义菜单类对象
m_PopMenu.CreatePopupMenu();
//创建弹出菜单窗口
m_Menu.AppendMenu(MF_POPUP,(UINT)m_PopMenu.m_hMenu,"动物");//插入菜单
m_PopMenu.AppendMenu(MF_STRING,ID_MENUCAT,"猫");
//插入子菜单
m_PopMenu.Detach();
//分离菜单句柄
SetMenu(&m_Menu);//菜单与窗口关联
5在对话框的头文件中声明菜单的消息处理函数,代码为
afx_msg void
OnMenucat();
6在对话框的源文件中添加消息映射宏,将命令ID关联到消息处理函数中。代码如下:
ON_COMMAND(ID_MENUCAT, OnMenucat)
//关联命令ID和消息处理函数
7最后一步,在对话框的源文件中添加消息处理函数的实现代码
void
CCreateMenuDlg::OnMenucat()
{
MessageBox("猫菜单被按下");
}
为树形控件添加弹出式菜单,并跟踪所选择的项,布布扣,bubuko.com
为树形控件添加弹出式菜单,并跟踪所选择的项
原文:http://www.cnblogs.com/lidabo/p/3701758.html