StevoStephenson StevoStephenson - 1 month ago 7
C++ Question

How To Add A Second Toolbar Into Mainframe?

I would like to add a second toolbar in my main frame window to sit under the existing toolbar.

Reading the following tutorials:

http://forums.codeguru.com/showthread.php?495887-Add-a-toolbar-to-an-MFC-application

http://www.codersource.net/2010/01/30/mfc-tutorial-toolbars/

MFC Toolbar on Dialog?

I have come to a similar conclusion to this unanswered thread:

How to add a second toolbar to an MFC application so that the toolbar is added on a second/next line

This is my code:

int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CFrameWnd::OnCreate(lpCreateStruct) == -1)
return -1;
// create a view to occupy the client area of the frame
if (!m_wndView.Create(NULL, NULL, AFX_WS_DEFAULT_VIEW,
CRect(0, 0, 0, 0), this, AFX_IDW_PANE_FIRST, NULL))
{
TRACE0("Failed to create view window\n");
return -1;
}
if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP
| CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) ||
!m_wndToolBar.LoadToolBar(IDR_MAINFRAME))
{
TRACE0("Failed to create toolbar\n");
return -1; // fail to create
}
if (!m_wndStatusBar.Create(this) ||
!m_wndStatusBar.SetIndicators(indicators,
sizeof(indicators)/sizeof(UINT)))
{
TRACE0("Failed to create status bar\n");
return -1; // fail to create
}

m_wndStatusBar.SetPaneInfo(EWF_PANE_INDEX, ID_SEPARATOR, SBPS_NORMAL, EWF_PANE_WIDTH);

for (int i=0;i<5; i++) {
// Change Status Bar style to make it Owner-drawn
m_wndStatusBar.GetStatusBarCtrl().SetText("", i, SBT_OWNERDRAW);
}

CToolBar myToolBar;

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


return 0;
}


I have added:

CToolBar myToolBar;

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


At the bottom for my second toolbar but it does not appear when the app is opened and it compiles with no errors.

In comparison to the already supplied toolbar which is called from
InitInstance()
by
pFrame->LoadFrame(IDR_MAINFRAME, WS_OVERLAPPEDWINDOW | FWS_ADDTOTITLE , NULL, NULL);


If I call this
pFrame->LoadFrame
with my second toolbar in the next line the app will not load all together.

How do I need to call my second toolbar?

Have I missed something completely?

Answer

You need to add CToolBar myToolBar as a member variable of your CMainFrame class, the same way as m_wndToolBar. Otherwise, it gets destroyed if you define it as a local variable after the OnCreate exits.

Comments