C++|右键菜单,动态创建

【C++|右键菜单,动态创建】case WM_RBUTTONDOWN://弹出右键菜单
{
CMenu menu1;
menu1.CreatePopupMenu(); //动态创建弹出式菜单对象
menu1.AppendMenu(MF_STRING, 1, " 菜单项1");
menu1.AppendMenu(MF_STRING, 2, " 菜单项2");
CPoint pt;
GetCursorPos(&pt);
CWnd *pWnd = CWnd::FromHandle(hwnd);
menu1.TrackPopupMenu(TPM_RIGHTBUTTON, pt.x, pt.y, pWnd);
menu1.DestroyMenu();
}
break;

自定义右键菜单:
C++|右键菜单,动态创建
文章图片

1 #ifndef_CONTEXTMENU_H_ 2 #define _CONTEXTMENU_H_ 3 #include 4 5 6 //动态菜单 7 #defineITEM_MENU_REPLY40001 8 #defineITEM_MENU_ALLREPLAY 40002 9 #defineITEM_MENU_RELAY 40003 10 #defineITEM_MENU_DELETE 40004 11 #defineITEM_MENU_FINALDELETE 40005 12 #defineITEM_MEUN_MARK 40006 13 #defineITEM_SUBMENU_UNSEEN 40007 14 #define ITEM_SUBMENU_SEEN 40008 15 16 17 class CContextPopMenu 18 { 19 public: 20CContextPopMenu(); 21~CContextPopMenu(); 22 23void PopMenu(HWND hwnd,int nX,int nY ); 24void PopMenu(HWND hwnd,const POINT& pt); 25 26void EnableMenu(int nItem,bool nEnable); 27 private: 28HMENU m_pPopMenu; 29 }; 30 #endif

C++|右键菜单,动态创建
文章图片


C++|右键菜单,动态创建
文章图片

1 #include "ContextMenu.h" 2 3 CContextPopMenu::CContextPopMenu() 4 { 5m_pPopMenu = CreatePopupMenu(); 6if (m_pPopMenu) 7{ 8HMENU Submenu = ::CreatePopupMenu(); 9::InsertMenu(m_pPopMenu,(-1),MF_BYPOSITION,ITEM_MENU_REPLY,TEXT("回复")); 10::InsertMenu(m_pPopMenu,(-1),MF_BYPOSITION,ITEM_MENU_ALLREPLAY,TEXT("全部回复")); 11::InsertMenu(m_pPopMenu,(-1),MF_BYPOSITION,ITEM_MENU_RELAY,TEXT("转发")); 12::InsertMenu(m_pPopMenu,(-1),MF_BYPOSITION,ITEM_MENU_DELETE,TEXT("删除")); 13::InsertMenu(m_pPopMenu,(-1),MF_BYPOSITION,ITEM_MENU_FINALDELETE,TEXT("彻底删除")); 14::InsertMenu(m_pPopMenu,(-1),MF_BYPOSITION|MF_POPUP,(unsigned int)Submenu,TEXT("标记")); 15::InsertMenu(Submenu,(-1),MF_BYPOSITION|MF_POPUP,ITEM_SUBMENU_UNSEEN,TEXT("未读邮件")); 16::InsertMenu(Submenu,(-1),MF_BYPOSITION|MF_POPUP,ITEM_SUBMENU_SEEN,TEXT("已读邮件")); 17} 18 } 19 20 CContextPopMenu::~CContextPopMenu() 21 { 22if (m_pPopMenu) 23{ 24DestroyMenu(m_pPopMenu); 25m_pPopMenu = NULL; 26} 27 } 28 29 void CContextPopMenu::PopMenu(HWND hwnd,int nX,int nY ) 30 { 31if (m_pPopMenu && hwnd) 32{ 33TrackPopupMenu(m_pPopMenu,TPM_LEFTALIGN|TPM_RIGHTBUTTON,nX,nY,0,hwnd,NULL) 34} 35 } 36 37 void CContextPopMenu::PopMenu(HWND hwnd,const POINT& pt) 38 { 39PopMenu(hwnd,pt.x,pt.y); 40 }

C++|右键菜单,动态创建
文章图片


然后在WndProc回调函数,响应WM_RBUTTONUP函数时创建
C++|右键菜单,动态创建
文章图片

1 case WM_RBUTTONUP: 2POINT pt; 3::GetCursorPos(&pt); 4CContextPopMenu* pPopMenu = new CContextPopMenu; 5pPopMenu->PopMenu(hwnd,pt); 6 break;

C++|右键菜单,动态创建
文章图片


对每个菜单项的响应在WM_COMMAND消息里处理
C++|右键菜单,动态创建
文章图片

1 case WM_COMMAND: 2switch(LOWORD(wParam)) 3{ 4case ITEM_MENU_REPLY: 5MessageBox(NULL,TEXT("响应回复菜单项"),TEXT("提示"),MB_OK); 6break; ; 7case ITEM_SUBMENU_UNSEEN: 8MessageBox(NULL,TEXT("响应标记子菜单项"),TEXT("提示"),MB_OK); 9break; 10}

C++|右键菜单,动态创建
文章图片

    推荐阅读