#include <afxwin.h> // MFC头文件 #include "resource.h" class CMyFrame : public CFrameWnd //…
- User
#include <afxwin.h> // MFC头文件 #include "resource.h" class CMyFrame : public CFrameWnd // 声明主框架(窗口)类 { DECLARE_MESSAGE_MAP() public: afx_msg int OnCreate(LPCREATESTRUCT); afx_msg void OnNew(); afx_msg void OnInitMenuPopup(CMenu , UINT, BOOL); afx_msg void OnContextMenu(CWnd, CPoint); CMenu menu;// 不能在成员函数中定义,会出异常 }; BEGIN_MESSAGE_MAP(CMyFrame,CFrameWnd) ON_WM_CREATE() ON_COMMAND(ID_NEW,OnNew) ON_WM_INITMENU() ON_WM_CONTEXTMENU() END_MESSAGE_MAP() afx_msg int CMyFrame::OnCreate(LPCREATESTRUCT pcs) { //CMenu menu; 注意不能是局部变量 menu.LoadMenu(IDR_MENU1); //API 函数实现 挂菜单 //::SetMenu(m_hWnd, menu.m_hMenu); SetMenu(&menu); return CFrameWnd::OnCreate(pcs); } void CMyFrame::OnNew() { AfxMessageBox("菜单项被点击"); } void CMyFrame::OnInitMenuPopup(CMenu * pPopup, UINT nPos, BOOL i) { pPopup->CheckMenuItem(ID_NEW, MF_CHECKED); } void CMyFrame::OnContextMenu(CWnd* pWnd, CPoint pt) { //HMENU hPopup = ::GetSubMenu(menu.m_hMenu, 0); //::TrackPopupMenu(hPopup, TPM_LEFTALIGN | TPM_TOPALIGN, pt.x, pt.y, // 0,this->m_hWnd,NULL); CMenu* pPopup = menu.GetSubMenu(0); pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_TOPALIGN, pt.x, pt.y, this); } class CMyApp : public CWinApp { public: CMyApp() { } virtual BOOL InitInstance() { CMyFrame *pFrame = new CMyFrame; //1)挂菜单方法 /*pFrame->Create(NULL, "MFCBASE", WS_OVERLAPPEDWINDOW, CFrameWnd::rectDefault, NULL, (CHAR )IDR_MENU1);/ pFrame->Create(NULL, "MFCBASE"); m_pMainWnd = pFrame; pFrame->ShowWindow(SW_SHOW); pFrame->UpdateWindow(); return TRUE; } }; CMyApp theApp; // 建立应用程序类的实例
增加菜单项和对应的响应函数,用消息处理机制处理
- Assistant
#include <afxwin.h> #include "resource.h"
class CMyFrame : public CFrameWnd { public: DECLARE_MESSAGE_MAP()
afx_msg int OnCreate(LPCREATESTRUCT); afx_msg void OnNew();};
BEGIN_MESSAGE_MAP(CMyFrame, CFrameWnd) ON_WM_CREATE() ON_COMMAND(ID_NEW, OnNew) END_MESSAGE_MAP()
afx_msg int CMyFrame::OnCreate(LPCREATESTRUCT pcs) { // 创建菜单 CMenu menu; menu.CreateMenu();
// 创建“文件”子菜单 CMenu fileMenu; fileMenu.CreatePopupMenu(); fileMenu.AppendMenu(MF_STRING, ID_NEW, "New"); menu.AppendMenu(MF_POPUP, (UINT_PTR)fileMenu.m_hMenu, "File"); // 设置菜单 SetMenu(&menu); return CFrameWnd::OnCreate(pcs);}
void CMyFrame::OnNew() { AfxMessageBox("New menu item clicked"); }
class CMyApp : public CWinApp { public: virtual BOOL InitInstance() { CMyFrame* pFrame = new CMyFrame; pFrame->Create(NULL, "MFCBASE");
m_pMainWnd = pFrame; pFrame->ShowWindow(SW_SHOW); pFrame->UpdateWindow(); return TRUE; }};
CMyApp theApp;