建立一個基於對話方塊的工程,工程名為CreateMenu
為該對話方塊增加一個檔案選單項和測試選單項,如下圖所示
測試選單項至少要有一個子選單項
在對話方塊屬性中關聯該選單
在resource.h中增加一個ID_TESTMENU巨集
#define ID_TESTMENU 5000
在對話方塊中新增一個Button按鈕,建立訊息對映,編輯程式碼如下
void CCreateMenuDlg::OnButton1()
{
// TODO: Add your control notification handler code here
char buf[2];
//獲取頂級選單
CMenu* pMenu=GetMenu();
//獲取1級選單
CMenu* pFileMenu=pMenu->GetSubMenu(0);
CMenu* pTestMenu=pMenu->GetSubMenu(1);
//新增2級選單
if(pTestMenu->GetSafeHmenu()==NULL)
return;
//新增一個2級彈出選單,將"檔案"選單項作為該選單的子選單
pTestMenu->AppendMenu(MF_POPUP,(UINT)pFileMenu->m_hMenu,"檔案");
//新增一個2級彈出選單,該選單的子選單為空
pTestMenu->AppendMenu(MF_POPUP,(UINT)pTestMenu->m_hMenu,"測試");
//新增10個2級普通選單
for(UINT m_ID=1;m_ID<=10;m_ID++)
{
itoa(m_ID,buf,10);
pTestMenu->AppendMenu(MF_SEPARATOR);
pTestMenu->AppendMenu(
MF_STRING,m_ID+ID_TESTMENU,"2級選單"+CString(buf));
}
//新增n級選單
CMenu* pnMenu=pTestMenu->GetSubMenu(2);
pnMenu->AppendMenu(MF_POPUP,(UINT)pnMenu->m_hMenu,"3級選單");
for(int i=0;i<5;i++)
{
pnMenu=pnMenu->GetSubMenu(0);
if(pnMenu==NULL) return;
itoa(i+4,buf,10);
pnMenu->AppendMenu(
MF_POPUP,(UINT)pnMenu->m_hMenu,buf + CString("級選單"));
}
pnMenu->GetSubMenu(0)->AppendMenu(
MF_STRING,ID_TESTMENU,"9級選單");
}
響應單擊選單的事件
新增OnCommand的訊息對映,編輯程式碼如下
BOOL CCreateMenuDlg::OnCommand(WPARAM wParam, LPARAM lParam)
{
// TODO: Add your specialized code here and/or call the base class
UINT uMsg=LOWORD(wParam);
char buf[2];
if(uMsg==ID_TESTMENU)
{
MessageBox("HELLO!");
}
for(UINT i=1;i<=10;i++)
{
if(uMsg==ID_TESTMENU+i)
{
itoa(i,buf,10);
MessageBox("HELLO! " + CString(buf));
}
}
return CDialog::OnCommand(wParam, lParam);
}
執行結果: