jeudi 24 février 2022

MFC CMenu strange draw background behavior

I tried to draw the menu background in MFC Dlg App.

But I found if I declare CMenu subMenu in OnInitDialog(), the background color works well. If I declare CMenu subMenu in Head file or like CMenu* subMenu=new CMenu; in OnInitDialog(), the Item's background will not be changed.This is weird and seems to be related to the CMenu lifetime.

Variable:

CMenu  m_accountMenu;
CMenu subMenu;

CMFCApplication3Dlg::OnInitDialog()

......some code
// TODO: Add extra initialization here
m_accountMenu.CreateMenu();
subMenu.CreatePopupMenu();
m_accountMenu.AppendMenuW(MF_BYPOSITION | MF_POPUP | MF_STRING , (UINT)subMenu.m_hMenu, _T("Sub Info"));
subMenu.AppendMenuW(/*MF_MENUBREAK|*/  MF_STRING | MF_ENABLED , 1001, _T("sub Info1"));  //  note: MF_MENUBREAK can make it work  
subMenu.AppendMenuW(MF_STRING | MF_ENABLED , 1002, _T("sub Info2"));

CBrush cBrush;
cBrush.CreateSolidBrush(RGB(255, 0, 0));
MENUINFO mi = { 0 };
mi.cbSize = sizeof(MENUINFO);
mi.fMask = MIM_BACKGROUND;
mi.hbrBack = cBrush;

SetMenuInfo(m_accountMenu.GetSubMenu(0)->GetSafeHmenu(), &mi);
cBrush.Detach();
SetMenu(&m_accountMenu);

Can someone help me unravel the mystery? Any useful information will be appreciated.

Aucun commentaire:

Enregistrer un commentaire