public static void InsertFromDwgFile(string fileName)
{
try
{
SetFocus(Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Window.Handle);
Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
Editor ed = doc.Editor;
Point3d ptNew = Point3d.Origin;
using (doc.LockDocument())
{
Database currentDb = doc.Database;
ObjectIdCollection ids = new ObjectIdCollection();
IdMapping idMap = new IdMapping();
using (Transaction tr = doc.TransactionManager.StartTransaction())
{
BlockTable currBt = (BlockTable)tr.GetObject(currentDb.BlockTableId, OpenMode.ForRead);
BlockTableRecord currBtr =
(BlockTableRecord)tr.GetObject(currBt[BlockTableRecord.ModelSpace], OpenMode.ForRead);
using (Database sourceDb = new Database(false, false))
{
sourceDb.ReadDwgFile(fileName, System.IO.FileShare.ReadWrite, false, "");
using (Transaction sourcetr = sourceDb.TransactionManager.StartTransaction())
{
ObjectIdCollection sourceIds = new ObjectIdCollection();
using (
BlockTableRecord sourceBtr =
(BlockTableRecord)sourcetr.GetObject(sourceDb.CurrentSpaceId, OpenMode.ForRead)
)
{
if (sourceBtr != null)
{
sourceIds = new ObjectIdCollection();
foreach (ObjectId id in sourceBtr)
{
if (!id.IsNull && id.IsValid) //optional
sourceIds.Add(id);
}
sourcetr.Commit();
}
if (sourceIds.Count != 0)
idMap = new IdMapping();
sourceDb.WblockCloneObjects(sourceIds, currBtr.ObjectId, idMap,
DuplicateRecordCloning.Ignore, false);
}
}
}
foreach (IdPair ip in idMap)
{
if (ip.IsPrimary) ids.Add(ip.Value);
}
var copied = new ObjectId[ids.Count];
ids.CopyTo(copied, 0);
ed.SetImpliedSelection(copied);
PromptSelectionResult psr = ed.SelectImplied();
if (psr.Status == PromptStatus.OK)
{
var ppr =
ed.Drag(
psr.Value,
"\nУкажите точку вставки: ",
delegate(Point3d pt, ref Matrix3d mtx)
{
if (ptNew == pt)
{
return SamplerStatus.NoChange;
}
mtx =
Matrix3d.Displacement(
ptNew.GetVectorTo(pt)
);
return SamplerStatus.OK;
}
);
if (ppr.Status == PromptStatus.OK)
{
var mtx =
Matrix3d.Displacement(
ptNew.GetVectorTo(ppr.Value)
);
foreach (SelectedObject sobj in psr.Value)
{
var en = tr.GetObject(sobj.ObjectId, OpenMode.ForRead, false) as Entity;
if (en != null)
{
en.UpgradeOpen();
en.TransformBy(mtx);
en.DowngradeOpen();
}
}
}
else
{
foreach (SelectedObject sobj in psr.Value)
{
var en = tr.GetObject(sobj.ObjectId, OpenMode.ForWrite, false) as Entity;
if (en != null)
{
en.Erase(true);
}
}
}
ed.SetImpliedSelection(new ObjectId[] { });
tr.Commit();
}
}
}
}
catch (Autodesk.AutoCAD.Runtime.Exception ex)
{
Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(ex.Message + "\n" + ex.StackTrace + "\n" + ex.TargetSite);
}
}