一.在ResourceView选项卡的Menu下添加一个菜单资源
![]()
二.在View的属性->消息->添加WM_CONTEXTMENU
![]()
三.在View里添加如下代码:
1 void CTestView::OnContextMenu(CWnd* /*pWnd*/, CPoint point)
2 {
3 // TODO: 在此处添加消息处理程序代码
4 //if (point.x == -1 && point.y == -1){
5 // CRect rect;
6 // GetClientRect(rect);
7 // ClientToScreen(rect);
8 // point = rect.TopLeft();
9 // point.Offset(5, 5);
10 // }
11 // CMenu menu;
12 // VERIFY(menu.LoadMenu(IDR_MENU1)); //CG_IDR_POPUP_TYPING_TEST_VIEW为菜单ID
13 // CMenu* pPopup = menu.GetSubMenu(0);
14 // ASSERT(pPopup != NULL);
15 // CWnd* pWndPopupOwner = this;
16 // while (pWndPopupOwner->GetStyle() & WS_CHILD) pWndPopupOwner = pWndPopupOwner->GetParent();
17 // pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y,pWndPopupOwner);
18
19 if (point.x == -1 && point.y == -1){
20 //keystroke invocation
21 CRect rect;
22 GetClientRect(rect);
23 ClientToScreen(rect); //把客户区坐标转换为屏幕坐标
24
25 point = rect.TopLeft();
26 point.Offset(5, 5);
27 }
28
29 CMenu menu;
30 VERIFY(menu.LoadMenu(IDR_MENU1)); //IDR_MENU1为右键菜单ID
31
32 CMenu* pPopup = menu.GetSubMenu(0);
33 ASSERT(pPopup != NULL);
34 CWnd* pWndPopupOwner = this;
35
36 while (pWndPopupOwner->GetStyle() & WS_CHILD)
37 pWndPopupOwner = pWndPopupOwner->GetParent();
38
39 pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y,
40 pWndPopupOwner); //显示一个快捷菜单
41 }