visual c++中制作弹出式菜单
visual c++中制作弹出式菜单
菜单一般分两类,除了前面介绍的依附于框架窗口的一般菜单,另一类是浮动的弹出式菜单,也称为快捷菜单或上下文菜单。
在Visual C++中,弹出式菜单主要是通过CMenu类实现的。
请看下面的实例,为程序增加一个帮助、关于快捷菜单。
void CMyDlg::OnContextMenu(CWnd* pWnd, CPoint point)
{
CMenu mnu;
if(mnu.CreatePopupMenu())
{
mnu.AppendMenu(MF_STRING,ID_MYHELP,"帮助(&H)");
mnu.AppendMenu(MF_STRING,ID_MYABOUT,"关于(&A)…");
mnu.TrackPopupMenu(TPM_CENTERALIGN,point.x,point.y ,this);
}
}
运行结果如图1所示。

图1 快捷菜单实例运行结果
除了上面的方法,Visual C++还提供了更简便的方法。
(1)单击系统主菜单“Project”/“Add to Project”/“Components and Controls”,在弹出的“Components and Controls Gallery”对话框中选择“Visual C++ Components”文件夹,然后选择“Pop-up Menu”,如图2所示。

图2 “Components and Contrals Gallery”对话框
(2)单击“Insert”按钮,系统会要求用户确认,单击“确定”按钮,弹出“Pop-up Menu”对话框。
(3)在此对话框中,将“Add Pop-up Menu to”组合框的内容改为“CMyView”。单击“OK”按钮,将此快捷菜单添加到项目中。
(4)此时,在“Workspace”工作区中,“ResourceView”选项卡里会添加一个菜单资源,按照上面讲述的编辑普通菜单的方法编辑此快捷菜单。
(5)实际上,这种方法只是让系统自动为程序添加显示快捷菜单的代码,其OnContextMenu成员函数中会自动添加如下代码:
void CAboutDlg::OnContextMenu(CWnd*, CPoint point)
{
{
if (point.x == -1 && point.y == -1){
//keystroke invocation
CRect rect;
GetClientRect(rect);
ClientToScreen(rect);
point = rect.TopLeft();
point.Offset(5, 5);
}
CMenu menu;
VERIFY(menu.LoadMenu(CG_IDR_POPUP_ABOUT_DLG));
CMenu* pPopup = menu.GetSubMenu(0);
ASSERT(pPopup != NULL);
CWnd* pWndPopupOwner = this;
while (pWndPopupOwner->GetStyle() & WS_CHILD)
pWndPopupOwner = pWndPopupOwner->GetParent();
pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y,
pWndPopupOwner);
}
}