MFC 菜单背景色设置(菜单重绘)
清泛原创
先上效果图:
源码下载(来自CSDN,感谢原作者):QTOOLS.rar
简单解析下:
最终是通过OnDrawItem()函数重新绘制菜单项,填充背景颜色。
MyMenu类中绘制代码:
MainFrm中调用MyMenu的方法:
源码下载(来自CSDN,感谢原作者):QTOOLS.rar
简单解析下:
最终是通过OnDrawItem()函数重新绘制菜单项,填充背景颜色。
MyMenu类中绘制代码:
//.h
virtual void DrawItem( LPDRAWITEMSTRUCT lpStruct ); //重绘菜单项
...
//.cpp
void CIconMenu::DrawItem( LPDRAWITEMSTRUCT lpStruct )
{
if (lpStruct->CtlType==ODT_MENU)
{
if(lpStruct->itemData == NULL) return;
unsigned int m_state = lpStruct->itemState;
CDC* m_dc = CDC::FromHandle(lpStruct->hDC);
//m_dc.Attach(lpStruct->hDC);
CString str = ((CMenuItemInfo*)(lpStruct->itemData))->m_ItemText;
LPSTR m_str = str.GetBuffer(str.GetLength());
int m_itemID = ((CMenuItemInfo*)(lpStruct->itemData))->m_ItemID;
int m_itemicon = ((CMenuItemInfo*)(lpStruct->itemData))->m_IconIndex;
CRect m_rect = lpStruct->rcItem;
m_dc->SetBkMode(TRANSPARENT);
switch(m_itemID)
{
case -2:
{
DrawTopMenu(m_dc,m_rect,m_str,(m_state&ODS_SELECTED)||(m_state&0x0040)); //0x0040 ==ODS_HOTLIGHT
// DrawItemText(m_dc,m_str,m_rect);
break;
}
case -1:
{
DrawItemText(m_dc,m_str,m_rect);
break;
}
case 0:
{
DrawSeparater(m_dc,m_rect);
break;
}
default:
{
DrawComMenu(m_dc,m_rect,RGB(200, 160, 80),RGB(100,140,80),m_state&ODS_SELECTED);
DrawItemText(m_dc,m_str,m_rect);
DrawMenuIcon(m_dc,m_rect,m_itemicon);
break;
}
}
}
}
MainFrm中调用MyMenu的方法:
//.h
CIconMenu mMenu;
...
//.cpp
BEGIN_MESSAGE_MAP(CMainFrm, CFrameWnd)
//{{AFX_MSG_MAP(CMainFrm)
ON_WM_CREATE()
ON_WM_DRAWITEM()
ON_WM_MEASUREITEM()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
...
int CMainFrm::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
UINT style=0;
if (CFrameWnd::OnCreate(lpCreateStruct) == -1)
return -1;
mMenu.AttatchMenu(LoadMenu(NULL,MAKEINTRESOURCE(IDR_MAINFRAME)));
mMenu.ChangeMenuItem(&mMenu,TRUE);
SetMenu(&mMenu);
...
}
void CMainFrm::OnDrawItem(int nIDCtl, LPDRAWITEMSTRUCT lpDrawItemStruct)
{
mMenu.DrawItem(lpDrawItemStruct);
}
void CMainFrm::OnMeasureItem(int nIDCtl, LPMEASUREITEMSTRUCT lpMeasureItemStruct)
{
mMenu.MeasureItem(lpMeasureItemStruct);
}
这样就OK了,更详细的请自行研究源码。
上一篇:CFormView 不显示、空白显示的问题
下一篇:菜单的背景颜色