arx对正在操作的文件进行保存

时间:2022-10-24 05:37:34
//对正在操作的文件进行保存
STDMETHODIMP CTHDatabase::Save(void)
{
 // TODO: 在此添加实现代码
 Acad::ErrorStatus es ;
 try{
  AcDbDatabase* pCurDb = acdbHostApplicationServices()->workingDatabase();
  if(pCurDb == NULL)
  {
   return Error(L"Fialed to get current docment " ,IID_ITHDatabase,E_FAIL);
  }
  AcAxDocLock docLock( pCurDb, AcAxDocLock::kCurDocSwitch );
  if(docLock.lockStatus() != Acad::eOk)
   throw docLock.lockStatus();

  //得到被操作dwg文件的数据库
  AcDbDatabase* pWorkDb = NULL;
  CAcApDocLockServer tempDocLockServer;

  if(m_strFileName.IsEmpty())
   pWorkDb = pCurDb;
  else
  {
   pWorkDb = tempDocLockServer.GetDataBase(m_strFileName);
   if(NULL == pWorkDb)
   {
    CString strErr = L"Fialed To open the " ;
    return Error(strErr + m_strFileName,IID_ITHDatabase,E_FAIL);
   }
  }
  //如果当前操作的文件不是ACAD当前活动文档,则进行存盘
  if(!m_strFileName.IsEmpty()){
            //遍历ACAD所打开的所有文档,如果当前操作的文件已经被ACAD打开,
   //那么把此文档切换为活动文档,存盘后在切换到原来的活动文档
   AcApDocument* pCurDoc = curDoc();
   AcApDocumentIterator* iter = acDocManager->newAcApDocumentIterator();
   if (iter) {
    AcApDocument* tmpDoc;
    for (; !iter->done(); iter->step()) {
     tmpDoc = iter->document();
     if (tmpDoc)
     {
      CString strFile(tmpDoc->fileName());
      if(m_strFileName.CompareNoCase(strFile) == 0)
      {
       es = acDocManager->setCurDocument(tmpDoc, AcAp::kWrite);//切换为活动文档
       if(Acad::eOk != es)
       {
        delete iter;
        throw MESSAGE(es);
       }
       es = tmpDoc->database()->saveAs(m_strFileName);
       if(Acad::eOk != es)
       {
        delete iter;
        throw MESSAGE(es);
       }
       es = acDocManager->unlockDocument(tmpDoc);
       if(Acad::eOk != es)
       {
        delete iter;
        throw MESSAGE(es);
       }
       es = acDocManager->setCurDocument(pCurDoc);//切换到原来的活动文档
       if(Acad::eOk != es)
       {
        delete iter;
        throw MESSAGE(es);
       }
       delete iter;
       iter = NULL;
       return S_OK;
      }
     }
    }
    if(iter != NULL)
    {
     delete iter;
     iter = NULL;
    }
   }
            //如果当前操作的文件没有被ACAD打开,直接保存
   es = pWorkDb->saveAs(m_strFileName);
   if(Acad::eOk != es)
    throw MESSAGE(es);
  }
 }
 catch(const Acad::ErrorStatus)
 {
   CString strErr = L"Fialed To open the " ;
   return Error(strErr + m_strFileName,IID_ITHDatabase,E_FAIL);
 }

 return S_OK;
}