[CommandMethod("InsertBlock")] //插入外面的块文件 public void InsertBlock() { Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; PromptPointResult ppr = ed.GetPoint("选择插入点"); Point3d pt = ppr.Value;//获取到插入点 //utility.WriteToEditor(pt.ToString()); string blockPath = @"C:\Users\Administrator\Desktop\变压器.dwg"; using (Database blkDb = new Database(false, true)) { //read drawing blkDb.ReadDwgFile(blockPath, System.IO.FileShare.Read, true, null); blkDb.CloseInput(true); using (DocumentLock docLock = doc.LockDocument())//多文档要先这样,否则报至命错误 { //新建图层id ObjectId layerId = ObjectId.Null; using (Transaction t = doc.TransactionManager.StartTransaction()) { string name = "变压器";//aa是不与blockPath文件中的任何块重名的字符串 //insert it as a new block ObjectId idBTR = doc.Database.Insert(name, blkDb, false); //create a ref to the block BlockTable bt = (BlockTable)t.GetObject(doc.Database.BlockTableId, OpenMode.ForRead); BlockTableRecord btr = (BlockTableRecord)t.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); //新建图层 LayerTable lt = (LayerTable)t.GetObject(doc.Database.LayerTableId, OpenMode.ForWrite); if (!lt.Has("图层4")) { LayerTableRecord ltr = new LayerTableRecord(); ltr.Name = "图层4"; layerId = lt.Add(ltr); t.AddNewlyCreatedDBObject(ltr, true); } //t.Commit(); btr.LayoutId = layerId; using (BlockReference bref = new BlockReference(pt, idBTR)) //pt是一个Point3D坐标,这里是插入进当前dwg文件中 { bref.LayerId = layerId; btr.AppendEntity(bref); t.AddNewlyCreatedDBObject(bref, true); } t.Commit(); } } } }