using System;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.EditorInput;
[assembly: CommandClass(typeof(Rivilis.MinsertToInsert))]
namespace Rivilis
{
public class MinsertToInsert
{
[CommandMethod("MI2I", CommandFlags.Modal)]
public void MI2I()
{
Document doc = Application.DocumentManager.MdiActiveDocument;
if (doc == null) return;
Editor ed = doc.Editor;
PromptEntityOptions prOpts =
new PromptEntityOptions("Выберите MInsert:");
prOpts.SetRejectMessage("Это не MInsert!");
prOpts.AddAllowedClass(typeof(MInsertBlock), false);
PromptEntityResult rs = ed.GetEntity(prOpts);
if (rs.Status == PromptStatus.OK)
{
using (MInsertBlock mRef =
rs.ObjectId.Open(OpenMode.ForWrite) as MInsertBlock)
{
ObjectId newBtrId = ObjectId.Null;
using (BlockTable bt =
doc.Database.BlockTableId.Open(OpenMode.ForWrite) as BlockTable)
{
using (BlockTableRecord newBtr = new BlockTableRecord())
{
Guid guid = Guid.NewGuid(); // Выбираем новое имя блока
newBtr.Name = guid.ToString();
newBtrId = bt.Add(newBtr);
using (BlockTableRecord btr =
mRef.BlockTableRecord.Open(OpenMode.ForWrite) as BlockTableRecord)
{
ObjectIdCollection ids = new ObjectIdCollection();
foreach (ObjectId id in btr) ids.Add(id);
newBtr.AssumeOwnershipOf(ids); // Перемещаем примитивы из одного блока в другой
}
}
using (BlockTableRecord btr =
mRef.OwnerId.Open(OpenMode.ForWrite) as BlockTableRecord)
{
using (BlockReference bref = new BlockReference(mRef.Position, newBtrId))
{
btr.AppendEntity(bref); // Добавляем вставку нового блока
}
}
// Проходимся по новому блоку, расчленяем прокси-примитивы и удаляем
// описания атрибутов
using (BlockTableRecord btr =
newBtrId.Open(OpenMode.ForWrite) as BlockTableRecord)
{
ObjectIdCollection ids = new ObjectIdCollection();
foreach (ObjectId id in btr) ids.Add(id);
foreach (ObjectId id in ids)
{
using (DBObject obj = id.Open(OpenMode.ForWrite))
{
if (obj.IsAProxy && obj is Entity)
{
DBObjectCollection objs = new DBObjectCollection();
Entity en = obj as Entity;
try
{
en.Explode(objs);
if (objs.Count > 0)
{
// Расчленяем прокси и избавляемся от него
// через HandOverTo, т.к. он неудаляемый
// (ProxyFlags == 0)
en.HandOverTo(objs[0], true, true);
objs[0].Close();
for (int i = 1; i < objs.Count; i++)
{
btr.AppendEntity(objs[i] as Entity);
objs[i].Close();
}
en.Dispose();
}
}
catch { }
} else if (obj.GetRXClass() == RXClass.GetClass(typeof(AttributeDefinition)))
{
obj.Erase();
}
}
}
}
}
mRef.Erase(); // Удаляем саму вставку блока
}
}
}
}
}