QA: How to check a toolbar button from ON_UPDATE_COMMAND_UI handler?

Alexander Shargin (rudankort@softspb.com), July 14, 2003.

Question

I am using CCmdUI::SetCheck method in my ON_UPDATE_COMMAND_UI handler. It works fine for menus but fails for toolbar buttons. How can I fix this?

Answer

This happens because CToolCmdUI::SetCheck method was incorrectly ported to CE. To fix this, you should avoid SetCheck and use TB_CHECKBUTTON message instead. A pointer to the toolbar is passed to ON_UPDATE_COMMAND_UI handler in CCmdUI::m_pOther member. So, your handler might look like this:

void CMyWnd::OnUpdateXXX(CCmdUI* pCmdUI) { BOOL bCheck = /* determine if the button should be checked */ pCmdUI->m_pOther->SendMessage(TB_CHECKBUTTON, pCmdUI->m_nID, MAKELONG(bCheck , 0)); }

This method works fine for toolbars. But what if you need to update both menus and toolbars with the same ON_UPDATE_COMMAND_UI handler? In this case you need to distinguish between a menu and a toolbar in your handler and use different code for them. When a menu item is updated, CCmdUI::m_pOther is set to NULL, so it is not difficult to implement this idea:

void CMyWnd::OnUpdateXXX(CCmdUI* pCmdUI) { BOOL bCheck = /* determine if the button should be checked */ if(::IsWindow(pCmdUI->m_pOther->GetSafeHwnd())) pCmdUI->m_pOther->SendMessage(TB_CHECKBUTTON, pCmdUI->m_nID, MAKELONG(bCheck , 0)); else pCmdUI->SetCheck(bCheck); }

Related resources: