HansElsen
HansElsen

Reputation: 1753

Create toolbar with event in MFC

Hi I'm having a problem with my single-document MFC application.

I want to add my own toolbar to MainFrm class (CFrameWnd).

I am a total newb with MFC. So I'm not sure that's even the place to add it.


So far:

A toolbar resource with id IDR_TOOLBAR1 is created

A toolbarbutton with id ID_SELECT_SHAPE

In MainFrm.h is CToolBar m_wndMyToolBar; declared

In MainFrm.cpp:

if (!m_wndMyToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP | CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) ||
            !m_wndMyToolBar.LoadToolBar(IDR_TOOLBAR1))
{
    TRACE0("Failed to create toolbar\n");
    return -1;      // fail to create
}


The toolbar is showing now. YAY!
But I don't know how to add the event handler.

Somebody who can tell if I'm on the right track? And if so, who can tell how to add that event?

Upvotes: 0

Views: 2705

Answers (1)

Mark Taylor
Mark Taylor

Reputation: 1851

Yes, you are on the right track. Your MainFrame.cpp should have a section that starts with

BEGIN_MESSAGE_MAP 

and ends with

END_MESSAGE_MAP

Inside that section, you will need an entry

ON_COMMAND  (ID_SELECT_SHAPE, &CFrameWnd::OnSelectShape)

In your .h file add a declaration

afx_msg void OnSelectShape();

and in the .cpp file implement the OnSelectShape function to handle your event.

Depending on what your handler needs to do and what data it needs to have, it may be easier to add the handler and implement it in the CView... class instead of the CFrameWnd class. Handlers can also be implemented in the CDocument... class. When the toolbar button is clicked, the MFC Doc-View framework will first look for a handler in the View. If there is no handler available, it then looks for one in the Document, and finally if there is not a handler there it will look for one in the main Frame window.

Upvotes: 1

Related Questions