Articles and Tutorials

Handling ON_COMMAND and ON_UPDATE_COMMAND_UI messages

Author: Kirk Stowell
Platform: Visual C++ MFC

(Part I) using ON_UPDATE_COMMAND_UI:
Command Bars supports the classic MFC updating mechanism using the ON_UPDATE_COMMAND_UI macro. For example, to make a menu or toolbar command item checked you would add the following code:

BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
//{{AFX_MSG_MAP(CMainFrame)
...
//}}AFX_MSG_MAP
ON_UPDATE_COMMAND_UI(ID_EDIT_STATE,OnUpdateEditState)
END_MESSAGE_MAP()

[...]

void CMainFrame::OnUpdateEditState(CCmdUI* pCmdUI)
{
    pCmdUI->SetCheck(m_bCheck);
    pCmdUI->Enable(TRUE);
}

You can cause a control to be updated from CCmdUI.

void CMainFrame::OnUpdateEditState(CCmdUI* pCmdUI)
{
    CXTPCommandBar* pToolBar = (CXTPToolBar*)pCmdUI->m_pOther;
    if (pToolBar)
    {
        CXTPContro* pControl = pToolBar->GetControls()->GetAt(pCmdUI->m_nIndex);
        pControl->SetIconId(ID_FILE_NEW);
    }
}

You can also manually update the control using the xtpFlagManualUpdate flag.

pButton->SetFlags(xtpFlagManualUpdate);
pButton->SetChecked(TRUE);

(Part II) using ON_COMMAND:
Command Bars support the classic MFC executing mechanism using ON_COMMAND macro, for example to handle the ‘ID_THEME_DEFAULT’ command handler, you would add the following code:

BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
//{{AFX_MSG_MAP(CMainFrame)
...
//}}AFX_MSG_MAP
ON_COMMAND(ID_THEME_DEFAULT, OnSwitchDefault)
END_MESSAGE_MAP()

[...]

void CMainFrame::OnSwitchDefault()
{
    CXTPPaintManager::SetTheme(xtpThemeOffice2000);
    GetCommandBars()->RedrawCommandBars();
}

(Part III) using ON_XTP_EXECUTE:
Sometimes we need what control is to be executed and not just the command ID. In this case we use the ‘ON_XTP_EXECUTE’ macro, for example:

BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
//{{AFX_MSG_MAP(CMainFrame)
...
//}}AFX_MSG_MAP
ON_XTP_EXECUTE(ID_EDIT_STATE, OnEditState)
END_MESSAGE_MAP()

[...]

void CMainFrame::OnEditState(NMHDR* pNMHDR, LRESULT* pResult)
{
    CXTPControl* pControl = ((NMXTPCONTROL*)pNMHDR) ->pControl;
    if (pControl->GetType() == xtpControlSplitButtonPopup)
    {
        …
            …
            *pResult = TRUE;
    }              
}

Articles and Tutorials