http://strongl.blog.163.com/blog/static/214315362008326102015494/
以下是MFC中关于菜单的操作,仅作记录。
1.如何在基于dialog的应用程序中添加菜单。
->在资源中添加新菜单并编辑,比如增加了IDR_MENU1这个菜单资源;
->在对话框的OnInitDialog()函数中添加如下代码:
// TODO: Add extra initialization here
CMenu menu; //可为局部变量
menu.LoadMenu(IDR_MENU1); //加载菜单资源使与CMenu Object相关联
SetMenu(&menu); // Sets the current menu to the specified menu( 这是CWnd的函数)
menu.Detach(); //这一步很关键,因为menu为局部变量,使用此函数 Detaches a Windows menu
//from a CMenu object and returns the handle. 就是说使HMENU与menu这个object相剥离
2.增加右键菜单
->方法一、 点击菜单栏Project->Add to Project->Components and Controls->Visual C++ Components->Pop-up Menu选择需要添加右键菜单的类即可,Visual会自动为该类添加函数void CMnDlg::OnContextMenu(CWnd*, CPoint point)和右键菜单资源CG_IDR_POPUP_MN_DLG,编辑该资源使符合我们的需求。
->方法二、参照上面Visual自动为我们添加的函数void CMnDlg::OnContextMenu(CWnd*, CPoint point)的写法添加我们自己写的右键菜单。具体步骤如下:
Step1.在资源中添加菜单资源IDR_MENU2
Step2.增加右键响应函数void CMnDlg::OnRButtonDown(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
ClientToScreen(&point); //将point从Client坐标转换到屏幕坐标
CMenu menu;
menu.LoadMenu(IDR_MENU2);
CMenu* pPopup=menu.GetSubMenu(0);
CWnd* pWndPopupOwner=this;
SetForegroundWindow( ); //增加此句可以解决系统托盘右键菜单不自动消失的问题
pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y,
pWndPopupOwner);
CDialog::OnRButtonDown(nFlags, point);
}