using System;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.EditorInput;
// This line is not mandatory, but improves loading performances
[assembly: CommandClass(typeof(InsertExplodeErase.MyCommands))]
namespace InsertExplodeErase
{
public class MyCommands
{
[CommandMethod("AddBlockTest")]
public void AddBlockTest()
{
Document doc = Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
string blockName = "55";
using (Database sourceDb = new Database(false, true))
{
sourceDb.ReadDwgFile("C:\\AutoCAD_prilozhenie\\prokat\\Sveler.dwg",
System.IO.FileShare.ReadWrite, true, "");
ObjectIdCollection ids = new ObjectIdCollection();
using (Transaction tr = sourceDb.TransactionManager.StartTransaction())
{
BlockTable bt =
(BlockTable)tr.GetObject(sourceDb.BlockTableId, OpenMode.ForRead);
if (bt.Has(blockName))
{
ids.Add(bt[blockName]);
}
tr.Commit();
}
if (ids.Count != 0)
{
Database destdb = doc.Database;
IdMapping iMap = new IdMapping();
destdb.WblockCloneObjects(ids, destdb.BlockTableId, iMap,
DuplicateRecordCloning.Ignore, false);
}
else return;
}
ObjectId blockId;
using (Transaction tr = db.TransactionManager.StartTransaction())
{
BlockTable bt =
tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
BlockTableRecord blockDef =
tr.GetObject(bt[blockName], OpenMode.ForRead) as BlockTableRecord;
blockId = blockDef.ObjectId;
// Открываем пространство модели – мы добавляем наш BlockReference к нему
BlockTableRecord ms =
tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
// Создаём BlockReference и связываем его с определением блока
Point3d point = new Point3d(2.0, 4.0, 6.0);
BlockReference blockRef =
new BlockReference(point, blockDef.ObjectId);
// Добавляем вставку блока к пространству модели
ms.AppendEntity(blockRef);
tr.AddNewlyCreatedDBObject(blockRef, true);
blockRef.ExplodeToOwnerSpace();
blockRef.Erase();
tr.Commit();
}
// Удаляем описание этого блока
if (!blockId.IsNull)
{
using (Transaction tr = db.TransactionManager.StartTransaction())
{
BlockTableRecord blockDef =
tr.GetObject(blockId, OpenMode.ForWrite) as BlockTableRecord;
// Только если нет вставок этого блока
ObjectIdCollection ids =
new ObjectIdCollection() { blockId };
db.Purge(ids);
if (ids.Count == 1)
{
blockDef.Erase();
}
tr.Commit();
}
}
}
}
}