ToughDev
ToughDev

Reputation: 117

How to embed CCmdTarget-derived class into MFC message chain?

I want to extract some settings-specific code from View class and put it in to CSettings class.

I don’t want to bloat my CView class when amount of settings will be more than 80.

All the messages from Menu (and ribbon) about settings should be processed in CSettings class.

The only thing I can't understand is how to embed message map entries in to CMyView message map.

//The main purpose of class CSettings is to remove all the logic of settings from View.
class CSettings : public CCmdTarget
{
   DECLARE_MESSAGE_MAP()
   DECLARE_DYNAMIC(CSettings)
   void OnCheckS1() {
       m_bVal1 = !m_bVal1;
   }

   void OnUpdateCheck1(CCmdUI* pCmdUI){
       pCmdUI->SetRadio(m_bVal1);
   }

   bool m_bVal1;
   <other 80 settings>
}

BEGIN_MESSAGE_MAP(CSettings, CCmdTarget)
    ON_COMMAND(ID_CHECK_S1, &CSettings::OnCheckS1)
    ON_UPDATE_COMMAND_UI(ID_CHECK_S1, &CSettings::OnUpdateCheck1)
END_MESSAGE_MAP()


class CMyView : public CView
{
      ...
    CSettings m_sett;
}

BEGIN_MESSAGE_MAP(CMyViewView, CView)
--->>> ??? <<<----
END_MESSAGE_MAP()

Upvotes: 4

Views: 1761

Answers (1)

ChrisN
ChrisN

Reputation: 16943

You don't have to add anything to your view class's message map. Instead you should override the OnCmdMsg function to route the command and update messages to your CSettings class, like this:

class CMyView : public CView {
    // ...
    virtual BOOL OnCmdMsg(UINT nID, int nCode, void* pExtra,
        AFX_CMDHANDLERINFO* pHandlerInfo);
};

BOOL CMyView::OnCmdMsg(UINT nID, int nCode, void* pExtra,
    AFX_CMDHANDLERINFO* pHandlerInfo)
{
    if (m_sett.OnCmdMsg(nID, nCode, pExtra, pHandlerInfo))
        return TRUE;

    return CView::OnCmdMsg(nID, nCode, pExtra, pHandlerInfo);    
}

Have a look at this page in MSDN for more information.

Also, if you've got 80+ settings, you might want to consider using ON_COMAND_RANGE and ON_UPDATE_COMMAND_UI_RANGE to avoid having to write handler functions for each individual setting.

Upvotes: 2

Related Questions