08-ObjectArx-获取某一层的所有实体

08-ObjectArx-获取某一层的所有实体

CwDatabase.h

static AcDbObjectIdArray GetAllEntIds(const ACHAR *layer=NULL,AcDbDatabase *pDb=acdbHostApplicationServices()->workingDatabase());

CwDatabase.cpp

AcDbObjectIdArray CwDatabase::GetAllEntIds(const ACHAR *layer/*=NULL*/,AcDbDatabase *pDb/*=acdbHostApplicationServices()->workingDatabase()*/)
{
	AcDbObjectIdArray entIds;
	AcDbObjectId layerId;
	bool bFilterLayer=false;
	if (layer!=NULL)
	{
		AcDbLayerTable *pLayerTbl;
		pDb->getLayerTable(pLayerTbl,AcDb::kForRead);
		if(!pLayerTbl->has(layer))
		{
			pLayerTbl->close();
			return entIds;
		}
		pLayerTbl->getAt(layer,layerId);
		pLayerTbl->close();
		bFilterLayer=true;
	}
	AcDbBlockTable *pBlkTbl=NULL;
	pDb->getBlockTable(pBlkTbl,AcDb::kForRead);
	AcDbBlockTableRecord *pBlkTblRcd=NULL;
	pBlkTbl->getAt(ACDB_MODEL_SPACE,pBlkTblRcd,AcDb::kForWrite);
	pBlkTbl->close();

	AcDbBlockTableRecordIterator *pItr=NULL;
	pBlkTblRcd->newIterator(pItr);
	for (pItr->start();!pItr->done();pItr->step())
	{
		if (bFilterLayer==true)
		{
			AcDbEntity *pEnt;

			pItr->getEntity(pEnt,AcDb::kForWrite);
			if (pEnt->layerId() == layerId)
			{
				entIds.append(pEnt->objectId());
			}
			pEnt->close();
		}
		AcDbObjectId objId;
		pItr->getEntityId(objId);
		entIds.append(objId);
	}
	delete pItr;
	pBlkTblRcd->close();
	return entIds;
}

2.实现,获取到测试层所有实体,并改为红色

Commands.h

void GetEnts();

Commands.cpp

void GetEnts()
{
	AcDbObjectIdArray entIds=CwDatabase::GetAllEntIds(_T("测试层"));
	for (int i=0;i<entIds.length();i++)
	{
		CwEditor::ChangeColor(entIds.at(i),1);
	}
}

注册命令

CwEditor::AddCommand(_T("GetEnts"),ACRX_CMD_MODAL,GetEnts);

3.打开AutoCAD,新建图层“测试层”,画任意实体,执行命令,可以看到所有实体变为红色