利用MFC 在运行中动态创建新窗口

[入库:2005年8月18日] [更新:2007年3月24日]

本文简介:选择自 candycat 的 blog

利用mfc 在运行中动态创建新窗口  作者:郑咏  发布时间:2001/03/23
 
文章摘要:

  本文介绍了visual c++ 6.0 编程环境下使用mfc 类库编程时,在程序运行中动态创建新窗口的一种方法。本方法利用了mfc的框架类,因此新窗口有自己的菜单条,工具栏,和状态条。
  关键词 mfc, visual c++,窗口,框架

       

正文:  


利用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可以获得新建窗口中的视图对象指针,从而可以利用文档/框架/视图结构进行进一步的操作。


  程序的运行界面:

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

作者会员名:阿当

 

本文关键:MFC, Visual C++,窗口,框架
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top