欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

AutoCAD .Net 不同文档间复制对象

程序员文章站 2024-03-18 13:05:04
...

使用Clone()函数可以在同一 AutoCAD 文档间复制对象。
在不同的 AutoCAD 文档间复制对象,则需要调用Database类的方法WblockCloneObjects
以下代码演示,将一外部 AutoCAD 文档(D:\test.dwg)中的图元复制到当前文档。

[CommandMethod("TestCopyBetweenDwgFiles")]
public void TestCopyBetweenDwgFiles()
{
    Document doc = Application.DocumentManager.MdiActiveDocument;
    Database db = doc.Database;

    using (Transaction tr = db.TransactionManager.StartTransaction())
    {
        using (Database srcDb = new Database(false, false))
        {
            srcDb.ReadDwgFile(@"D:\test.dwg", FileOpenMode.OpenForReadAndReadShare, true, "");
            ObjectIdCollection oids = GetDbModelSpaceEntities(srcDb);

            if (oids.Count > 0)
            {
                IdMapping idMap = new IdMapping();
                srcDb.WblockCloneObjects(oids, db.CurrentSpaceId, idMap, DuplicateRecordCloning.Ignore, false);
            }
        }

        tr.Commit();
    }
}

/// <summary>
/// 获取数据库模型空间的所有图元
/// </summary>
private ObjectIdCollection GetDbModelSpaceEntities(Database db)
{
    ObjectIdCollection oids = new ObjectIdCollection();

    using (Transaction tr = db.TransactionManager.StartTransaction())
    {
        BlockTable blockTbl = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
        BlockTableRecord modelSpace = tr.GetObject(
            blockTbl[BlockTableRecord.ModelSpace],
            OpenMode.ForRead) as BlockTableRecord;

        foreach (ObjectId oid in modelSpace)
        {
            DBObject dbobj = tr.GetObject(oid, OpenMode.ForRead);
            if (dbobj is Entity)
            {
                oids.Add(oid);
            }
        }
    }

    return oids;
}
相关标签: AutoCAD