【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);
}

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

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

我以后研究出来再说。

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

相关推荐
lingzhilab3 天前
零知派ESP32——BLE Mesh蓝牙组网智能灯控系统(PIR感应+W2812三档调色)
c++·mfc
lihao lihao3 天前
MFC知识点
c++·mfc
小小测试开发4 天前
NVIDIA SANA-WM:2.6B 开源世界模型,单卡 H100 生成 1 分钟 720p 视频
c++·音视频·mfc
lingzhilab5 天前
零知派ESP32——TCS3200高精度RGB颜色识别系统教程
c++·mfc
兵哥工控6 天前
MFC实现 Modbus-TCP 实时采集ZH-T08R 电阻模块阻值实例
c++·tcp/ip·mfc·modbus-tcp
techdashen7 天前
Rust 社区在 4 月做了什么:项目管理月报解读
开发语言·rust·mfc
lingzhilab10 天前
零知派ESP32-DFPlayer MP3智能音乐播放器2
c++·mfc
gqk0111 天前
C++ / MFC / Qt / C# 核心知识点汇总笔记
c++·qt·mfc
liuhuizuikeai11 天前
菜品抽奖活动MFC+服务端
c++·windows·mfc