我想通过单击窗口内的按钮来更改呈现的视图像这样 https://i.stack.imgur.com/3IA2o.png。
我的项目设置:
- 我制作了一个没有文档/视图支持的 MFC 项目 (SDI)。
我在设计器中又创建了两个视图并向它们添加了类。新的视图类源自CFormView
。我将新视图类的构造函数和析构函数更改为公共。
将它们添加为 MainFrm.h 的指针:
CMainView* m_pMainView;
CSecondView* m_pSecondView;
- 我改变了
OnCreate()
,OnSetFocus()
and OnCmdMsg()
MainFrm.cpp的方法如下:
(这允许呈现我用设计器制作的 FormView)
int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CFrameWnd::OnCreate(lpCreateStruct) == -1)
return -1;
// First, build the view context structure
CCreateContext ccx;
// Designate the class from which to build the view
ccx.m_pNewViewClass = RUNTIME_CLASS(CMainView);
// Using the structure, create a view
m_pMainView = DYNAMIC_DOWNCAST(CMainView, this->CreateView(&ccx));
if (!m_pMainView)
{
TRACE0("creation of view failed");
}
// Do layout recalc
RecalcLayout();
// Show the view and do an initial update
m_pMainView->ShowWindow(SW_SHOW);
m_pMainView->OnInitialUpdate();
// Set this view active
SetActiveView(m_pMainView);
// Order it to resize the parent window to fit
m_pMainView->ResizeParentToFit(FALSE);
return 0;
}
...
void CMainFrame::OnSetFocus(CWnd* /*pOldWnd*/)
{
m_pMainView->SetFocus();
}
BOOL CMainFrame::OnCmdMsg(UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo)
{
if (m_pMainView->OnCmdMsg(nID, nCode, pExtra, pHandlerInfo))
return TRUE;
return CFrameWnd::OnCmdMsg(nID, nCode, pExtra, pHandlerInfo);
}
现在我的问题来了!我在第一个呈现的视图上有一个按钮,如果单击它,视图应该会改变。我在设计器中使用事件处理程序创建了以下函数:
void CMainView::OnBnClickedButton1()
{
// What to do here? I want to change the current view to another View by clicking the button
}
如果我在 MainFrm.cpp 类中处理它,例如使用菜单按钮,那就没有问题......工作正常:
void CMainFrame::OnViewNextview()
{
CCreateContext ccx2;
ccx2.m_pNewViewClass = RUNTIME_CLASS(CSecondView);
m_pSecondView = DYNAMIC_DOWNCAST(CSecondView, this->CreateView(&ccx2));
RecalcLayout();
m_pMainView->ShowWindow(SW_SHOW);
m_pMainView->OnInitialUpdate();
SetActiveView(m_pMainView);
m_pMainView->ResizeParentToFit(FALSE);
}
我尝试编写一个函数CMainFrame
并在中调用这个函数CMainView::OnBnClickedButton1()
但我不知道如何获取当前的 MainFrm 对象。 MainFrm 上的指针或其成员CMainView
不工作。
我搜索并红色教程好几天来解决我的问题。我还尝试使用文档/视图支持,如下所示:https://learn.microsoft.com/en-us/cpp/mfc/adding-multiple-views-to-a-single-document?view=vs-2019 https://learn.microsoft.com/en-us/cpp/mfc/adding-multiple-views-to-a-single-document?view=vs-2019但我不知道在哪里正确调用 switchView() 。
也许任何人都可以帮忙...