MFC动态创建窗口

MFC动态创建窗口

在程序运行中,经常要利用对话框来给出某些提示,或者接收用户的反馈。然而在莫些场合下,仅仅利用对话框的方式是不够的。我们可能需要弹出一个新窗口,它包含自己的菜单条,对话框和状态条;当然,我们可以在对话框里加入菜单条,对话框和状态条,这在技术上是完全可行的,然而为何不直接创建新的窗口呢?本文给出了在MFC下的一种方法。
  我们知道,Windows编程下,创建新窗口包括两个步骤:
  (1)注册相应的Windows窗口类;
  (2)根据注册的窗口类,生成某个窗口。
  然而如果在MFC下,想要利用C++和MFC的特性,我们最好利用现成的MFC类,从其继承过来,并加以改造,以添加我们必须的元素。

  以下给出具体例子,主窗口显示一个矩形图形,在主窗口单击,将弹出包含编辑控件的新窗口。注意可以创建多个新窗口,当主窗口关闭时,所有新窗口也随之关闭。

步骤一,创建一个SDI工程Test。
 
  
编辑CtestView:OnDraw函数,在客户区画一个矩形:
void CTestView::OnDraw(CDC* pDC)
{
 CTestDoc* pDoc = GetDocument();
 ASSERT_VALID(pDoc);
 // TODO: add draw code for native data here

 // Draw a rectangle in Client
 pDC->Rectangle( 50, 50, 200, 200);
 pDC->TextOut( 10, 10, "在窗口单击鼠标左键,创建新窗口");

}

步骤二:利用ClassWizard从CframeWnd继承新窗口的类CnewFrame:

  在资源里资源:

简单起见,工具栏仍然采用主窗口的工具栏和状态条。

  在CNewFrame.H的类声明中插入工具栏和状态栏对象的声明:
protected: // control bar embedded members
 CStatusBar m_wndStatusBar;
 CToolBar m_wndToolBar;

  在CNewFrame响应WM_CREATE消息,在CNewFrame::OnCreate中装载工具栏和状态条:
int CNewFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
 if (CFrameWnd::OnCreate(lpCreateStruct) == -1)
  return -1;

 // TODO: Add your specialized creation code here

 if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP
  | CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) ||
  !m_wndToolBar.LoadToolBar(IDR_MAINFRAME))

// 简单起见,仍然装载主窗口的工具栏
  // 用户也可装载自己的工具栏
 {
  TRACE0("Failed to create toolbarn");
  return -1; // fail to create
 }

 if (!m_wndStatusBar.Create(this) ||
   !m_wndStatusBar.SetIndicators(indicators,
    sizeof(indicators)/sizeof(UINT)))
 {
  TRACE0("Failed to create status barn");
  return -1; // fail to create
 }

 // TODO: Delete these three lines if you don't want the toolbar to
 // be dockable
 m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY);
 EnableDocking(CBRS_ALIGN_ANY);
 DockControlBar(&m_wndToolBar);

 static int s_nNewFrameID = 0;
 s_nNewFrameID ++;
 CString str;
 str.Format( "第 %d 号新窗口 ", s_nNewFrameID );

SetWindowText( str );//设置新窗口的标题
 return 0;
}

  步骤三:窗口的销毁的处理。如果我们能确保只创建一个新窗口的话,那么这个步骤可以跳过,我们无须额外的代码;然而往往实用的情况是用户创建了多个窗口,各个窗口互相独立。那么,窗口销毁的问题则变得非常复杂。

我们知道MFC里窗口类的销毁包括两个方面的内容,首先是窗口的销毁,其次是窗口类的析构。因为CNewFrame从CFrameWnd继承,而后者在其虚拟函数PostNcDestroy里有delete this 的语句,如下所示:
void CFrameWnd::PostNcDestroy()
{
 // default for frame windows is to allocate them on the heap
 // the default post-cleanup is to 'delete this'.
 // never explicitly call 'delete' on a CFrameWnd, use DestroyWindow instead
 delete this;
}
  说明CframeWnd包括其子类都必须在堆上建立。如果我们严格的创建新窗口,关闭它,然后在创建,在关闭,那么一切都很正常;而如果我们创建了多个窗口,然后关闭主窗口,随着程序的结束退出,所有新窗口都会关闭,然而此时会发生内存泄露,因为我们退出时没有逐个销毁新建的窗口,因而PostNcDestroy中的delete this没有被执行。
  解决的办法是在主窗口程序中保存所有新建窗口的指针。我们用列表来保存所有指针。在CTestApp.h里添加:
#include "AfxTempl.h" // CList 的头文件说明
#include "NewFrame.h" // 新窗口的头文件
  在CtestApp类里添加成员:
public:
 CList < CNewFrame*, CNewFrame* > m_listFrame; // 保存所有新建窗口的指针
  当关闭新建的窗口时,应该从指针列表删去该窗口的指针:

void CNewFrame::PostNcDestroy()

{

 // TODO: Add your specialized code here and/or call the base class

 // because CFrameWnd::PostNcDestroy() will delete this but

 // won't set the pointer to this frame(pFrame) to NULL, thus

 // this will cause the CMsgsManagerApp::ExitInstance() to

 // delete the pointer again, and this will cause one exception

 // so we must travel the list frame to set the point to null

 // or delete it

 CTestApp* pApp = (CTestApp*)AfxGetApp();

 POSITION pos = pApp->m_listFrame.Find( this );

 if ( pos )

 pApp->m_listFrame.RemoveAt( pos );

 CFrameWnd::PostNcDestroy();

}

  如果没关闭新窗口而直接退出主程序时应该遍历列表,逐个销毁窗口:

int CTestApp::ExitInstance()

{

 // TODO: Add your specialized code here and/or call the base class

 CNewFrame* pFrame;

 // 如果退出程序时还有窗口未关闭,则遍历窗口链表

 // and close every frame of the listFrame

 TRACE("count = %dn", m_listFrame.GetCount());

 while ( !m_listFrame.IsEmpty() ){

  pFrame = m_listFrame.RemoveHead();

  if ( pFrame->GetSafeHwnd() ){

   TRACE("count = %dn", m_listFrame.GetCount());

   pFrame->DestroyWindow();

   // we need not delete pFrame

   // because pFrame inherit the CFrameWnd

   // and the virtual method PostNCDestroy of CFrameWnd

   // will delete this

  }

 }

 return CWinApp::ExitInstance();

}

  步骤四:创建新窗口。

  首先把CNewFrame的构造和析构函数的属性改为public:

public:///protected:

 CNewFrame(); // protected constructor used by dynamic creation

 virtual ~CNewFrame();

  把CtestDoc的构造函数改为public:

public:///protected: // create from serialization only

 CTestDoc();

  其次在单击鼠标左键响应函数中创建新窗口:

void CTestView::OnLButtonDown(UINT nFlags, CPoint point)

{

 // TODO: Add your message handler code here and/or call default

 CNewFrame* pFrame = new CNewFrame;

 CCreateContext Context;

 CTestDoc* pMsgsManagerDoc = new CTestDoc;

 Context.m_pCurrentDoc = pMsgsManagerDoc ;//GetDocument();

 Context.m_pNewViewClass = RUNTIME_CLASS(CEditView);

 pFrame->LoadFrame( IDR_NEWFRAME,                                    WS_OVERLAPPEDWINDOW | FWS_ADDTOTITLE,

  NULL, &Context );

 pFrame->ShowWindow(TRUE);

 // this is import!!!

 CTestApp* pApp = ( CTestApp* )AfxGetApp();

 pApp->m_listFrame.AddTail(pFrame);

 TRACE("count = %dn", pApp->m_listFrame.GetCount());

 POSITION pos = pMsgsManagerDoc->GetFirstViewPosition();

 CEditView* pView = (CEditView*) pMsgsManagerDoc->GetNextView(pos);

 ASSERT( pView) ;

 pView->GetEditCtrl().SetWindowText("新窗口示例。");

}

 注意:

  (1)新窗口创建成功后要添加到窗口指针列表中。

  (2)用GetFirstViewPosition和GetNextView可以获得新建窗口中的视图对象指针,从而可以利用文档/框架/视图结构进行进一步的操作。

  程序的运行界面

                     

  本文只是提供一个简单的例子,用户可以自己插入自己的工具栏和状态条,以及相应的消息函数。希望本文对于大家能有所帮

猜你喜欢

转载自blog.csdn.net/ycbx1569/article/details/88228962
今日推荐