I am trying to create a toolbar on my dialog, so I am creating it in the OnInitDialog() function, but the toolbar is not coming. please help me finding whats going wrong in this. Thanks Sujan

BOOL CDlgsViewDlg::OnInitDialog()
{
	CDialog::OnInitDialog();
	CToolBar m_FirstToolBar;
	if(!m_FirstToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | 
	WS_VISIBLE | CBRS_TOP | CBRS_GRIPPER | CBRS_TOOLTIPS | 
	CBRS_FLYBY | CBRS_SIZE_DYNAMIC) || 
	!m_FirstToolBar.LoadToolBar(IDR_MAINFRAME))
{
   EndDialog(IDCANCEL);
}

RepositionBars(AFX_IDW_CONTROLBAR_FIRST, AFX_IDW_CONTROLBAR_LAST,0);
	return TRUE;  // return TRUE  unless you set the focus to a control
}

Dani AI

Generated

Short expert note: the toolbar vanished because the CToolBar instance was created as a local (automatic) variable inside OnInitDialog() and was destroyed when that function returned. As found, the fix is to keep the toolbar alive for the dialog’s lifetime (declare it as a member). : CToolBar is an MFC class (not part of standard C++), so it requires an MFC project and the MFC headers.

Why this happens: objects with automatic storage duration are destroyed at the end of the block where they were created; the window they created gets torn down with the object, so nothing stays visible after OnInitDialog returns. See the C++ storage-duration description for details.

Practical checklist and pattern to follow:

  • Add a CToolBar member to the dialog class (header).
  • In OnInitDialog, call CreateEx (parent = this) and then LoadToolBar using the correct resource ID.
  • On failure, stop initialization (call EndDialog or return) so you do not continue with a half-initialized UI.
  • If the toolbar still does not appear, verify the toolbar resource ID, styles (WS_CHILD | WSVISIBLE | CBRS*), parent argument, and call RepositionBars or ShowWindow(SW_SHOW). Use EnableDocking if you want docking behavior.

References:

Recommended Answers

All 2 Replies

I dont recognize the datatype "CToolBar"... is this libraries added to C++?

CToolBar is the class for the toolbar. Anyway my problem is sorted out, I need to declare it a member variable then it works. thanks for your efforts.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.