static void InsertBlock()
{
//获取要插入的块名
TCHAR str[40];
acedGetString(Adesk::kFalse, _T("
请输入要插入的块名称:"), str);
CString blockName ;
blockName.Format(_T("%s"), str);
//判断在当前图纸中是否已经被定义
AcDbDatabase *pCurDb = acdbHostApplicationServices()->workingDatabase();
AcDbBlockTable *pBlkTab;
AcDbObjectId blockId;
pCurDb->getBlockTable(pBlkTab, AcDb::kForRead);
//当前图纸中未定义该块
if (!pBlkTab->has(blockName))
{
pBlkTab->close();
//获取指定的外部图纸中的数据库
TCHAR *filePath = _T("D:\BlockTest.dwg");
CString strName;
strName.Format(_T("%s"), filePath);
AcDbDatabase *pDwg = getDatabaseByDwg(strName);
//获取外部数据库中该块中所有实体的id
AcDbObjectIdArray objIds;
getIdsByDwgBlkName(pDwg, blockName, objIds);//该函数属于自己编写,将在后面给出
//将外部数据库中对应ID的实体写入到pDb数据库中,该操作的作用是选择出我们所需要的所有实体
AcDbDatabase *pDb= NULL;
pDwg->wblock(pDb, objIds, AcGePoint3d(0, 0, 0));
//将pDb中的所有实体插入到当前图形中
Acad::ErrorStatus es = pCurDb->insert(blockId, blockName, pDb, Adesk::kFalse);
if (Acad::eOk != es)
{
acutPrintf(_T("
插入块错误!"));
return;
}
delete pDb;
}
//当前图纸中已经定义了该块
else
{
pBlkTab->getAt(blockName, blockId);
}
//获取块参照的插入点
ads_point pt;
acedGetPoint(NULL, _T("请选择插入点:"), pt);
AcGePoint3d ptInsert = asPnt3d(pt);
//创建块参照
AcDbBlockReference *pBlkRef = new AcDbBlockReference(ptInsert, blockId);
//获得模型空间块表记录,并插入块参照
AcDbBlockTable *pBlockTab;
acdbHostApplicationServices()->workingDatabase()
->getBlockTable(pBlockTab, AcDb::kForRead);
AcDbBlockTableRecord *pBlockTabRcd;
pBlockTab->getAt(ACDB_MODEL_SPACE, pBlockTabRcd, AcDb::kForWrite);
pBlockTab->close();
pBlockTabRcd->appendZcDbEntity(pBlkRef);
//获得属性
AcDbBlockTableRecord *pBlkDefRcd;
acdbOpenObject(pBlkDefRcd, blockId, AcDb::kForRead);
if (pBlkDefRcd->hasAttributeDefinitions())
{
//遍历块表记录
AcDbBlockTableRecordIterator *pItr;
pBlkDefRcd->newIterator(pItr);
for (pItr->start(); !pItr->done(); pItr->step())
{
//如果是属性,则加入到要插入的属性对象中
AcDbEntity *pEnt;
pItr->getEntity(pEnt, AcDb::kForRead);
AcDbAttributeDefinition *pAttDef = AcDbAttributeDefinition::cast(pEnt);
if (pAttDef != NULL)
{
AcDbAttribute *pAtt = new AcDbAttribute();
pAtt->setPropertiesFrom(pAttDef);
pAtt->setInvisible(pAttDef->isInvisible());
pAtt->setHorizontalMode(pAttDef->horizontalMode());
pAtt->setVerticalMode(pAttDef->verticalMode());
AcGePoint3d basePt = pAttDef->position();
basePt.x += ptInsert.x;
basePt.y += ptInsert.y;
basePt.z += ptInsert.z;
pAtt->setPosition(basePt);
pAtt->setHeight(pAttDef->height());
pAtt->setTextStyle(pAttDef->textStyle());
//设置属性的Tag、TextString
pAtt->setTag(pAttDef->tag());
pAtt->setTextString(pAttDef->textString());
pAtt->setFieldLength(pAttDef->fieldLength());
//将属性对象追加到块参照中
pBlkRef->appendAttribute(pAtt);
pAtt->close();
pEnt->close();
}
}
delete pItr;
}
pBlkDefRcd->close();
pBlockTabRcd->close();
pBlkRef->close();
}