public bool ToNiMingBlock(ObjectIdCollection IDs) { bool result; try { Document mdiActiveDocument = Application.DocumentManager.MdiActiveDocument; Database database = mdiActiveDocument.Database; using (Transaction transaction = database.TransactionManager.StartTransaction()) { BlockTable blockTable = (BlockTable)transaction.GetObject(database.BlockTableId, 1); BlockTableRecord blockTableRecord = new BlockTableRecord(); blockTableRecord.Name = "*Q"; Entity entity = (Entity)transaction.GetObject(IDs[0], 0); Point3d minPoint = entity.GeometricExtents.MinPoint; blockTableRecord.Origin = minPoint; try { foreach (object obj in IDs) { ObjectId objectId2; ObjectId objectId = (obj != null) ? ((ObjectId)obj) : objectId2; Entity entity2 = (Entity)transaction.GetObject(objectId, 1); Entity entity3 = (Entity)entity2.Clone(); entity2.Erase(); blockTableRecord.AppendEntity(entity3); } } finally { IEnumerator enumerator; if (enumerator is IDisposable) { (enumerator as IDisposable).Dispose(); } } blockTable.Add(blockTableRecord); transaction.AddNewlyCreatedDBObject(blockTableRecord, true); BlockTableRecord blockTableRecord2 = (BlockTableRecord)transaction.GetObject(blockTable[BlockTableRecord.ModelSpace], 1); BlockReference blockReference = new BlockReference(minPoint, blockTableRecord.ObjectId); blockReference.Layer = entity.Layer; blockTableRecord2.AppendEntity(blockReference); transaction.AddNewlyCreatedDBObject(blockReference, true); transaction.Commit(); } result = true; } catch (Exception ex) { result = false; } return(result); }
//This function returns the ObjectId for the BlockTableRecord called "EmployeeBlock", //creating it if necessary. The block contains three entities - circle, text //and ellipse. private static ObjectId CreateEmployeeDefinition() { ObjectId newBtrId = ObjectId.Null; //The return value for this function Database db = HostApplicationServices.WorkingDatabase; //save some space using (Transaction trans = db.TransactionManager.StartTransaction()) // begin the transaction { //Now, drill into the database and obtain a reference to the BlockTable BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForWrite); if (bt.Has("EmployeeBlock")) { newBtrId = bt["EmployeeBlock"]; //Already there...no need to recreate it! } else { Point3d center = new Point3d(0, 0, 0); //convenient declaration... //Declare and define the entities we want to add: //Circle: Circle circle = new Circle(center, Vector3d.ZAxis, 2.0); //Attribute AttributeDefinition attDef = new AttributeDefinition(center, "NoName", "Name:", "Enter Name", db.Textstyle); //Ellipse: Ellipse ellipse = new Ellipse(center, Vector3d.ZAxis, new Vector3d(3, 0, 0), 0.5, 0.0, 0.0); //Next, create a layer with the helper function, and assign //the layer to our entities. ObjectId empId = CreateLayer(); circle.LayerId = empId; ellipse.LayerId = empId; //Set the color for each entity irrespective of the layer//s color. attDef.ColorIndex = 2; circle.ColorIndex = 1; ellipse.ColorIndex = 3; //Create a new block definition called EmployeeBlock BlockTableRecord newBtr = new BlockTableRecord(); newBtr.Name = "EmployeeBlock"; newBtrId = bt.Add(newBtr); //Add the block, and set the id as the return value of our function trans.AddNewlyCreatedDBObject(newBtr, true); //Let the transaction know about any object/entity you add to the database! newBtr.AppendEntity(circle); //Append our entities... newBtr.AppendEntity(attDef); newBtr.AppendEntity(ellipse); trans.AddNewlyCreatedDBObject(circle, true); //Again, let the transaction know about our newly added entities. trans.AddNewlyCreatedDBObject(attDef, true); trans.AddNewlyCreatedDBObject(ellipse, true); } trans.Commit(); //All done, no errors? Go ahead and commit! } return (newBtrId); } // end of CreateEmployeeDefinition
/// <summary> /// Создание определения блока панели по описанию из базы XML от конструкторов. /// Должна быть открыта транзакция. /// </summary> /// <exception cref="Autodesk.AutoCAD.Runtime.Exception">DuplicateBlockName</exception> /// <returns>ObjectId созданного определения блока в текущей базе.</returns> public void CreateBlock() { // Имя для блока панели АКР BlNameAkr = defineBlockPanelAkrName(); Openings = new List <Extents3d>(); Database db = Service.Db; //Transaction t = db.TransactionManager.TopTransaction; using (var t = db.TransactionManager.StartTransaction()) { BlockTable bt = db.BlockTableId.GetObject(OpenMode.ForRead) as BlockTable; // Ошибка если блок с таким именем уже есть if (bt.Has(BlNameAkr)) { IdBtrPanel = bt[BlNameAkr]; Inspector.AddError($"Блок панели с именем {BlNameAkr} уже определен в чертеже.", icon: System.Drawing.SystemIcons.Error); return; } BlockTableRecord btrPanel = new BlockTableRecord(); btrPanel.Name = BlNameAkr; bt.UpgradeOpen(); IdBtrPanel = bt.Add(btrPanel); bt.DowngradeOpen(); t.AddNewlyCreatedDBObject(btrPanel, true); //корректировка точки отсчета панели correctStartPointCoordinatesPanel(); // Добавление полилинии контура createContour(btrPanel, t); // Добавление окон addWindows(btrPanel, t); // заполнение плиткой addTiles(btrPanel, t); // Добавление торцов (Cheek) addCheek(btrPanel, t); // Образмеривание (на Фасаде) DimensionFacade dimFacade = new DimensionFacade(btrPanel, t, this); dimFacade.Create(); // Образмеривание (в Форме) DimensionForm dimForm = new DimensionForm(btrPanel, t, this); dimForm.Create(); t.Commit(); } }
/// <summary> /// 将块表记录加入到块表中 /// </summary> /// <returns>块表记录ObjectId</returns> public ObjectId AddBlockTableRecord(BlockTableRecord btr, Database db) { ObjectId id = new ObjectId(); using (Transaction transaction = db.TransactionManager.StartTransaction()) { BlockTable bt = transaction.GetObject(db.BlockTableId, OpenMode.ForWrite) as BlockTable; id = bt.Add(btr); transaction.AddNewlyCreatedDBObject(btr, true); transaction.Commit(); } return(id); }
public static ObjectId criarDefiniçãoDeBloco(ObjectId[] objIds) { string nomeBloco = "Teste1"; Database db = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Database; using (Transaction trans = db.TransactionManager.StartTransaction()) { try { Autodesk.AutoCAD.ApplicationServices.Document Doc = null; Doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; using (DocumentLock dl = Doc.LockDocument()) { //abrir tabela de blocos BlockTable bt = trans.GetObject(db.BlockTableId, OpenMode.ForWrite) as BlockTable; //verificar se o bloco já existe if (bt.Has(nomeBloco)) { return(bt[nomeBloco]); } BlockTableRecord novoBloco = new BlockTableRecord(); novoBloco.Name = nomeBloco; bt.UpgradeOpen(); bt.Add(novoBloco); trans.AddNewlyCreatedDBObject(novoBloco, true); foreach (ObjectId objId in objIds) { DBObject obj = trans.GetObject(objId, OpenMode.ForRead); Entity ent = (Entity)obj; Entity entClone = ent.Clone() as Entity; novoBloco.AppendEntity(entClone); trans.AddNewlyCreatedDBObject(entClone, true); } trans.Commit(); return(novoBloco.ObjectId); } } catch (System.Exception ex) { trans.Abort(); return(ObjectId.Null); } } }
/// <summary> /// 将块表记录加入到块表中 /// </summary> /// <returns></returns> public static ObjectId AddToBlockTable(BlockTableRecord Record) { Database db = HostApplicationServices.WorkingDatabase; ObjectId id = new ObjectId(); using (Transaction transaction = db.TransactionManager.StartTransaction()) { BlockTable table = transaction.GetObject(db.BlockTableId, OpenMode.ForWrite) as BlockTable; id = table.Add(Record); transaction.AddNewlyCreatedDBObject(Record, true); transaction.Commit(); } return(id); }
addBlockRefPolyLdr(List <Vertex2d> vtxs2d, string nameLayer = "0", short color = 256) { ObjectId id = ObjectId.Null; Database db = BaseObjs._db; Layer.manageLayers(nameLayer); try { using (Transaction tr = BaseObjs.startTransactionDb()) { Polyline poly = new Polyline(); int i = -1; poly.SetDatabaseDefaults(); foreach (Vertex2d vtx2d in vtxs2d) { i = ++i; Point2d pnt2d = new Point2d(vtx2d.Position.X, vtx2d.Position.Y); poly.AddVertexAt(i, pnt2d, vtx2d.Bulge, vtx2d.StartWidth, vtx2d.EndWidth); } poly.Layer = nameLayer; poly.Color = Color.FromColorIndex(ColorMethod.ByBlock, color); BlockTable bt = (BlockTable)db.BlockTableId.GetObject(OpenMode.ForWrite); BlockTableRecord btr = new BlockTableRecord(); btr.Name = "*U"; btr.Explodable = false; btr.Origin = poly.StartPoint; btr.AppendEntity(poly); btr.Annotative = AnnotativeStates.True; ObjectId idbtr = bt.Add(btr); tr.AddNewlyCreatedDBObject(btr, true); BlockTableRecord ms = (BlockTableRecord)bt[BlockTableRecord.ModelSpace].GetObject(OpenMode.ForWrite); BlockReference br = new BlockReference(poly.StartPoint, idbtr); //BlockTableRecord btrPoly = (BlockTableRecord)tr.GetObject(br.ObjectId, OpenMode.ForWrite); //btrPoly.Name = "*U"; //btrPoly.Annotative = AnnotativeStates.True; id = ms.AppendEntity(br); tr.AddNewlyCreatedDBObject(br, true); tr.Commit(); } } catch (System.Exception ex) { BaseObjs.writeDebug(ex.Message + " Blocks.cs: line: 467"); } return(id); }
public Database() { _dictId2Object = new Dictionary <ObjectId, DBObject>(); _idMgr = new ObjectIdMgr(this); blockTable = new BlockTable(this); Block modelSpace = new Block(); modelSpace.name = "ModelSpace"; blockTable.Add(modelSpace); IdentifyDBTable(blockTable); layerTable = new LayerTable(this); IdentifyDBTable(layerTable); }
/// <summary> /// Loads a block table record from an external database to the current database. /// If the blockname exists on the table record, the block table record id is taken from the curren database block table. /// </summary> /// <param name="blockname">The block table record name.</param> /// <param name="filePath">The dwg block file path.</param> /// <param name="tr">The active transaction.</param> /// <returns>The object id of the block table record</returns> public static ObjectId _LoadBlock(this String blockname, String filePath, Transaction tr) { ObjectId id = new ObjectId(); Database dwg = Application.DocumentManager.MdiActiveDocument.Database; try { BlockTable blkTab = (BlockTable)dwg.BlockTableId.GetObject(OpenMode.ForRead); if (!blkTab.Has(blockname)) { //1: Se crea un registro de bloque blkTab.UpgradeOpen(); BlockTableRecord newRecord = new BlockTableRecord(); newRecord.Name = blockname; //2: Se agregá el registro a la tabla blkTab.Add(newRecord); tr.AddNewlyCreatedDBObject(newRecord, true); //3: Se abre la base de datos externa Database externalDB = new Database(false, true); externalDB.ReadDwgFile(filePath, FileShare.Read, true, ""); //4: Con una subtransacción se clonán los elementos que esten contenidos en el espcio de modelo de la //base de datos externa ObjectIdCollection ids; using (Transaction subTr = externalDB.TransactionManager.StartTransaction()) { //4.1: Abrir el espacio de modelo de la base de datos externa ObjectId modelId = SymbolUtilityServices.GetBlockModelSpaceId(externalDB); BlockTableRecord model = subTr.GetObject(modelId, OpenMode.ForRead) as BlockTableRecord; //4.2: Se extraen y clonan los elementos mediante la clase IdMapping ids = new ObjectIdCollection(model.OfType <ObjectId>().ToArray()); //IEnumerable<DBObject> objs = ids.OfType<ObjectId>().Select(x => x.GetObject(OpenMode.ForRead)); int erased = ids.OfType <ObjectId>().Count(x => x.IsValid); using (IdMapping iMap = new IdMapping()) dwg.WblockCloneObjects(ids, newRecord.Id, iMap, DuplicateRecordCloning.Replace, false); } id = newRecord.Id; } else { id = blkTab[blockname]; } } catch (Exception exc) { throw exc; } return(id); }
DefineNewAnonymousBlockRec() { Debug.Assert(m_trans != null); BlockTableRecord blkRec = null; BlockTable tbl = (BlockTable)m_trans.GetObject(m_db.BlockTableId, OpenMode.ForWrite); blkRec = new BlockTableRecord(); blkRec.Name = "*U"; tbl.Add(blkRec); m_trans.AddNewlyCreatedDBObject(blkRec, true); return(blkRec); }
private ObjectId GetOrCreateBlock(Database db, string blockName, ObjectId textLayerId, ObjectId lineLayerId, ObjectId textStyleId) { ObjectId id = ObjectId.Null; using (Transaction tr = db.TransactionManager.StartTransaction()) { BlockTable table = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead); if (table.Has(blockName)) { id = table[blockName]; } else { BlockTableRecord blockDef = new BlockTableRecord(); blockDef.Name = blockName; table.UpgradeOpen(); id = table.Add(blockDef); tr.AddNewlyCreatedDBObject(blockDef, true); double crossSize = 1; double spacing = 0.5; double th = 1; Point3d pt = new Point3d(0, 0, 0); Line line1 = AcadUtility.AcadEntity.CreateLine(db, pt - new Vector3d(crossSize, 0, 0), pt + new Vector3d(crossSize, 0, 0), lineLayerId); Line line2 = AcadUtility.AcadEntity.CreateLine(db, pt - new Vector3d(0, crossSize, 0), pt + new Vector3d(0, crossSize, 0), lineLayerId); AttributeDefinition text1 = AcadUtility.AcadEntity.CreateAttribute(db, pt + new Vector3d(crossSize + spacing, 0, 0), "Y", "Y", "0 000 000", th, 0, 1, TextHorizontalMode.TextLeft, TextVerticalMode.TextVerticalMid, textStyleId, textLayerId); text1.LockPositionInBlock = true; AttributeDefinition text2 = AcadUtility.AcadEntity.CreateAttribute(db, pt + new Vector3d(0, crossSize + spacing, 0), "X", "X", "0 000 000", th, Math.PI / 2, 1, TextHorizontalMode.TextLeft, TextVerticalMode.TextVerticalMid, textStyleId, textLayerId); text2.LockPositionInBlock = true; foreach (Entity ent in new Entity[] { line1, line2, text1, text2 }) { blockDef.AppendEntity(ent); tr.AddNewlyCreatedDBObject(ent, true); } } tr.Commit(); } return(id); }
public override void Run(string filename, Database db) { using (Transaction tr = db.TransactionManager.StartTransaction()) { try { // Get all items in this space BlockTableRecord btrModel = (BlockTableRecord)tr.GetObject(SymbolUtilityServices.GetBlockModelSpaceId(db), OpenMode.ForWrite); ObjectIdCollection items = new ObjectIdCollection(); foreach (ObjectId id in btrModel) { items.Add(id); } if (items.Count > 0) { // Create the unexlodable anon block BlockTableRecord btrProtected = new BlockTableRecord(); btrProtected.Name = "*U"; btrProtected.Explodable = false; // Add the new block to the block table BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForWrite); ObjectId btrId = bt.Add(btrProtected); tr.AddNewlyCreatedDBObject(btrProtected, true); // Add all entities in this space to the anon block btrProtected.AssumeOwnershipOf(items); // Add the block reference to this space BlockReference br = new BlockReference(Autodesk.AutoCAD.Geometry.Point3d.Origin, btrId); btrModel.AppendEntity(br); tr.AddNewlyCreatedDBObject(br, true); } } catch (System.Exception ex) { OnError(ex); } tr.Commit(); } }
/// <summary> /// 创建一个块表记录并添加到数据库中 /// </summary> /// <param name="db">数据库对象</param> /// <param name="blockName">块名</param> /// <param name="ents">加入块中的实体列表</param> /// <returns>返回块表记录的Id</returns> public static ObjectId AddBlockTableRecord(this Database db, string blockName, List <Entity> ents) { //打开块表 BlockTable bt = (BlockTable)db.BlockTableId.GetObject(OpenMode.ForRead); if (!bt.Has(blockName)) //判断是否存在名为blockName的块 { //创建一个BlockTableRecord类的对象,表示所要创建的块 BlockTableRecord btr = new BlockTableRecord(); btr.Name = blockName;//设置块名 //将列表中的实体加入到新建的BlockTableRecord对象 ents.ForEach(ent => btr.AppendEntity(ent)); bt.UpgradeOpen(); //切换块表为写的状态 bt.Add(btr); //在块表中加入blockName块 db.TransactionManager.AddNewlyCreatedDBObject(btr, true); //通知事务处理 bt.DowngradeOpen(); //为了安全,将块表状态改为读 } return(bt[blockName]); //返回块表记录的Id }
public static Boolean LoadBlock(String path, String blockname, Document doc, Transaction tr) { if (File.Exists(path)) { //Buscamos que no exista el registro BlockTable blkTab = (BlockTable) doc.Database.BlockTableId.GetObject(OpenMode.ForRead); //Si no existe el registro debe cargarse del archivo if (!blkTab.Has(blockname)) { //1: Creación de espacio de bloque blkTab.UpgradeOpen();//A modo escritura para escribir el bloque BlockTableRecord newRecord = new BlockTableRecord(); newRecord.Name = blockname; blkTab.Add(newRecord); tr.AddNewlyCreatedDBObject(newRecord, true); //2: Abrir base de datos externas Database external = new Database(); external.ReadDwgFile(path, FileShare.Read, true, null); ObjectIdCollection ids; //3: Agregarles las entidades mediante un mapeo using (Transaction extTr = external.TransactionManager.StartTransaction()) { BlockTableRecord extModelSpace = (BlockTableRecord) SymbolUtilityServices.GetBlockModelSpaceId(external).GetObject(OpenMode.ForRead); ids = new ObjectIdCollection(extModelSpace.OfType <ObjectId>().ToArray()); using (IdMapping iMap = new IdMapping()) { doc.Database.WblockCloneObjects(ids, newRecord.Id, iMap, DuplicateRecordCloning.Replace, false); } } } return(true); } else { BlockTable blkTab = (BlockTable)doc.Database.BlockTableId.GetObject(OpenMode.ForRead); //Si no existe el registro debe cargarse del archivo return(blkTab.Has(blockname)); } }
public ObjectId AddBlockTableRecord(BlockTableRecord btr, Database db) { ObjectId id = new ObjectId(); try { using (Transaction trans = db.TransactionManager.StartTransaction()) { BlockTable bt = trans.GetObject(db.BlockTableId, OpenMode.ForWrite) as BlockTable; id = bt.Add(btr); trans.AddNewlyCreatedDBObject(btr, true); trans.Commit(); } } catch (Autodesk.AutoCAD.Runtime.Exception ex) { Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(ex.Message); } return(id); }
public static ObjectId ToBlockDefinition(this IEnumerable <Entity> ents, string blockName, Database db = null) { db = (db ?? Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument.Database); ObjectId id = ObjectId.Null; BlockTableRecord blkDef = new BlockTableRecord(); blkDef.Name = blockName; foreach (Entity ent in ents) { blkDef.AppendEntity(ent); } using (Transaction trans = db.TransactionManager.StartTransaction()) { BlockTable blkTbl = trans.GetObject(db.BlockTableId, OpenMode.ForWrite) as BlockTable; id = blkTbl.Add(blkDef); trans.AddNewlyCreatedDBObject(blkDef, true); trans.Commit(); } return(id); }
public ObjectId CreateBlockWithAttributes() { Database db = HostApplicationServices.WorkingDatabase; ObjectId blockId = ObjectId.Null; BlockTableRecord record = new BlockTableRecord(); record.Name = "RMNUM"; using (Transaction trans = db.TransactionManager.StartTransaction()) { Point3dCollection points = new Point3dCollection(); points.Add(new Point3d(-18.0, -6.0, 0.0)); points.Add(new Point3d(18.0, -6.0, 0.0)); points.Add(new Point3d(18.0, 6.0, 0.0)); points.Add(new Point3d(-18.0, 6.0, 0.0)); Polyline2d pline = new Polyline2d(Poly2dType.SimplePoly, points, 0.0, true, 0.0, 0.0, null); record.AppendEntity(pline); AttributeDefinition attdef = new AttributeDefinition(); attdef.Position = new Point3d(0.0, 0.0, 0.0); attdef.Height = 8.0; //设置文字高度 attdef.Rotation = 0.0; //设置文字旋转角度 attdef.HorizontalMode = TextHorizontalMode.TextMid; //设置水平对齐方式 attdef.VerticalMode = TextVerticalMode.TextVerticalMid; //设置垂直对齐方式 attdef.Prompt = "Room Number:"; //设置属性提示 attdef.TextString = "0000"; //设置属性的缺省值 attdef.Tag = "NUMBER"; //设置属性标签 attdef.Invisible = false; //设置不可见选项为假 attdef.Verifiable = false; //设置验证方式为假 attdef.Preset = false; //设置预置方式为假 attdef.Constant = false; //设置常数方式为假 record.Origin = points[3]; record.AppendEntity(attdef); BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForWrite); if (!bt.Has("RMNUM")) //判断是否存在名为"RMNUM"的块 { blockId = bt.Add(record); //在块表中加入"RMNUM"块 trans.AddNewlyCreatedDBObject(record, true); trans.Commit(); } } return(blockId); }
public void CreateBlockFrom() { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; using (Transaction tr = db.TransactionManager.StartOpenCloseTransaction()) { DBObjectCollection objs = new DBObjectCollection(); BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead); //EntProxy.Explode(objs); string blkName = "Getname"; if (bt.Has(blkName) == false) { BlockTableRecord btr = new BlockTableRecord(); btr.Name = blkName; bt.UpgradeOpen(); ObjectId btrId = bt.Add(btr); tr.AddNewlyCreatedDBObject(btr, true); foreach (DBObject obj in objs) { Entity ent = (Entity)obj; btr.AppendEntity(ent); tr.AddNewlyCreatedDBObject(ent, true); } BlockTableRecord ms = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); BlockReference br = new BlockReference(Point3d.Origin, btrId); ms.AppendEntity(br); tr.AddNewlyCreatedDBObject(br, true); } tr.Commit(); } }
public void AddBlockTableRecord() { Database db = HostApplicationServices.WorkingDatabase; BlockTableRecord btr = new BlockTableRecord(); btr.Name = "new Added"; Line line = new Line(Point3d.Origin, new Point3d(10, 15, 0)); Circle circle = new Circle(Point3d.Origin, Vector3d.ZAxis, 15); btr.AppendEntity(line); btr.AppendEntity(circle); ObjectId objectId = new ObjectId(); using (Transaction transaction = db.TransactionManager.StartTransaction()) { BlockTable bt = transaction.GetObject(db.BlockTableId, OpenMode.ForWrite) as BlockTable; objectId = bt.Add(btr); transaction.AddNewlyCreatedDBObject(btr, true); transaction.Commit(); } }
/// <summary> Adds a new block defintion by name. If it already exists then it returns <c>ObjectId.Null</c>. </summary> /// <exception cref="ArgumentNullException"> Thrown when blockDefinitionName is null or empty. </exception> /// <param name="blockDefinitionName"> Name of the block definition. </param> /// <returns> An ObjectId - new if created or existing if the block already exists. </returns> public static ObjectId AddNewBlockDefintion(string blockDefinitionName) { if (string.IsNullOrEmpty(blockDefinitionName)) { throw new ArgumentNullException("blockDefinitionName"); } Database database = Application.DocumentManager.MdiActiveDocument.Database; TransactionManager transactionManager = database.TransactionManager; ObjectId newBlockId; using (Transaction transaction = transactionManager.StartTransaction()) { BlockTable blockTable = transaction.GetObject(database.BlockTableId, OpenMode.ForWrite) as BlockTable; if (blockTable != null && blockTable.Has(blockDefinitionName)) { return(ObjectId.Null); } using (BlockTableRecord blockTableRecord = new BlockTableRecord()) { blockTableRecord.Name = blockDefinitionName; blockTableRecord.Origin = new Point3d(0, 0, 0); using (Circle circle = new Circle()) { circle.Center = new Point3d(0, 0, 0); circle.Radius = 2; blockTableRecord.AppendEntity(circle); if (blockTable != null) { blockTable.Add(blockTableRecord); } transaction.AddNewlyCreatedDBObject(blockTableRecord, true); newBlockId = blockTableRecord.Id; } } transaction.Commit(); } return(newBlockId); }
BlockTableRecord DefinitionFrom(BlockTable table) { WPF.Layer.Ensure(Layer, ColorIndices.Cyan); var record = new BlockTableRecord { Name = BlockName }; var circle = new Circle() { Center = new Point3d(0, 0, 0), Radius = 9.0, // inches Layer = Layer, ColorIndex = ColorIndices.ByLayer, }; record.AppendEntity(circle); table.Add(record); return(record); }
public static void CreateBlock(string _name, DBObjectCollection ents) { Document mdiActiveDocument = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument; Database database = mdiActiveDocument.Database; using (mdiActiveDocument.LockDocument()) { using (Transaction transaction = database.TransactionManager.StartTransaction()) { BlockTable blockTable = (BlockTable)transaction.GetObject(database.BlockTableId, OpenMode.ForRead); BlockTableRecord blockTableRecord = new BlockTableRecord(); if (blockTable.Has(_name)) { blockTableRecord = (BlockTableRecord)transaction.GetObject(blockTable[_name], OpenMode.ForWrite, false, true); foreach (ObjectId id in blockTableRecord) { Entity entity = (Entity)transaction.GetObject(id, OpenMode.ForWrite); entity.Erase(); } ObjectId objectId = blockTableRecord.ObjectId; } else { blockTableRecord.Name = _name; blockTable.UpgradeOpen(); ObjectId objectId = blockTable.Add(blockTableRecord); transaction.AddNewlyCreatedDBObject(blockTableRecord, true); } foreach (object obj2 in ents) { Entity entity = (Entity)obj2; blockTableRecord.AppendEntity(entity); transaction.AddNewlyCreatedDBObject(entity, true); } blockTableRecord.Units = UnitsValue.Millimeters; transaction.Commit(); } } }
private static void ImportMBlock(string path, BlockTable blockTable) { using (Database mBlocksDb = new Database(false, true)) { ObjectIdCollection oidc; mBlocksDb.ReadDwgFile(path, FileShare.Read, false, null); mBlocksDb.CloseInput(true); using (Transaction trans = mBlocksDb.TransactionManager.StartTransaction()) { BlockTable bt = (BlockTable)mBlocksDb.BlockTableId.GetObject(OpenMode.ForRead); BlockTableRecord modelSpace = (BlockTableRecord)bt[BlockTableRecord.ModelSpace].GetObject(OpenMode.ForRead); using (BlockTableRecord btr = new BlockTableRecord()) { bt.UpgradeOpen(); bt.Add(btr); btr.Name = Regex.Match(path, @"M\d{4}").Value; oidc = new ObjectIdCollection(); foreach (ObjectId oid in modelSpace) { oidc.Add(oid); } btr.AssumeOwnershipOf(oidc); trans.AddNewlyCreatedDBObject(btr, true); oidc = new ObjectIdCollection(new ObjectId[] { btr.ObjectId }); } trans.Commit(); } mBlocksDb.WblockCloneObjects(oidc, blockTable.ObjectId, new IdMapping(), DuplicateRecordCloning.Ignore, false); } }
private ObjectId getIdBtrEnd(BlockTable bt) { ObjectId idBtrEnd; if (bt.Has(BlNameEnd)) { // отредактировать существующий блок торца - удалтить все старые объекты idBtrEnd = bt[BlNameEnd]; eraseEntInBlock(idBtrEnd); IsExistsBlockEnd = true; } else { using (var btr = new BlockTableRecord()) { btr.Name = BlNameEnd; bt.UpgradeOpen(); idBtrEnd = bt.Add(btr); bt.Database.TransactionManager.TopTransaction.AddNewlyCreatedDBObject(btr, true); } } return(idBtrEnd); }
/// <summary> 创建块定义 </summary> public static ObjectId CreateBTR(Database db, string blockName, IEnumerable <Entity> ents) { BlockTable blockTable = (BlockTable)db.BlockTableId.GetObject(OpenMode.ForRead); if (!blockTable.Has(blockName)) { var btr = new BlockTableRecord { Name = blockName }; //将列表中的实体加入到新建的BlockTableRecord foreach (var ent in ents) { btr.AppendEntity(ent); } blockTable.UpgradeOpen(); //切换块为写的状态 blockTable.Add(btr); db.TransactionManager.AddNewlyCreatedDBObject(btr, true); blockTable.DowngradeOpen(); //切换块为读的状态 } return(blockTable[blockName]); }
DefineNewBlockRec(string blkName) { Debug.Assert(m_trans != null); BlockTableRecord blkRec = null; BlockTable tbl = (BlockTable)m_trans.GetObject(m_db.BlockTableId, OpenMode.ForWrite); // if it already exists, we are re-defining it and we need to // erase all the existing entities if (tbl.Has(blkName)) { blkRec = (BlockTableRecord)m_trans.GetObject(tbl[blkName], OpenMode.ForWrite); // erase all DBObject tmpObj = null; foreach (ObjectId objId in blkRec) { tmpObj = m_trans.GetObject(objId, OpenMode.ForWrite); if (tmpObj != null) { tmpObj.Erase(true); } } } else { blkRec = new BlockTableRecord(); blkRec.Name = blkName; tbl.Add(blkRec); m_trans.AddNewlyCreatedDBObject(blkRec, true); } return(blkRec); }
private ObjectId getIdBtrEnd(BlockTable bt) { ObjectId idBtrEnd; if (bt.Has(BlNameEnd)) { // отредактировать существующий блок торца - удалтить все старые объекты idBtrEnd = bt[BlNameEnd]; eraseEntInBlock(idBtrEnd); IsExistsBlockEnd = true; } else { using (var btr = new BlockTableRecord()) { btr.Name = BlNameEnd; bt.UpgradeOpen(); idBtrEnd = bt.Add(btr); bt.Database.TransactionManager.TopTransaction.AddNewlyCreatedDBObject(btr, true); } } return idBtrEnd; }
public void AddAnEnt() { Document doc = Application.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; // Declare a PromptKeywordOptions variable and instantiate it by creating // a new PromptKeywordOptions. Use a string similar to the following for the // messageAndKeywords string. // "Which entity do you want to create? [Circle/Block] : ", "Circle Block" PromptKeywordOptions poEntity = new PromptKeywordOptions( "Which entity do you want to create? [Circle/Block] : ", "Circle Block"); // String with the options separated with a space // Instantiate the PromptResult by making it equal to the return value of the GetKeywords method. PromptResult prEntity = ed.GetKeywords(poEntity); if (prEntity.Status == PromptStatus.OK) { switch (prEntity.StringResult) { case "Circle": // Ask for a point, which will be the center of the circle PromptPointOptions poCenterPoint = new PromptPointOptions("Pick Center Point: "); // Pass the prompt to the editor and get the resulting point PromptPointResult prCenterPoint = ed.GetPoint(poCenterPoint); if (prCenterPoint.Status == PromptStatus.OK) { // Ask for a distance (radius) PromptDistanceOptions poRadius = new PromptDistanceOptions("Pick Radius: "); // Make the point selected earlier the base point of the distance prompt poRadius.BasePoint = prCenterPoint.Value; // Tell the prompt to actually use the base point poRadius.UseBasePoint = true; // Get the distance PromptDoubleResult prRadius = ed.GetDistance(poRadius); if (prRadius.Status == PromptStatus.OK) { // Add the circle to the DWG Database dwg = ed.Document.Database; // Start a transaction (as you would with a database) Transaction trans = dwg.TransactionManager.StartTransaction(); try { // Create the circle. // The second parameter is the normal (perpendicular) vector. Circle circle = new Circle(prCenterPoint.Value, Vector3d.ZAxis, prRadius.Value); // Create a new block // A BlockTableRecord is similar to using the "BLOCK" command on AutoCAD. // When we add a record to the current space, we ARE NOT adding it to the "Blocks" utility. BlockTableRecord curSpace = (BlockTableRecord)trans.GetObject(dwg.CurrentSpaceId, OpenMode.ForWrite); // Add the circle to the new block curSpace.AppendEntity(circle); // Tell the transaction about the new object (entity) trans.AddNewlyCreatedDBObject(circle, true); // Commit trans.Commit(); } catch (Autodesk.AutoCAD.Runtime.Exception ex) { // Write exception on the AutoCAD command line ed.WriteMessage("EXCEPTION: " + ex.Message); } finally { // Dispose of the transaction (whether an error has occurred or not) trans.Dispose(); } } } break; case "Block": // Add a prompt to name the block PromptStringOptions poBlockName = new PromptStringOptions("Enter the name of the Block to create: "); // Don't allow spaces, as a block's name can't have spaces poBlockName.AllowSpaces = false; // Get the name PromptResult prBlockName = ed.GetString(poBlockName); if (prBlockName.Status == PromptStatus.OK) { // Add the block to the dwg Database dwg = ed.Document.Database; Transaction trans = dwg.TransactionManager.StartTransaction(); try { // Create new BTR from scratch BlockTableRecord btr = new BlockTableRecord(); // Set name to the prompt result btr.Name = prBlockName.StringResult; // First verify if a block with the same name already exists in the Block Table // We open the Block Table in read, because we won't be changing it right now BlockTable blockTable = (BlockTable)trans.GetObject(dwg.BlockTableId, OpenMode.ForRead); if (blockTable.Has(prBlockName.StringResult)) { throw new Autodesk.AutoCAD.Runtime.Exception( ErrorStatus.InvalidInput, "Cannot create block. Block with same name already exists."); } else { // Update OpenMode to ForWrite blockTable.UpgradeOpen(); // Add to the block table (this will make the block available for the user in the "Block" utility) blockTable.Add(btr); // Tell the transaction about the new object, so that it auto-closes it trans.AddNewlyCreatedDBObject(btr, true); // We defined that the block consists of two circles, so we'll add them Circle circle1 = new Circle(new Point3d(0, 0, 0), Vector3d.ZAxis, 10); Circle circle2 = new Circle(new Point3d(20, 10, 0), Vector3d.ZAxis, 10); btr.AppendEntity(circle1); btr.AppendEntity(circle2); trans.AddNewlyCreatedDBObject(circle1, true); trans.AddNewlyCreatedDBObject(circle2, true); // Prompt for insertion point PromptPointOptions poPoint = new PromptPointOptions("Pick insertion point of BlockRef : "); PromptPointResult prPoint = ed.GetPoint(poPoint); if (prPoint.Status != PromptStatus.OK) { // If point is not valid, return trans.Dispose(); return; } // The BlockTableRecord is the BLOCK (i.e., a template) // The BlockReference is the result of using INSERT (i.e., an instance of a block) BlockReference blockRef = new BlockReference(prPoint.Value, btr.ObjectId); // Add to the current space BlockTableRecord curSpace = (BlockTableRecord)trans.GetObject(dwg.CurrentSpaceId, OpenMode.ForWrite); curSpace.AppendEntity(blockRef); // Finish transaction trans.AddNewlyCreatedDBObject(blockRef, true); trans.Commit(); } } catch (Autodesk.AutoCAD.Runtime.Exception ex) { ed.WriteMessage("EXCEPTION: " + ex.Message); } finally { trans.Dispose(); } } break; } } }
public static void ExImportLayout(this Database targetDb, FileInfo file, string layoutName, Vector3d vector) { if (!file.Exists) { throw new FileNotFoundException("找不到图纸文件", file.FullName); } var doc = Application.DocumentManager.MdiActiveDocument; if (doc == null) { throw new Exception("没有打开的文档,无法执行命令"); } var targetlayoutName = layoutName; var ed = doc.Editor; var layoutNames = HostApplicationServices.WorkingDatabase.ExGetLayoutNames(); while (layoutNames.Contains(targetlayoutName)) { var prompt = ed.DoPrompt(new PromptStringOptions($"{Environment.NewLine}布局[{targetlayoutName}]已存在,请指定新的布局名称:{Environment.NewLine}")); if (prompt.Status != PromptStatus.OK) { return; } targetlayoutName = prompt.StringResult; } Database sourceDb = new Database(false, true); sourceDb.ReadDwgFile(file.FullName, FileOpenMode.OpenForReadAndAllShare, true, ""); using (Transaction sourceTr = sourceDb.TransactionManager.StartTransaction()) { var sourceLayout = sourceDb.ExGetLayout(layoutName, sourceTr); // Create a transaction for the current drawing using (Transaction targetTr = targetDb.TransactionManager.StartTransaction()) { // Get the block table and create a new block // then copy the objects between drawings BlockTable blkTbl = targetTr.GetObject(targetDb.BlockTableId, OpenMode.ForWrite) as BlockTable; using (BlockTableRecord newLayoutBtr = new BlockTableRecord()) { newLayoutBtr.Name = $"*Paper_Space{layoutNames.Count-1}"; blkTbl.Add(newLayoutBtr); targetTr.AddNewlyCreatedDBObject(newLayoutBtr, true); targetDb.WblockCloneObjects(sourceLayout.ExGetObejctIds(sourceTr), newLayoutBtr.ObjectId, new IdMapping(), DuplicateRecordCloning.Ignore, false); // Create a new layout and then copy properties between drawings DBDictionary layouts = targetTr.GetObject(targetDb.LayoutDictionaryId, OpenMode.ForWrite) as DBDictionary; using (Layout lay = new Layout()) { lay.LayoutName = targetlayoutName; lay.AddToLayoutDictionary(targetDb, newLayoutBtr.ObjectId); targetTr.AddNewlyCreatedDBObject(lay, true); lay.CopyFrom(sourceLayout); var plotsettings = sourceDb.ExGetPlotSettings(sourceTr, sourceLayout.PlotSettingsName); targetDb.ExImportPlotSettings(targetTr, plotsettings); } //所有视口重新定位到指定点 int vieportindex = 0; foreach (var oid in newLayoutBtr) { var obj = targetTr.GetObject(oid, OpenMode.ForRead); if (obj is Viewport) { if (vieportindex != 0) { var vp = obj as Viewport; vp.UpgradeOpen(); vp.ViewCenter += new Vector2d(vector.X, vector.Y); } vieportindex++; } } } targetTr.Commit(); } } }
//loads the block into the blocktable if it isnt there //then uses a jig to find extents of print area public static Extents3d BlockInserter(Database db, Editor ed, Document doc) { //create a window to show the plot area Polyline polyPlot = new Polyline(); polyPlot.AddVertexAt(0, new Point2d(-4.25, 5.5), 0, 0, 0); polyPlot.AddVertexAt(1, new Point2d(4.25, 5.5), 0, 0, 0); polyPlot.AddVertexAt(2, new Point2d(4.25, -5.5), 0, 0, 0); polyPlot.AddVertexAt(3, new Point2d(-4.25, -5.5), 0, 0, 0); polyPlot.Closed = true; using (Transaction trCurrent = db.TransactionManager.StartTransaction()) { //open block table for read BlockTable btCurrent = trCurrent.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; //check if spec is already loaded into drawing ObjectId blkRecId = ObjectId.Null; if (!btCurrent.Has("PlotGuide")) { using (BlockTableRecord newRec = new BlockTableRecord()) { newRec.Name = "PlotGuide"; newRec.Origin = new Point3d(0, 0, 0); //add the polyline to the block newRec.AppendEntity(polyPlot); //from read to write btCurrent.UpgradeOpen(); btCurrent.Add(newRec); trCurrent.AddNewlyCreatedDBObject(newRec, true); blkRecId = newRec.Id; } } else { blkRecId = btCurrent["PlotGuide"]; } //now insert block into current space using our jig Point3d stPnt = new Point3d(0, 0, 0); BlockReference br = new BlockReference(stPnt, blkRecId); BlockJig entJig = new BlockJig(br); //use jig Extents3d printWindow = new Extents3d(); //loop as jig is running, to get keywords/key strokes for rotation PromptStatus stat = PromptStatus.Keyword; while (stat == PromptStatus.Keyword) { //use iMsg filter var filt = new TxtRotMsgFilter(doc); WinForms.Application.AddMessageFilter(filt); PromptResult pr = ed.Drag(entJig); WinForms.Application.RemoveMessageFilter(filt); stat = pr.Status; if (stat == PromptStatus.OK) { printWindow = entJig.GetEntity().GeometricExtents; } //commit changes } trCurrent.Commit(); return(printWindow); } }
public static void CreatePlotType() { Document acDoc = Application.DocumentManager.MdiActiveDocument; Editor acEditor = acDoc.Editor; Database acCurDb = acDoc.Database; if (CurrentOpen == null) { PromptStringOptions pStrOpts = new PromptStringOptions("\nEnter plot type name: ") { AllowSpaces = true }; PromptResult pStrRes = acDoc.Editor.GetString(pStrOpts); //Verify input if (pStrRes.Status == PromptStatus.OK) { //Check the block does not already exist bool exists = false; using (Transaction tr = acCurDb.TransactionManager.StartTransaction()) { //Create all plot specific layers LayerTable acLayerTable = tr.GetObject(acCurDb.LayerTableId, OpenMode.ForWrite) as LayerTable; Core.Utilities.CreateLayer(tr, acLayerTable, Constants.JPP_HS_PlotPerimiter, Constants.JPP_HS_PlotPerimiterColor); //Create the background block BlockTable bt = (BlockTable)tr.GetObject(acCurDb.BlockTableId, OpenMode.ForRead); if (bt.Has(pStrRes.StringResult)) { exists = true; } } if (!exists) { // Prompt for the start point PromptPointOptions pPtOpts = new PromptPointOptions("") { Message = "\nEnter the base point. Basepoint to be located at bottom left corner of the plot: " }; PromptPointResult pPtRes = acDoc.Editor.GetPoint(pPtOpts); if (pPtRes.Status == PromptStatus.OK) { CurrentOpen = new PlotType() { PlotTypeName = pStrRes.StringResult, BasePoint = pPtRes.Value }; using (Transaction tr = acCurDb.TransactionManager.StartTransaction()) { Main.AddRegAppTableRecord(); //Create all plot specific layers LayerTable acLayerTable = tr.GetObject(acCurDb.LayerTableId, OpenMode.ForWrite) as LayerTable; Core.Utilities.CreateLayer(tr, acLayerTable, Constants.JPP_HS_PlotPerimiter, Constants.JPP_HS_PlotPerimiterColor); //Create the background block BlockTable bt = (BlockTable)tr.GetObject(acCurDb.BlockTableId, OpenMode.ForRead); bt.UpgradeOpen(); BlockTableRecord backgroundBlockRecord = new BlockTableRecord { Name = CurrentOpen.PlotTypeName + "Background", Origin = CurrentOpen.BasePoint }; ObjectId objRef = bt.Add(backgroundBlockRecord); tr.AddNewlyCreatedDBObject(backgroundBlockRecord, true); //Prep the block for finalising BlockTableRecord plotTypeBlockRecord = new BlockTableRecord { Name = CurrentOpen.PlotTypeName, Origin = CurrentOpen.BasePoint }; ObjectId blockRef = bt.Add(plotTypeBlockRecord); tr.AddNewlyCreatedDBObject(plotTypeBlockRecord, true); //Insert the background block CurrentOpen.BackgroundBlockID = Core.Utilities.InsertBlock(CurrentOpen.BasePoint, 0, objRef); CurrentOpen.BlockID = blockRef; //Create and add basepoint Circle bp = new Circle { Center = CurrentOpen.BasePoint, Radius = 0.5f }; BlockTableRecord acBlkTblRec = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; if (acBlkTblRec != null) { CurrentOpen.BasepointID = acBlkTblRec.AppendEntity(bp); } else { //This should never, ever come up but best to handle it throw new NullReferenceException("Model space not found", null); } tr.AddNewlyCreatedDBObject(bp, true); tr.Commit(); } //Inform all event handlers the current plot type has changed OnCurrentOpenChanged?.Invoke(); } else { acEditor.WriteMessage("Point selection cancelled\n"); } } else { acEditor.WriteMessage("Plot Type Name already exists as block. Please choose a different name or rename exisitng block\n"); } } else { acEditor.WriteMessage("No plot type name entered\n"); } } else { acEditor.WriteMessage("Plot Type already open for editing. Please finalise before attempting to create a new plot type.\n"); } }