[cpp] view plaincopy
- <span style="font-size:24px;color:#ff0000;">为树形控件添加弹出式菜单,并跟踪所选择的项</span>
[cpp] view plaincopy
- 动态弹出式菜单
[cpp] view plaincopy
- //获取当前右键的位置
- 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);
- }
- 也可以用已有的菜单资源弹出一个菜单的子项
[cpp] view plaincopy
- void CLeaveDlg::OnRclickTree(NMHDR* pNMHDR, LRESULT* pResult)
- {
- // TODO: Add your control notification handler code here
- CMenu menu;
- menu.LoadMenu(IDR_MENU_SHOW);
[cpp] view plaincopy
- CBitmap bitmap; //为菜单子项添加图标
- bitmap.LoadBitmap(IDB_BITMAP_BIG);
- deviceTreeMenu.SetMenuItemBitmaps(IDC_MENU_DEVICE_RENAME,MF_BYCOMMAND/*|MF_BYPOSITION*/,
- &bitmap,&bitmap);
[cpp] view plaincopy
- //获取当前右键的位置
- 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;
- }
[cpp] view plaincopy
动态创建菜单步骤:
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("猫菜单被按下");
}