功能
通过CAD二次开发获取块名称、编号、位置、属性等息。
代码
public void GetCADLocationData()
{
// 获取当前文档和数据库
Document doc = Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = doc.Editor;
// 开始事务
using(Transaction tr = db.TransactionManager.StartTransaction())
{
// 打开模型空间块表记录
BlockTable blockTable = (BlockTable) tr.GetObject(db.BlockTableId, OpenMode.ForRead);
BlockTableRecord btr = (BlockTableRecord) tr.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForRead);
// 遍历模型空间中的所有对象
int n = 1;
foreach(ObjectId id in btr)
{
// 检查是否为块参照
Entity ent = tr.GetObject(id, OpenMode.ForRead) as Entity;
BlockReference blockRef = ent as BlockReference;
//ed.WriteMessage("1234");
//ed.WriteMessage(blockRef.Name);
if(ent != null && ent is BlockReference && blockRef.Name == "钻孔")
{
// 输出块名称、编号
ed.WriteMessage($ "\n块名称: {blockRef.Name + " - " + n}");
// 输出块坐标XY
ed.WriteMessage($ "\n块位置: {blockRef.Position.ToString()}");
// 遍历块中的每个属性
foreach(ObjectId attrId in blockRef.AttributeCollection)
{
DBObject obj = tr.GetObject(attrId, OpenMode.ForRead);
if(obj is AttributeReference)
{
AttributeReference attribute = obj as AttributeReference;
// 输出属性值--钻孔号、高程值
ed.WriteMessage($ "\n{attribute.Tag+": "+ attribute.TextString}");
}
}
n++;
}
}
// 提交事务
tr.Commit();
}
}