1. Create a new toolbar Idr_toolbar in the TOOLBAR resource. Add buttons. Then add a member variable to the mainframe CToolBar M_newtoolbar; In the OnCreate function of mainframe, add:
//创建工具栏,并加载工具栏资源
if (!m_newToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_RIGHT | CBRS_GRIPPER |
CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) || !m_newToolBar.LoadToolBar(IDR_TOOLBAR))
{
TRACE0("Failed to create toolbar\n");
return -1; // fail to create
}
m_newToolBar.EnableDocking(CBRS_ALIGN_ANY); //允许工具栏在工具栏区域中移动
EnableDocking(CBRS_ALIGN_ANY); //此框架任何地方允许可拖动,如果已经为别的ToolBar写过可以不用再写
DockControlBar(&m_newToolBar); //允许此工具栏在整个window窗口中拖动
2. Create a new menu (Id_toolbar, toolbar test) and add a command response function to the menu by ClassWizard:
Method One
void CMainFrame::OnToolbar()
{
if (m_newToolBar.IsWindowVisible()) //如果工具栏是显示着,那么就隐藏,否则就显示。
{
m_newToolBar.ShowWindow(SW_HIDE);
}
else
{
m_newToolBar.ShowWindow(SW_SHOW);
}
RecalcLayout(); //注意如果不写这行,会出现工具栏隐藏,但工具条仍然存在的现象,需要重新计算
DockControlBar(&m_newToolBar); //这行是为了在工具栏被拖役出边框时,工具栏窗口不能被隐藏。需要重靠。
}
Method Two, change the contents of the above function to:
Showcontrolbar (&m_newtoolbar,!m_newtoolbar.iswindowvisible (), FALSE),//One sentence can achieve the above function, and can save the window position before being hidden
3, let the menu item checked tag and toolbar associated. We create a new UPDATE_COMMAND_UI message corresponding function on the menu item:
void CMainFrame::OnUpdateToolbar(CCmdUI* pCmdUI)
{
pCmdUI->SetCheck(m_newToolBar.IsWindowVisible());
}
4. Edit the shortcut key in the accelerator resource: Select the menu ID to respond to the shortcut key, and then set the shortcut key.