探究MFC之Dialog系统菜单添加
本文描述给Dialog增加系统菜单;单击对话框左上角menu弹出的菜单,我们称为该对话框的系统菜单。
- 启动VisualC++6.0,New->MFC AppWizard(exe) 创建Dialog示例程序MFC01;
在ResourceView->String Table添加菜单项字符串,参考下面斜体项目;
ID Value Caption IDS_ABOUTBOX 101 MFC01 のバージョン情報(&A)… IDS_HELLOMENU 102 Hello IDS_HELLOMSG 103 Hello World!!! 在Resource.h文件中,定义菜单消息资源 IDM_HELLOBOX
//{{NO_DEPENDENCIES}} // Microsoft Developer Studio generated include file. // Used by MFC01.rc // #define IDM_ABOUTBOX 0x0010 #define IDM_HELLOBOX 0x0020 #define IDD_ABOUTBOX 100 #define IDS_ABOUTBOX 101 #define IDD_MFC01_DIALOG 102 #define IDS_HELLOMENU 102 #define IDS_HELLOMSG 103 #define IDR_MAINFRAME 128 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 129 #define _APS_NEXT_COMMAND_VALUE 32771 #define _APS_NEXT_CONTROL_VALUE 1000 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif
在Dialog的初始化函数中,给系统菜单添加新的菜单项;
///////////////////////////////////////////////////////////////////////////// // CMFC01Dlg message handlers BOOL CMFC01Dlg::OnInitDialog() { CDialog::OnInitDialog(); // Add "About..." menu item to system menu. // IDM_ABOUTBOX must be in the system command range. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); //验证菜单消息资源IDM_HELLOBOX有效 ASSERT((IDM_HELLOBOX & 0xFFF0) == IDM_HELLOBOX); ASSERT(IDM_HELLOBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { CString strAboutMenu; strAboutMenu.LoadString(IDS_ABOUTBOX); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } //添加菜单项Hello到系统菜单中 CString strHelloMenu; strHelloMenu.LoadString(IDS_HELLOMENU); if (!strHelloMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_HELLOBOX, strHelloMenu); } } // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here return TRUE; // return TRUE unless you set the focus to a control }
设置新添加菜单项Hello的消息响应
void CMFC01Dlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else if ((nID & 0xFFF0) == IDM_HELLOBOX)//Hello菜单消息响应 { AfxMessageBox(IDS_HELLOMSG); } else { CDialog::OnSysCommand(nID, lParam); } }