通过CreateControl()直接创建控件(ocx)失败时的处理

来源:互联网 发布:js判断css样式 编辑:程序博客网 时间:2024/05/12 19:02

刚开始的时候,在一个对话框工程exe中,通过CreateControl()可以成功地直接创建一个控件(ocx),后来由于变化,需要在一个控件中再手动创建其它的控件,结果却失败了,创建的代码和在exe中完全一样,可为什么不成功呢?

出问题的那一句是:

m_pCtrlCont = afxOccManager->CreateContainer(this);

是windows自己的文件中,函数如下:

BOOL CWnd::InitControlContainer(BOOL bCreateFromResource)
{
   if (m_pCtrlCont == NULL)
   {
   BOOL bSuccess;

   bSuccess = CreateControlContainer( &m_pCtrlCont );
   if (bSuccess && (m_pCtrlCont == NULL))
   {
   // The window wants to use the default control container.
    TRY
    {
   m_pCtrlCont = afxOccManager->CreateContainer(this);
    }
    END_TRY
   }
   //When Container is created and it is not during creation from resources,
   //populate the list with all resource created Win32 controls.
   if (!bCreateFromResource)
   {
   m_pCtrlCont->FillListSitesOrWnds(GetOccDialogInfo());  
   }
   }

 // Mark all ancestor windows as containing OLE controls.
 if (m_pCtrlCont != NULL)
 {
  CWnd* pWnd = this;
  while ((pWnd != NULL) && !(pWnd->m_nFlags & WF_OLECTLCONTAINER))
  {
   pWnd->m_nFlags |= WF_OLECTLCONTAINER;
   pWnd = pWnd->GetParent();
   if (! (GetWindowLong(pWnd->GetSafeHwnd(), GWL_STYLE) & WS_CHILD))
    break;
  }
 }
 
 return (m_pCtrlCont != NULL);
}

 然后查看afxOccManager,发现有

#define afxOccManager   AfxGetModuleState()->m_pOccManager

这时,m_pOccManager为NULL,所以创建不成功

这个变量名称让我想起可能是和ole有关的环境没有初始化造成的,查看exe工程的CexeApp::InitInstance()中,有 AfxEnableControlContainer();,而控件工程中却没有,于是把它拷贝到控件工程的CocxApp::InitInstance()中,编译运行,控件创建成功

拷贝之后的函数如下:

BOOL CocxApp::InitInstance()
{
 BOOL bInit = COleControlModule::InitInstance();

 if (bInit)
 {
  // TODO: Add your own module initialization code here.
  AfxEnableControlContainer();
 }

 return bInit;
}

原创粉丝点击