在Visual Studio 2008SP1中,要弹出上下文关联菜单的话,只需要在应用程序初始化的时候调用CWinAppEx::InitContextMenuManager,然后使用CWinAppEx::GetContextMenuManager获得一个指向应用程序的上下文管理器。
如果工程是单文档/多文档的话,可能会自动关联一个右键菜单,可以在应用程序的实现文件看到类似如下代码:
// CXXXApp 自定义加载/保存方法
void CXXXApp::PreLoadState()
{
BOOL bNameValid;
CString strName;
bNameValid = strName.LoadString(IDS_EDIT_MENU);
ASSERT(bNameValid);
GetContextMenuManager()->AddMenu(strName, IDR_POPUP_EDIT);
}
要弹出菜单的时候,只需要调用ShowPopupMenu即可。如下类似:
BOOL CXXXForEdit::PreTranslateMessage(MSG* pMsg)
{
if ((pMsg->message == WM_RBUTTONDOWN))
{
CPoint point(pMsg->pt);
theApp.GetContextMenuManager()->ShowPopupMenu(IDR_POPUP_EDIT, point.x, point.y, this, TRUE);
return TRUE;
}
else
return CXXXForEdit::PreTranslateMessage(pMsg);
}
如果是要弹出另一个菜单资源ID的话,需要先在CXXXApp::PreLoadState()里面添加快捷菜单,如下:
void CXXXApp::PreLoadState()
{
BOOL bNameValid;
CString strName;
bNameValid = strName.LoadString(IDS_EDIT_MENU);
ASSERT(bNameValid);
GetContextMenuManager()->AddMenu(strName, IDR_POPUP_EDIT);
GetContextMenuManager()->AddMenu(_T("专门编辑"), IDR_POPUP_FOREDIT);
}
这时,才能使用下面语句调用:
theApp.GetContextMenuManager()->ShowPopupMenu(IDR_POPUP_FOREDIT, point.x, point.y, this, TRUE);
要为菜单添加图标的话,要使用到CMFCToolBar::AddToolBarForImageCollection ()函数,其函数原型如下:
static BOOL __stdcall AddToolBarForImageCollection(
UINT uiResID, //Resource ID of a toolbar with images to load.
UINT uiBmpResID=0, //Resource ID of a bitmap with toolbar images.
UINT uiColdResID=0, //Resource ID of a bitmap with "cold" toolbar images.
UINT uiMenuResID=0, //Resource ID of a bitmap with menu images.
UINT uiDisabledResID=0,//Resource ID of a bitmap with disabled toolbar images.
UINT uiMenuDisabledResID=0 //Resource ID of a bitmap with disabled menu images.
);
在资源视图ToolBar插入一个ToolBar,然后创建四个工具栏对象,如下图所示:
接着四个工具栏对象的ID号要跟需要绑定到菜单项图标的ID号一致,且顺序一致。接着把预先准备好的工具栏图像位图BMP,加载到资源视图里面,修改其ID为IDB_POPUP_BITMAP,如下图所示:
然后,在初始化函数OnInitialUpdate()下添加入下代码:
CMFCToolBar::AddToolBarForImageCollection (IDR_TOOLBAR1,IDB_POPUP_BITMAP);
运行程序就可以看到效果了,但是此时还是灰色状态,为菜单项“添加事件处理程序”,结果如下图所示:
参考资料:
1.CContextMenuManager
2.CMFCToolBar::AddToolBarForImageCollection
3.BCGControlBar菜单编程方法详解