public static bool EraseBlkRefs(ObjectId blkId) { bool blkRefsErased = false; if (blkId.IsNull) { return(false); } Database db = blkId.Database; if (db == null) { return(false); } using (Transaction tr = db.TransactionManager.StartTransaction()) { BlockTableRecord blk = (BlockTableRecord)tr.GetObject(blkId, OpenMode.ForRead); var blkRefs = blk.GetBlockReferenceIds(true, true); if (blkRefs != null && blkRefs.Count > 0) { foreach (ObjectId blkRefId in blkRefs) { BlockReference blkRef = (BlockReference)tr.GetObject(blkRefId, OpenMode.ForWrite); blkRef.Erase(); } blkRefsErased = true; } tr.Commit(); } return(blkRefsErased); }
public void GetLayoutsWithDynBlocks(Transaction trans) { // получаем таблицу блоков и проходим по всем записям таблицы блоков _blokTable = (BlockTable)trans.GetObject(Active.Database.BlockTableId, OpenMode.ForRead); foreach (ObjectId btrId in _blokTable) { // получаем запись таблицы блоков и смотри анонимная ли она BlockTableRecord btr = (BlockTableRecord)trans.GetObject(btrId, OpenMode.ForRead); if (btr.IsDynamicBlock && BlockNameToSearch.Contains(btr.Name)) { // получаем все анонимные блоки динамического блока ObjectIdCollection anonymousIds = btr.GetAnonymousBlockIds(); foreach (ObjectId anonymousBtrId in anonymousIds) { // получаем анонимный блок BlockTableRecord anonymousBtr = (BlockTableRecord)trans.GetObject(anonymousBtrId, OpenMode.ForRead); // получаем все вставки этого блока BlockRefIds = anonymousBtr.GetBlockReferenceIds(true, true); GetBlockInLayout(trans); } } } }
public static bool EraseBlk(ObjectId blkId) { bool blkIsErased = false; if (blkId.IsNull) { return(false); } Database db = blkId.Database; if (db == null) { return(false); } using (Transaction tr = db.TransactionManager.StartTransaction()) { BlockTableRecord blk = (BlockTableRecord)tr.GetObject(blkId, OpenMode.ForRead); var blkRefs = blk.GetBlockReferenceIds(true, true); if (blkRefs == null || blkRefs.Count == 0) { blk.UpgradeOpen(); blk.Erase(); blkIsErased = true; } tr.Commit(); } return(blkIsErased); }
public List <string> GetParentBlokName() { List <string> newlist = new List <string>(); dataParentBlok = new List <string>(); using (Transaction tr = acDb.TransactionManager.StartTransaction()) { BlockTable bt = acDb.BlockTableId.GetObject(OpenMode.ForRead) as BlockTable; foreach (ObjectId objId in bt) { BlockTableRecord btr = (BlockTableRecord)objId.GetObject(OpenMode.ForRead); if (btr.IsAnonymous) { continue; } if (btr.GetBlockReferenceIds(true, false).Count > 0) { if (btr.HasAttributeDefinitions) { newlist.Add(btr.Name); dataParentBlok.Add(btr.Name); } } } } return(newlist); }
public List <string> GetBlokRefs() { List <string> ParentBlok = new List <string>(); ParentBlok.AddRange(dataParentBlok); List <string> newlist = new List <string>(); foreach (string item in ParentBlok) { using (Transaction tr = acDb.TransactionManager.StartTransaction()) { BlockTable bt = acDb.BlockTableId.GetObject(OpenMode.ForRead) as BlockTable; BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[item], OpenMode.ForRead); ObjectIdCollection objIds = btr.GetBlockReferenceIds(true, false); foreach (ObjectId id in objIds) { BlockReference bRef = (BlockReference)tr.GetObject(id, OpenMode.ForRead); AttList = new List <string>(); newlist.Add(string.Format("{0}:{1}", btr.Name, id)); foreach (ObjectId idRef in bRef.AttributeCollection) { AttributeReference AttRef = (AttributeReference)tr.GetObject(idRef, OpenMode.ForRead); AttList.Add(String.Format("[{0}:{1}]", AttRef.Tag, AttRef.TextString)); } } } } return(newlist); }
public static void SynchronizeAttributes(this BlockTableRecord target) { if (target == null) { throw new ArgumentNullException("target"); } Transaction tr = target.Database.TransactionManager.TopTransaction; if (tr == null) { throw new Autodesk.AutoCAD.Runtime.Exception(ErrorStatus.NoActiveTransactions); } List <AttributeDefinition> attDefs = target.GetAttributes(tr); foreach (ObjectId id in target.GetBlockReferenceIds(true, false)) { BlockReference br = (BlockReference)tr.GetObject(id, OpenMode.ForWrite); br.ResetAttributes(attDefs, tr); } if (target.IsDynamicBlock) { target.UpdateAnonymousBlocks(); foreach (ObjectId id in target.GetAnonymousBlockIds()) { BlockTableRecord btr = (BlockTableRecord)tr.GetObject(id, OpenMode.ForRead); attDefs = btr.GetAttributes(tr); foreach (ObjectId brId in btr.GetBlockReferenceIds(true, false)) { BlockReference br = (BlockReference)tr.GetObject(brId, OpenMode.ForWrite); br.ResetAttributes(attDefs, tr); } } } }
/// <summary> /// Синхронизация атрибутов блока. Требуется запущенная транзакция /// </summary> public static void SynchronizeAttributes([NotNull] this BlockTableRecord target) { if (target == null) { throw new ArgumentNullException(nameof(target)); } var tr = target.Database.TransactionManager.TopTransaction; if (tr == null) { throw new Autodesk.AutoCAD.Runtime.Exception(ErrorStatus.NoActiveTransactions); } var attDefs = target.GetAttributes(tr); foreach (ObjectId id in target.GetBlockReferenceIds(true, false)) { var br = id.GetObjectT <BlockReference>(); br.ResetAttributes(attDefs, tr); } if (target.IsDynamicBlock) { target.UpdateAnonymousBlocks(); foreach (ObjectId id in target.GetAnonymousBlockIds()) { var btr = id.GetObjectT <BlockTableRecord>(); attDefs = btr.GetAttributes(tr); foreach (ObjectId brId in btr.GetBlockReferenceIds(true, false)) { var br = brId.GetObject <BlockReference>(OpenMode.ForWrite); br?.ResetAttributes(attDefs, tr); } } } }
private Dictionary <string, List <string> > KoleksiBlok(string blkRefName) { Dictionary <string, List <string> > newList = new Dictionary <string, List <string> >(); using (Transaction trx = db.TransactionManager.StartTransaction()) { BlockTable bt = db.BlockTableId.GetObject(OpenMode.ForRead) as BlockTable; BlockTableRecord btr = (BlockTableRecord)trx.GetObject(bt[blkRefName], OpenMode.ForRead); ObjectIdCollection objIds = btr.GetBlockReferenceIds(true, false); foreach (ObjectId id in objIds) { BlockReference bRef = (BlockReference)trx.GetObject(id, OpenMode.ForRead); List <string> AttList = new List <string>(); foreach (ObjectId idRef in bRef.AttributeCollection) { AttributeReference AttRef = (AttributeReference)trx.GetObject(idRef, OpenMode.ForRead); AttList.Add(String.Format("[{0}:{1}]", AttRef.Tag, AttRef.TextString)); } newList.Add(bRef.Name, AttList); } trx.Commit(); } return(newList); }
private static ObjectId FetchFFLBlockID() { Document acDoc = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument; Database acCurrDb = acDoc.Database; Editor acEditor = acDoc.Editor; // Create the selection filter for the FFL block TypedValue[] selFilterList = new TypedValue[2]; selFilterList[0] = new TypedValue(0, "INSERT"); selFilterList[1] = new TypedValue(2, "JPP_App_Outline*"); SelectionFilter selFilter = new SelectionFilter(selFilterList); // Set prompt options and message PromptSelectionOptions selOptions = new PromptSelectionOptions(); selOptions.MessageForAdding = "Select FFL block: "; selOptions.SinglePickInSpace = true; selOptions.SingleOnly = true; // Prompt user to select FFL add exposed brickwork PromptSelectionResult selResult = acEditor.GetSelection(selOptions, selFilter); ObjectId[] FFLToEditId = selResult.Value.GetObjectIds(); ObjectId blockId = FFLToEditId[0]; using (Transaction acTrans = acCurrDb.TransactionManager.StartTransaction()) { try { BlockTable acBlkTbl = acTrans.GetObject(acCurrDb.BlockTableId, OpenMode.ForRead) as BlockTable; BlockReference fflBlock = acTrans.GetObject(blockId, OpenMode.ForRead) as BlockReference; BlockTableRecord acBlkTblRec = acTrans.GetObject(acBlkTbl[fflBlock.Name], OpenMode.ForRead) as BlockTableRecord; if (acBlkTblRec == null) { acEditor.WriteMessage("\nError FFL block not found."); acTrans.Commit(); return(ObjectId.Null); } // Check there is only one instance of this block reference in the drawing if (acBlkTblRec.GetBlockReferenceIds(false, true).Count != 1) { acEditor.WriteMessage("\nError more than one instance of the block reference."); acTrans.Commit(); return(ObjectId.Null); } acTrans.Commit(); return(fflBlock.ObjectId); } catch (Autodesk.AutoCAD.Runtime.Exception acException) { Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog ("The following exception was caught: \n" + acException.Message + "\nError retrieving FFL Block Id!\n"); acTrans.Abort(); return(ObjectId.Null); } } }
/// <summary> /// Обновление графики во вхождениях блока для данного определения блока /// Должна быть запущена транзакция!!! /// </summary> public static void SetBlRefsRecordGraphicsModified([NotNull] this BlockTableRecord btr) { var idsBlRef = btr.GetBlockReferenceIds(true, false); foreach (ObjectId idBlRefApart in idsBlRef) { var blRefApartItem = (BlockReference)idBlRefApart.GetObject(OpenMode.ForWrite, false, true); blRefApartItem.RecordGraphicsModified(true); } }
public void DynamicBlockTest() { BlockReference br; if (!ObjectCollector.TrySelectAllowedClassObject(out br)) { return; } Tools.StartTransaction(() => { br = br.Id.GetObjectForRead <BlockReference>(); var pSet = br.DynamicBlockReferencePropertyCollection; BlockTableRecord btr = br.BlockTableRecord.GetObjectForRead <BlockTableRecord>(); if (pSet == null) { return; } foreach (DynamicBlockReferenceProperty p in pSet) { if (p.PropertyTypeCode == (short)PropertyTypeCodes.Mirror) { Type t = p.Value.GetType(); p.Value = (short)((short)p.Value == 0 ? 1 : 0); } } BlockTableRecord btrDyn = br.DynamicBlockTableRecord.GetObjectForRead <BlockTableRecord>(); foreach (ObjectId id in btrDyn.GetBlockReferenceIds(false, false)) { var brDyn = id.GetObjectForRead <BlockReference>(); pSet = brDyn.DynamicBlockReferencePropertyCollection; if (pSet == null) { return; } foreach (DynamicBlockReferenceProperty p in pSet) { object obj = p; } } var rbuffer = btrDyn.XData; byte[] buffer = new byte[System.Runtime.InteropServices.Marshal.SizeOf(rbuffer.UnmanagedObject)]; IntPtr destPtr = System.Runtime.InteropServices.Marshal.AllocHGlobal(rbuffer.UnmanagedObject); System.Runtime.InteropServices.Marshal.Copy(rbuffer.UnmanagedObject, buffer, 0, System.Runtime.InteropServices.Marshal.SizeOf(rbuffer.UnmanagedObject)); }); }
static void ed_PointMonitor(object sender, PointMonitorEventArgs e) { string blockInfo = ""; //用于存储块参照的信息:名称和个数 //获取命令行对象(鼠标监视事件的发起者),用于获取文档对象 Editor ed = (Editor)sender; Document doc = ed.Document; InputPointContext ic = e.Context; //获取鼠标停留处的实体 FullSubentityPath[] paths = e.Context.GetPickedEntities(); using (Transaction trans = doc.TransactionManager.StartTransaction()) { //如果鼠标停留处有实体 if (paths.Length > 0) { //获取鼠标停留处的实体 FullSubentityPath path = paths[0]; BlockReference blockRef = trans.GetObject(path.GetObjectIds()[0], OpenMode.ForRead) as BlockReference; if (blockRef != null)//如果鼠标停留处为块参照 { //获取块参照所属的块表记录并以写的方式打开 ObjectId blockId = blockRef.BlockTableRecord; BlockTableRecord btr = trans.GetObject(blockId, OpenMode.ForRead) as BlockTableRecord; //获取属于同一块表记录的所有块参照 ObjectIdCollection ids = btr.GetBlockReferenceIds(true, false); //若鼠标停留处的块参照的块表记录与上一次的不同 Entity ent = null; if (ids.Count >= 0) { ent = trans.GetObject(ids[0], OpenMode.ForRead) as Entity; } if (ent != null && blockName != btr.Name || ent.HighlightState(path) == HighlightStyle.None) { blockName = btr.Name; //重新设置块表记录名 blockIds.UnHighlightEntities(); //取消上一次块表记录的块参照的亮显 blockIds.Clear(); //清空块参照ObjectId列表 blockIds = ids; //设置需要亮显的块参照的ObjectId列表 blockIds.HighlightEntities(); //亮显所有同名的块参照 } blockInfo += "块名:" + btr.Name + "\n个数:" + blockIds.Count.ToString(); } } trans.Commit(); } if (blockInfo != "") { e.AppendToolTipText(blockInfo);//在鼠标停留处显示提示信息 } }
public static List <string> GetBlockRefSelected(string brefName) { List <string> newList = new List <string>(); Document doc = AcAp.DocumentManager.MdiActiveDocument; Database db = doc.Database; using (Transaction tr = db.TransactionManager.StartTransaction()) { BlockTable bt = db.BlockTableId.GetObject(OpenMode.ForRead) as BlockTable; foreach (ObjectId objId in bt) { BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[brefName], OpenMode.ForRead); if (btr.IsAnonymous) { continue; } if (btr.GetBlockReferenceIds(true, false).Count > 0) { if (btr.HasAttributeDefinitions) { ObjectIdCollection objIds = btr.GetBlockReferenceIds(true, false); foreach (ObjectId brefId in objIds) { BlockReference bRef = (BlockReference)tr.GetObject(brefId, OpenMode.ForRead); Autodesk.AutoCAD.DatabaseServices.AttributeCollection atRefColl = bRef.AttributeCollection; foreach (ObjectId atId in atRefColl) { AttributeReference atdef = (AttributeReference)tr.GetObject(atId, OpenMode.ForRead); newList.Add(atdef.Tag); } } } } } } return(newList); }
public static IEnumerable <ObjectId> GetAllBlockReferenceIds(this BlockTableRecord btr, bool directOnly) { IEnumerable <ObjectId> brefIds = btr .GetBlockReferenceIds(directOnly, false) .Cast <ObjectId>() .Concat( btr.GetAnonymousBlockIds() .Cast <ObjectId>() .SelectMany( n => ((BlockTableRecord)n.GetObject(OpenMode.ForRead)) .GetBlockReferenceIds(directOnly, false) .Cast <ObjectId>())); return(brefIds); }
/// <summary> /// Возвращает ObjectId всех вхождений блока. В том числе если блок динамический /// </summary> /// <param name="btr">BlockTableRecord блока, чьи вхождения надо искать</param> /// <returns>Коллекцию вхождений блока, в том числе динамических</returns> public static IEnumerable <ObjectId> GetAllBlockReferenceIds(this BlockTableRecord btr, bool directOnly) { Database db = btr.Database; IEnumerable <ObjectId> brefIds = btr .GetBlockReferenceIds(directOnly, false) .Cast <ObjectId>() .Concat( btr.GetAnonymousBlockIds() .Cast <ObjectId>() .SelectMany( n => n.GetObject <BlockTableRecord>() .GetBlockReferenceIds(directOnly, false) .Cast <ObjectId>())); return(brefIds); }
public Dictionary <string, ObjectId> GetBlockReferenceFromBtIds(PilihanDrawing mode) { Dictionary <string, ObjectId> newList = new Dictionary <string, ObjectId>(); ObjectIdCollection objIds = new ObjectIdCollection(); switch (mode) { case PilihanDrawing.CurrentDrawing: break; case PilihanDrawing.PickFromDrawing: break; case PilihanDrawing.ExternalDrawing: foreach (KeyValuePair <string, ObjectId> btName in GetBT_IDs) { for (int i1 = 0; i1 < DBFiles.Count; i1++) { acDbs = new Database(false, true); try { acDbs.ReadDwgFile(ListFileDwgs[i1].FullName, FileShare.Read, false, ""); } catch (Autodesk.AutoCAD.Runtime.Exception acExep) { throw new Autodesk.AutoCAD.Runtime.Exception(ErrorStatus.FilerError, acExep.Message); } using (Transaction tr = acDbs.TransactionManager.StartTransaction()) { BlockTable bt = acDbs.BlockTableId.GetObject(OpenMode.ForRead) as BlockTable; BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[btName.Key], OpenMode.ForRead); objIds = btr.GetBlockReferenceIds(true, false); foreach (ObjectId id in objIds) { BlockReference bRef = (BlockReference)tr.GetObject(id, OpenMode.ForRead); newList.Add(btr.Name + id, id); } } } } break; default: break; } return(newList); }
public static void RefreshBlockGraphics( BlockTableRecord block) { Database documentDatabase = block.Database; using (var transaction = documentDatabase.TransactionManager.StartTransaction()) { var blockReference = (BlockReference)transaction.GetObject( block.GetBlockReferenceIds(true, true)[0], OpenMode.ForWrite); blockReference.Position = blockReference.Position; transaction.Commit(); } }
public void Update() { Tools.StartTransaction(() => { if (_blockRecordId != ObjectId.Null) { BlockTableRecord btr = _blockRecordId.GetObjectForRead <BlockTableRecord>(false); //btr.UpgradeOpen(); foreach (ObjectId id in btr.GetBlockReferenceIds(true, true)) { BlockReference br = id.GetObjectForWrite <BlockReference>(false); br.RecordGraphicsModified(true); btr.Database.TransactionManager.QueueForGraphicsFlush(); } } }); }
private void FillTreeView() { using (Transaction trx = db.TransactionManager.StartTransaction()) { datablok = new List <string>(); BlockTable bt = db.BlockTableId.GetObject(OpenMode.ForRead) as BlockTable; foreach (ObjectId BtId in bt) { BlockTableRecord BlokTblRec = (BlockTableRecord)BtId.GetObject(OpenMode.ForRead); if (BlokTblRec.HasAttributeDefinitions) { datablok.Add(string.Format("{0}|{1}", BlokTblRec.Name, BtId)); listBox1.Items.Add(string.Format("{0}|{1}", BlokTblRec.Name, BtId)); } } foreach (string item in datablok) { string[] SplitItem = item.Split('|'); BlockTableRecord btr = (BlockTableRecord)trx.GetObject(bt[SplitItem[0]], OpenMode.ForRead); ObjectIdCollection objIds = btr.GetBlockReferenceIds(true, false); AttributBlok = new List <string>(); koleksi = new ObjectIdCollection(); foreach (ObjectId id in objIds) { AttributBlok.Add(string.Format("{0}|{1}", btr.Name, id)); koleksi.Add(id); listBox2.Items.Add(string.Format("{0}|{1}", btr.Name, id)); } foreach (ObjectId itemid in koleksi) { BlockReference bRef = (BlockReference)trx.GetObject( itemid, OpenMode.ForRead); foreach (ObjectId idRef in bRef.AttributeCollection) { AttributeReference AttRef = (AttributeReference)trx.GetObject( idRef, OpenMode.ForRead); AttributBlok.Add(String.Format("[{0}:{1}]", AttRef.Tag, AttRef.TextString)); } } } } }
public static void UpdateParam() { //Get active document of drawing with Dynamic block var doc = Application.DocumentManager.MdiActiveDocument; var db = doc.Database; // read input parameters from JSON file InputParams inputParams = JsonConvert.DeserializeObject <InputParams>(File.ReadAllText("params.json")); using (Transaction t = db.TransactionManager.StartTransaction()) { var bt = t.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; foreach (ObjectId btrId in bt) { //get the blockDef and check if is anonymous BlockTableRecord btr = (BlockTableRecord)t.GetObject(btrId, OpenMode.ForRead); if (btr.IsDynamicBlock) { //get all anonymous blocks from this dynamic block ObjectIdCollection anonymousIds = btr.GetAnonymousBlockIds(); ObjectIdCollection dynBlockRefs = new ObjectIdCollection(); foreach (ObjectId anonymousBtrId in anonymousIds) { //get the anonymous block BlockTableRecord anonymousBtr = (BlockTableRecord)t.GetObject(anonymousBtrId, OpenMode.ForRead); //and all references to this block ObjectIdCollection blockRefIds = anonymousBtr.GetBlockReferenceIds(true, true); foreach (ObjectId id in blockRefIds) { dynBlockRefs.Add(id); } } if (dynBlockRefs.Count > 0) { //Get the first dynamic block reference, we have only one Dyanmic Block reference in Drawing var dBref = t.GetObject(dynBlockRefs[0], OpenMode.ForWrite) as BlockReference; UpdateDynamicProperties(dBref, inputParams); } } } t.Commit(); } LogTrace("Saving file..."); db.SaveAs("outputFile.dwg", DwgVersion.Current); }
void ChangeAttributeValue(String AttributeTagName, String OldValue, String NewValue) { Document activeDoc = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument; Database db = activeDoc.Database; using (Transaction tr = db.TransactionManager.StartTransaction()) { BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForWrite) as BlockTable; foreach (ObjectId oid in bt) { BlockTableRecord btr = tr.GetObject(oid, OpenMode.ForWrite) as BlockTableRecord; if (!btr.IsLayout) { ObjectIdCollection brefIds = btr.GetBlockReferenceIds(false, false); foreach (ObjectId brId in brefIds) { BlockReference bref = tr.GetObject(brId, OpenMode.ForRead) as BlockReference; foreach (ObjectId arId in bref.AttributeCollection) { AttributeReference ar = tr.GetObject(arId, OpenMode.ForRead) as AttributeReference; if (ar != null) { if (ar.Tag.ToUpper().Equals(AttributeTagName.ToUpper())) { if (ar.TextString.ToUpper().Equals(OldValue)) { ar.UpgradeOpen(); ar.TextString = NewValue; } } } } } } } tr.Commit(); } }
/// <summary> /// Get all references to the given BlockTableRecord, including /// references to anonymous dynamic BlockTableRecords. /// </summary> public static IEnumerable <BlockReference> GetBlockReferences( this BlockTableRecord btr, OpenMode mode = OpenMode.ForRead, bool directOnly = true) { if (btr == null) { throw new ArgumentNullException("btr"); } var tr = btr.Database.TransactionManager.TopTransaction; if (tr == null) { throw new InvalidOperationException("No transaction"); } var ids = btr.GetBlockReferenceIds(directOnly, true); var cnt = ids.Count; for (var i = 0; i < cnt; i++) { yield return((BlockReference) tr.GetObject(ids[i], mode, false, false)); } if (btr.IsDynamicBlock) { BlockTableRecord btr2 = null; var blockIds = btr.GetAnonymousBlockIds(); cnt = blockIds.Count; for (var i = 0; i < cnt; i++) { btr2 = (BlockTableRecord)tr.GetObject(blockIds[i], OpenMode.ForRead, false, false); ids = btr2.GetBlockReferenceIds(directOnly, true); var cnt2 = ids.Count; for (var j = 0; j < cnt2; j++) { yield return((BlockReference) tr.GetObject(ids[j], mode, false, false)); } } } }
public void ChangeBlock(string blockName, string roomNumber) { Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; Database db = HostApplicationServices.WorkingDatabase; using (Transaction trans = db.TransactionManager.StartTransaction()) { //打开块表 BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead); //打开块表中名为blockName的块表记录 BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[blockName], OpenMode.ForRead); //获取所有名为blockName的块参照 ObjectIdCollection blcokRefIds = btr.GetBlockReferenceIds(true, true); //循环遍历块参照 foreach (ObjectId blockRefId in blcokRefIds) { //打开当前块参照 BlockReference blockRef = (BlockReference)trans.GetObject(blockRefId, OpenMode.ForRead); //获取当前块参照的属性集合 AttributeCollection blockRefAtts = blockRef.AttributeCollection; //循环遍历属性集合 foreach (ObjectId attId in blockRefAtts) { //获取当前属性参照对象 AttributeReference attRef = (AttributeReference)trans.GetObject(attId, OpenMode.ForRead); //只改变NUMBER属性值为"0000"的属性值为roomNumber switch (attRef.Tag) { case "NUMBER": if (attRef.TextString == "0000") { attRef.UpgradeOpen(); //切换属性参照对象为可写状态 attRef.TextString = roomNumber; } break; } } } trans.Commit(); } }
public static List <BlockReference> GetListBlockReferences(BlockTableRecord block) { Database documentDatabase = block.Database; List <BlockReference> listReferences = new List <BlockReference>(); using (var transaction = documentDatabase.TransactionManager.StartTransaction()) { ObjectIdCollection objectIdCollection = block.GetBlockReferenceIds(true, true); foreach (ObjectId id in objectIdCollection) { listReferences.Add((BlockReference)transaction.GetObject(id, OpenMode.ForWrite)); } transaction.Commit(); } return(listReferences); }
/// <summary> /// Method for getting all blockreference Ids /// </summary> /// <param name="btr">The BTR.</param> /// <param name="trx">The TRX.</param> /// <param name="directOnly">if set to <c>true</c> [direct only].</param> /// <param name="forceValidity">if set to <c>true</c> [force validity].</param> /// <returns></returns> /// <exception cref="Exception"></exception> public static ObjectIdCollection GetAllBlockReferenceIds(this BlockTableRecord btr, Transaction trx, bool directOnly, bool forceValidity) { if (trx == null) { throw new Exception(ErrorStatus.NoActiveTransactions); } ObjectIdCollection blockReferenceIds = btr.GetBlockReferenceIds(directOnly, forceValidity); if (!btr.IsDynamicBlock) { return(blockReferenceIds); } foreach (ObjectId id in btr.GetAnonymousBlockIds()) { BlockTableRecord record = trx.GetObject(id, OpenMode.ForRead) as BlockTableRecord; blockReferenceIds.Add(record.GetBlockReferenceIds(directOnly, forceValidity)); } return(blockReferenceIds); }
internal static List <BlockReference> GetAllBlockReferences(this Database currentDatabase) { if (currentDatabase == null) { throw new ArgumentNullException(nameof(currentDatabase)); } Transaction acTrans = currentDatabase.TransactionManager.TopTransaction; List <BlockReference> result = new List <BlockReference>(); foreach (BlockTableRecord btRecord in GetAllBlockDefinitions(currentDatabase)) { var ids = btRecord.GetBlockReferenceIds(true, true); int cnt = ids.Count; for (int i = 0; i < cnt; i++) { result.Add((BlockReference)acTrans.GetObject(ids[i], OpenMode.ForRead, false, false)); } if (btRecord.IsDynamicBlock) { var blockIds = btRecord.GetAnonymousBlockIds(); cnt = blockIds.Count; for (int i = 0; i < cnt; i++) { BlockTableRecord btr2 = (BlockTableRecord)acTrans.GetObject(blockIds[i], OpenMode.ForRead, false, false); ids = btr2.GetBlockReferenceIds(true, true); int cnt2 = ids.Count; for (int j = 0; j < cnt2; j++) { result.Add((BlockReference)acTrans.GetObject(ids[j], OpenMode.ForRead, false, false)); } } } } return(result); }
/// <summary> /// 获取指定块名的块参照 /// </summary> /// <param name="db">数据库对象</param> /// <param name="blockName">块名</param> /// <returns>返回指定块名的块参照</returns> public static List <BlockReference> GetAllBlockReferences(this Database db, string blockName) { List <BlockReference> blocks = new List <BlockReference>(); using (Transaction trans = db.TransactionManager.StartTransaction()) { //打开块表 BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead); //打开指定块名的块表记录 BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[blockName], OpenMode.ForRead); //获取指定块名的块参照集合的Id ObjectIdCollection blockIds = btr.GetBlockReferenceIds(true, true); foreach (ObjectId id in blockIds) // 遍历块参照的Id { //获取块参照 BlockReference block = (BlockReference)trans.GetObject(id, OpenMode.ForRead); blocks.Add(block); // 将块参照添加到返回列表 } trans.Commit(); } return(blocks); //返回块参照列表 }
public static void SetBlockPosition( BlockTableRecord block, Point3d position) { Database documentDatabase = block.Database; using (var transaction = documentDatabase.TransactionManager.StartTransaction()) { var blockTable = (BlockTable)transaction.GetObject( documentDatabase.BlockTableId, OpenMode.ForWrite); var blockReference = (BlockReference)transaction.GetObject( block.GetBlockReferenceIds(true, true)[0], OpenMode.ForWrite); blockReference.Position = position; transaction.Commit(); } }
public static ObjectIdCollection GetAllBlockReferenceByName(string name, Database db) { ObjectIdCollection ids_temp = null, ids = new ObjectIdCollection(); List <string> blkNames = new List <string>(); blkNames.Add(name); List <ObjectId> objectIds = new List <ObjectId>(); Transaction tr = db.TransactionManager.StartTransaction(); try { BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead); BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[name], OpenMode.ForRead); BlockTableRecord btr_model = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead); SelectionFilter sf = new SelectionFilter(CreateFilterListForBlocks(blkNames)); PromptSelectionResult psr = Active.Editor.SelectAll(sf); ObjectId id_model = btr_model.ObjectId; ids_temp = btr.GetBlockReferenceIds(true, true); foreach (ObjectId id in ids_temp) { DBObject obj = (DBObject)tr.GetObject(id, OpenMode.ForRead); // If BlockReference owned with Model Space - add it to collection if (obj.OwnerId == id_model) { ids.Add(id); objectIds.Add(id); } } tr.Commit(); } finally { tr.Dispose(); } return(ids); }
public void selAll() { Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; //开启事务 using (Transaction transaction = db.TransactionManager.StartTransaction()) { //打开块表 BlockTable bt = transaction.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; //打开模型空间块表记录 BlockTableRecord modelspace = transaction.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead) as BlockTableRecord; ObjectIdCollection objidcoll = modelspace.GetBlockReferenceIds(true, true); ed.WriteMessage("\n共有{0}个", objidcoll.Count); foreach (ObjectId item in objidcoll) { Entity ent = (Entity)transaction.GetObject(item, OpenMode.ForRead); ed.WriteMessage("\n名字有:{0}", ent.BlockName); } } }