【MFC】多工具栏如何保存状态

MFC中的工具栏本来只有一个,如果想增加几个工具栏是比较简单,但现在一个重要的问题是,状态无法保存,导致每次打开,工具栏就会出现问题,要么偏移位置要么显示不出。

经过研究,发现是MFC框架中的一个bug,就是在保存工具栏时,将两个工具栏都保存到注册表的同一个路径中了。

MFC的具体源代码如下:

以下是加载工具栏了,

复制代码
//-----------------------------------------------------
    // Load all toolbars, menubar and docking control bars:
    //-----------------------------------------------------
    for (POSITION posTlb = afxAllToolBars.GetHeadPosition(); posTlb != NULL;)
    {
        CMFCToolBar* pToolBar = (CMFCToolBar*) afxAllToolBars.GetNext(posTlb);
        ENSURE(pToolBar != NULL);

        if (CWnd::FromHandlePermanent(pToolBar->m_hWnd) != NULL)
        {
            ASSERT_VALID(pToolBar);

            if (!m_bLoadSaveFrameBarsOnly || pToolBar->GetTopLevelFrame() == pFrameImpl->m_pFrame)
            {
                if (!pToolBar->IsFloating())
                {
                    pToolBar->LoadState(strSection);
                    if (pToolBar->IsResourceChanged())
                    {
                        bResetImages = TRUE;
                    }
                }
            }
        }
    }

以下是加载工具栏的具体实现

复制代码
BOOL CMFCToolBar::LoadState(LPCTSTR lpszProfileName, int nIndex, UINT uiID)
{
CString strProfileName = ::AFXGetRegPath(AFX_MFC_TOOLBAR_PROFILE, lpszProfileName);
BOOL bResult = FALSE;

if (nIndex == -1)
{
    nIndex = GetDlgCtrlID();
}

CString strSection;
if (uiID == (UINT) -1)
{
    strSection.Format(AFX_REG_SECTION_FMT, (LPCTSTR)strProfileName, nIndex);
}
else
{
    strSection.Format(AFX_REG_SECTION_FMT_EX, (LPCTSTR)strProfileName, nIndex, uiID);
}

LoadState的3个参数其中后两个都是用默认参数,导致最后调用的路径生成的为strSection.Format(AFX_REG_SECTION_FMT, (LPCTSTR)strProfileName, nIndex);

这个值是相同的。最后注册表中就是这样:

加载都是这样,可以想到保存也是类似的。

修改方法,就是在框架加载或保存后,对这两个工具条的状态再次进行加载和保存。

实现的具体代码在APP中,如下:

复制代码
void CMFCApplication8App::LoadCustomState()
{
	CString strSection = GetRegSectionPath();
	CMainFrame* pFrm = (CMainFrame*)AfxGetMainWnd();
	pFrm->m_wndToolBar.LoadState(strSection, -1,
		theApp.m_bHiColorIcons ? IDR_MAINFRAME_256 : IDR_MAINFRAME);
	pFrm->m_wndToolBar1.LoadState(strSection, -1, IDR_TOOLBAR1);
}

void CMFCApplication8App::SaveCustomState()
{
	CString strSection = GetRegSectionPath();

	((CMainFrame*)m_pMainWnd)->m_wndToolBar.SaveState(strSection, -1,
		theApp.m_bHiColorIcons ? IDR_MAINFRAME_256 : IDR_MAINFRAME);
	((CMainFrame*)m_pMainWnd)->m_wndToolBar1.SaveState(strSection, -1, IDR_TOOLBAR1);
}

具体代码见文章绑定的资源

但现在还存在一个问题,就是在视图中没有出现增加的工具栏

我以后研究出来再说。

但这个视图的自定义中有了:

相关推荐
DoWeixin61 天前
【请关注】VC内存泄露的排除及处理
c++·mfc·vc++·vc
lzb_kkk4 天前
【MFC】初识MFC
c++·mfc
技术程序猿华锋5 天前
Void:免费且隐私友好的 AI 编码利器,挑战 Cursor 地位?
c++·人工智能·mfc
等风来不如迎风去5 天前
【MFC】如何设置让exe的控制台不会跟着exe退出而退出
c++·mfc·控制台
秋天的落雨9 天前
MFC中嵌入外部独立EXE程序
c++·mfc
跑不了的你9 天前
MFC——编程框架和基础
c++·mfc
blog_wanghao9 天前
MFC:获取所有打印机的名称(打印机模块-2)
c++·mfc
blog_wanghao9 天前
MFC:获取所有打印机的名称(打印机模块-1)
c++·mfc
DoWeixin69 天前
【请关注】VC++ MFC常见异常问题及处理方法
c++·mfc·vc++·vc
blog_wanghao10 天前
MFC: 文件加解密(单元测试模块)
c++·单元测试·mfc