天天看点

代码_MFC_右键菜单

精简代码

CMenu menu;
    menu.LoadMenu(IDR_MENU1);
    CMenu* pPopup = menu.GetSubMenu(0);
 
    ClientToScreen(&point);
    pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y,GetParent())
           

复杂代码

直接响应你要添加弹出菜单的窗口的OnContextMenu 

然后添加一下下面的代码就行了: 

C/C++ code ?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28

void

CMyF1Dlg::OnContextMenu(CWnd* pWnd, CPoint point) 

{

// CG: This block was added by the Pop-up Menu component//Pop-Up Menu在代码上就添加了下面的这段

{

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);

}

}

接下来你只需要建立一个ID为CG_IDR_POPUP_ABOUT_DLG的菜单就行了。

注意添加的时候有点情况下会是: 

C/C++ code ?

1

void

CMyF1Dlg::OnContextMenu(CWnd*  

, CPoint  

)

只需要把.h文件和.cpp文件对应的位置都改成: 

C/C++ code ?

1

void

CMyF1Dlg::OnContextMenu(CWnd* pWnd, CPoint point) 

就可以了。

VS已经放弃了VC6.0下那种通过控件来添加右键菜单的方法。  如果你自己看VC6.0下右键菜单的添加 跟我上面用代码添加其实是完全一样的。

VC6.0下添加右键菜单那个控件实际上就是帮你做了上面谢谢代码生成过程。 在VS下自己添加也是一样的。