【发布时间】:2019-12-23 23:12:25
【问题描述】:
我想通过单击窗口内的按钮来更改显示的视图 like this。 我的项目设置:
- 我创建了一个不支持 Doc/View 的 MFC 项目 (SDI)。
我在设计器中又制作了两个视图并向它们添加了类。新的视图类派生自
CFormView。我将新视图类的构造函数和析构函数更改为公开的。将它们作为指向 MainFrm.h 的指针添加:
CMainView* m_pMainView;
CSecondView* m_pSecondView;
- 我更改了 MainFrm.cpp 的
OnCreate(),OnSetFocus()和OnCmdMsg()方法,如下所示: (这样可以展示我用 Designer 制作的 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);
}
现在我的问题来了!我在第一个呈现的视图上有一个按钮,如果你点击它,视图应该会改变。我在 Designer 中使用事件处理程序创建了以下函数:
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 对象。 CMainView 中 MainFrm 或其成员的指针不起作用。
我搜索了几天的红色教程来解决我的问题。我还尝试使用 Doc/View 支持,如下所示: https://docs.microsoft.com/en-us/cpp/mfc/adding-multiple-views-to-a-single-document?view=vs-2019 但我不知道在哪里正确调用 switchView()。
也许任何人都可以提供帮助......
【问题讨论】:
标签: c++ visual-c++ view mfc sdi