SWIFTuser Studios

A small game development studio that works on sciency application too

CMFCToolBar with Checked Button

January 14
by anegri 14. January 2014 00:13

Working on an internal tool and little things creep up.  Here is an easy way to add your own CMFCToolBar to an MFC SDI/MDI application.  Step by step:

 

  1. Insert Toolbar, in the Resource View of VS 2008.
  2. Draw you button.
  3. Give it a unique ID_TEST
  4. Add a string to the String Table:

    IDS_TOOLBAR_TEST => "This is a test" 
  5. To the header file of your choice (for this project it was my MainFrm.h) add a reference to the toold bar and a variable to hold its state:

        CMFCToolBar m_wndToolBarTest;
        BOOL m_blToolBarTestState[1]; 
  6. Add the message map functions:

        afx_msg void OnTest();
        afx_msg void OnUpdateTest(CCmdUI* pCmdUI); 
  7. On the message map of the source file (MainFrm.cpp) add the following messages:

        ON_COMMAND(ID_TEST, &CMainFrame::OnTest)
        ON_UPDATE_COMMAND_UI(ID_TEST, &CMainFrame::OnUpdateTest) 
  8. On the OnCreate method create your toolbar:
        if (!m_wndToolBarTest.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP | CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) ||
            !m_wndToolBarTest.LoadToolBar(theApp.m_bHiColorIcons ? IDR_ALIGN_256 : IDR_ALIGN))
        {
            TRACE0("Failed to create test toolbar\n");
            return -1;      // fail to create
        }

        BOOL bNameValid = strToolBarName.LoadString(IDS_TOOLBAR_TEST);
        ASSERT(bNameValid);   
        m_wndToolBarTest.SetWindowText(strToolBarName);
        ...
        m_wndToolBarTest.EnableDocking(CBRS_ALIGN_ANY);
        EnableDocking(CBRS_ALIGN_ANY);
        DockPane(&m_wndToolBarTest);
  9. Initialize array somwhere either on the constructor or in the create method:
    m_blToolBarTestState[0] = FALSE;
  10. Implement the button command:

    void CMainFrame::OnTest()
    {
        m_blToolBarTestState[0] = !m_blToolBarTestState[0];
  11. Implement the update command ui:

    void CMainFrame:: OnUpdateTest(CCmdUI* pCmdUI)
    {
        pCmdUI-> SetCheck(m_blToolBarTestState[0]);
    }

And we are done... hope it helps anyone that works on MFC and needs a step by step guide on this!