VC++深入详解-第六章学习心得

菜单的添加可以分为动态和静态

 

所谓静态也就是在ResourceView里自己去添加菜单

所谓动态也就是在代码中按需添加菜单

 

 

关于菜单的一些基本操作如下:

	CString str;
	str.Format("x=%d,y=%d",GetSystemMetrics(SM_CXMENUCHECK),GetSystemMetrics(SM_CYMENUCHECK));
	MessageBox(str);
	m_bitmap.LoadBitmap(IDB_BITMAP1);
	GetMenu()->GetSubMenu(0)->SetMenuItemBitmaps(0,MF_BYPOSITION,&m_bitmap,&m_bitmap);

	GetMenu()->GetSubMenu(0)->EnableMenuItem(1,MF_BYPOSITION|MF_DISABLED|MF_GRAYED);

	SetMenu(NULL);

	CMenu menu;
	menu.LoadMenu(IDR_MAINFRAME);
	SetMenu(&menu);
	menu.Detach();


对于菜单状态的改变一般利用MFC菜单命令更新机制

void CMainFrame::OnUpdateFileNew(CCmdUI* pCmdUI) 
{
	// TODO: Add your command update UI handler code here
	if (ID_FILE_NEW == pCmdUI->m_nID)
	{
		pCmdUI->Enable(FALSE);
	}

}

自定义的右键菜单

void CMenuView::OnRButtonDown(UINT nFlags, CPoint point) 
{
	// TODO: Add your message handler code here and/or call default
	CMenu menu;
	menu.LoadMenu(IDR_MENU1);
	CMenu* pPopup = menu.GetSubMenu(0);
	ClientToScreen(&point);
	pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON,point.x,point.y,this);
	CView::OnRButtonDown(nFlags, point);
}


 

 

动态菜单的相关代码

	CMenu menu;
	menu.CreateMenu();
//	GetMenu()->AppendMenu(MF_POPUP,(UINT)menu.m_hMenu,"TEST");
	GetMenu()->InsertMenu(2,MF_POPUP | MF_BYPOSITION,(UINT)menu.m_hMenu,"test");
	menu.AppendMenu(MF_STRING,IDM_HELLO,"HELLO");
	menu.AppendMenu(MF_STRING,112,"HELLO");
	menu.AppendMenu(MF_STRING,113,"HELLO");
	GetMenu()->GetSubMenu(0)->AppendMenu(MF_STRING,114,"bye");
	GetMenu()->GetSubMenu(0)->InsertMenu(ID_FILE_NEW,MF_STRING | MF_BYCOMMAND,115,"vc++");
	menu.Detach();
	GetMenu()->DeleteMenu(1,MF_BYPOSITION);
	GetMenu()->GetSubMenu(0)->DeleteMenu(2,MF_BYPOSITION);

 

最后贴上电话簿的代码,其中利用了框架类窗口截获菜单命令

void CMenu2View::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags) 
{
	// TODO: Add your message handler code here and/or call default
	CClientDC dc(this);
	if (0x0d == nChar)
	{
		if(0 == ++m_nIndex)
		{
			m_menu.CreatePopupMenu();
			GetParent()->GetMenu()->AppendMenu(MF_POPUP,(UINT)m_menu.m_hMenu,"PhoneBook");
			GetParent()->DrawMenuBar();
		}
		m_menu.AppendMenu(MF_STRING,IDM_PHONE1+m_nIndex,m_strLine.Left(m_strLine.Find(" ")));
		m_strArray.Add(m_strLine);
		m_strLine.Empty();
		Invalidate();
	}
	else
	{
		m_strLine += nChar;
		dc.TextOut(0,0,m_strLine);
	}
	CView::OnChar(nChar, nRepCnt, nFlags);
}


 

BOOL CMainFrame::OnCommand(WPARAM wParam, LPARAM lParam) 
{
	// TODO: Add your specialized code here and/or call the base class
	int MenuCmdID = LOWORD(wParam);
	CMenu2View *pView = (CMenu2View *)GetActiveView();
	if(MenuCmdID >= IDM_PHONE1 && MenuCmdID < IDM_PHONE1 + pView->m_strArray.GetSize())
	{
		//MessageBox("test");
		CClientDC dc(pView);
		dc.TextOut(0,0,pView->m_strArray.GetAt(MenuCmdID-IDM_PHONE1));
		return TRUE;
	}
	return CFrameWnd::OnCommand(wParam, lParam);
}


 

你可能感兴趣的:(VC++深入详解)