public void LayerDel() { string layerName = ""; PromptStringOptions propStrOps = new PromptStringOptions("请输入图层名称:\n"); do { var propStrRes = Ed.GetString(propStrOps); if (propStrRes.Status == PromptStatus.OK) { layerName = propStrRes.StringResult; } } while (layerName == ""); try { SymbolUtilityServices.ValidateSymbolName(layerName, false); if (DeleteLayer(Db, layerName)) { Ed.WriteMessage("delete ok"); } else { Ed.WriteMessage("delete not ok"); } } catch (Autodesk.AutoCAD.Runtime.Exception e) { Ed.WriteMessage(e.Message + "\n"); } }
public static ObjectId ContainLayer(String name) { using (DocumentLock docLock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument()) { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; Transaction tr = db.TransactionManager.StartTransaction(); using (tr) { LayerTable lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead); SymbolUtilityServices.ValidateSymbolName(name, false); if (lt.Has(name)) { foreach (ObjectId layerId in lt) { LayerTableRecord layer = tr.GetObject(layerId, OpenMode.ForRead) as LayerTableRecord; if (layer.Name.CompareTo(name) == 0) { return(layerId); } } } } return(ObjectId.Null); } }
public static void CreateGroup(string groupName, ObjectIdCollection ids) { //Document doc =Application.DocumentManager.MdiActiveDocument; Database db = HostApplicationServices.WorkingDatabase; //Editor ed = doc.Editor; Transaction tr = db.TransactionManager.StartTransaction(); using (tr) { // Get the group dictionary from the drawing DBDictionary gd = (DBDictionary)tr.GetObject(db.GroupDictionaryId, OpenMode.ForRead); // Check the group name, to see whether it's // A variable for the group's name string grpName = ""; try { // Validate the provided symbol table name SymbolUtilityServices.ValidateSymbolName(groupName, false); // Only set the block name if it isn't in use if (gd.Contains(groupName)) { //ed.WriteMessage("\nA group with this name already exists."); //throw new System.Exception("A group with this name already exists."); AddIds2Group(groupName, ids, tr); return; } else { grpName = groupName; } } catch { // An exception has been thrown, indicating the // name is invalid //ed.WriteMessage("\nInvalid group name."); } // Create our new group... Group grp = new Group("Test group", true); // Add the new group to the dictionary gd.UpgradeOpen(); ObjectId grpId = gd.SetAt(grpName, grp); tr.AddNewlyCreatedDBObject(grp, true); //grp.InsertAt(0, ids); AddIds2Group(grp, ids); // Commit the transaction tr.Commit(); // Report what we've done //ed.WriteMessage("\nCreated group named \"{0}\" containing entities.",grpName); } }
public static BlockDrawingObject Create(Database target, string blockName) { Transaction trans = target.TransactionManager.TopTransaction; BlockTable bt = (BlockTable)trans.GetObject(target.BlockTableId, OpenMode.ForRead); SymbolUtilityServices.ValidateSymbolName(blockName, false); if (bt.Has(blockName)) { throw new InvalidOperationException("Block name exists"); } BlockTableRecord btr = new BlockTableRecord(); btr.Name = blockName; bt.UpgradeOpen(); ObjectId btrId = bt.Add(btr); trans.AddNewlyCreatedDBObject(btr, true); BlockDrawingObject blockDrawingObject = new BlockDrawingObject(target); blockDrawingObject.BaseObject = btrId; return(blockDrawingObject); }
public void CreateBlock() { using (Transaction tr = AcadFuncs.GetActiveDb().TransactionManager.StartTransaction()) { // Get the block table from the drawing BlockTable blk_tbl = (BlockTable)tr.GetObject( AcadFuncs.GetActiveDb().BlockTableId, OpenMode.ForRead); PromptStringOptions pso = new PromptStringOptions("\nEnter new block name: "); pso.AllowSpaces = true; string blk_name = ""; do { PromptResult pr = AcadFuncs.GetEditor().GetString(pso); if (PromptStatus.OK != pr.Status) { return; } try { SymbolUtilityServices.ValidateSymbolName(pr.StringResult, false); if (blk_tbl.Has(pr.StringResult)) { AcadFuncs.GetEditor().WriteMessage("\nA block with this name already exists."); } else { blk_name = pr.StringResult; } } catch { AcadFuncs.GetEditor().WriteMessage("\nInvalid block name."); } } while ("" == blk_name); BlockTableRecord btr = new BlockTableRecord(); btr.Name = blk_name; blk_tbl.UpgradeOpen(); ObjectId btrId = blk_tbl.Add(btr); tr.AddNewlyCreatedDBObject(btr, true); DBObjectCollection ents = SquareOfLines(5); foreach (Entity ent in ents) { btr.AppendEntity(ent); tr.AddNewlyCreatedDBObject(ent, true); } BlockTableRecord ms = (BlockTableRecord)tr.GetObject(blk_tbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite); BlockReference br = new BlockReference(AcadGeo.Point3d.Origin, btrId); ms.AppendEntity(br); tr.AddNewlyCreatedDBObject(br, true); tr.Commit(); } }
public static string GetValidDbSymbolName([NotNull] this string name) { // string testString = "<>/?\";:*|,='"; var pattern = new Regex("[<>/?\";:*|,=']"); var res = pattern.Replace(name, "."); res = res.Replace('\\', '.'); SymbolUtilityServices.ValidateSymbolName(res, false); return(res); }
/// <summary> /// Returns true, if the given name is a valid SymbolTable name. /// </summary> /// <param name="name">The name to check.</param> /// <returns>True, if the given name is a valid SymbolTable name.</returns> public static bool IsNameValid(string name) { try { SymbolUtilityServices.ValidateSymbolName(name, false); return(true); } catch { return(false); } }
public static bool IsValidDbSymbolName(this string input) { try { SymbolUtilityServices.ValidateSymbolName(input, false); return(true); } catch { return(false); } }
// Переименование блоков с именами вида - DET_АРКВ_14т - DET_АРКВ_14т-10723881-S_01, в АРКВ_14т private void renameApartsFromRevit() { bool hasRenamedBlocks = false; using (var t = _db.TransactionManager.StartTransaction()) { var bt = t.GetObject(_db.BlockTableId, OpenMode.ForRead) as BlockTable; foreach (ObjectId idBtr in bt) { var btr = t.GetObject(idBtr, OpenMode.ForRead) as BlockTableRecord; string oldName = btr.Name; if (!btr.IsLayout) { string newName = string.Empty; if (tryGetRenameName(btr.Name, out newName)) { // Проверка нет ли уже такого имени блока в базе чертежа if (string.IsNullOrWhiteSpace(newName)) { Inspector.AddError(string.Format("{0} - при переименовании этого блока, новое имя имеет недопустимое значение = {1}", btr.Name, newName)); } else { try { SymbolUtilityServices.ValidateSymbolName(newName, false); if (bt.Has(newName)) { Inspector.AddError(string.Format("{0} - переименнованный блок уже есть в чертеже - {1}", btr.Name, newName)); } else { btr.UpgradeOpen(); btr.Name = newName; _ed.WriteMessage("\nБлок {0} переименован в {1}", oldName, newName); hasRenamedBlocks = true; } } catch { Inspector.AddError(string.Format("{0} - переименнованный блок имеет недопустимое имя {1}", btr.Name, newName)); } } } } } t.Commit(); } if (!hasRenamedBlocks) { throw new Exception("Блоки квартир экспортированные из Revit не найдены."); } }
public void layer1() { // 新创建一个图层表记录,并命名为”MyLayer” 图层名称必须合法! 不能为空/特殊字符 LayerTableRecord ltr = new LayerTableRecord() { Name = "lucky" }; // LayerTableRecord ltr = new LayerTableRecord(){ Name = " " }; // 校检 输入的图层名称是否合法 不合法则抛出异常 SymbolUtilityServices.ValidateSymbolName(ltr.Name, false); ltr.addLayerTableR1ecord(); }
public static void IsValidSymbolName(string name, string parameterName) { StringNotEmpty(name, parameterName); try { SymbolUtilityServices.ValidateSymbolName(name, false); } catch { throw new ArgumentException($"'{name}' is not a valid name", parameterName); } }
private Database createLayer(Transaction tr, Database db) { LayerTable lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead); // A variable for the layer name string layName = "XREF"; // Check the layer name, to see whether it's // already in use // Validate the provided symbol table name SymbolUtilityServices.ValidateSymbolName(layName, false ); // Only set the layer name if it isn't in use if (!lt.Has(layName)) { // Create our new layer table record... LayerTableRecord ltr = new LayerTableRecord(); // ... and set its properties ltr.Name = layName; ltr.Color = Color.FromColorIndex(ColorMethod.ByAci, 8); // Add the new layer to the layer table lt.UpgradeOpen(); ObjectId ltId = lt.Add(ltr); tr.AddNewlyCreatedDBObject(ltr, true); // Set the layer to be current for this drawing db.Clayer = ltId; } else { db.Clayer = lt[layName]; } return(db); }
public static ObjectId CreateBlockTableRecord(string name, Point3d origin, IEnumerable <Entity> entities, AnnotativeStates annotative, bool getIfExists = false) { ObjectId btrId = ObjectId.Null; Tools.StartTransaction(() => { Transaction trans = Tools.GetAcadDatabase().TransactionManager.TopTransaction; var bt = Tools.GetAcadDatabase().BlockTableId.GetObjectForRead <BlockTable>(); if (name != "*U") { SymbolUtilityServices.ValidateSymbolName( name, false ); if (bt.Has(name)) { if (!getIfExists) { btrId = bt[name]; } else { throw new ArgumentException(string.Format("A block with this name \"{0}\" already exists.", name)); } } } BlockTableRecord btr = new BlockTableRecord { Name = name, Origin = origin, Annotative = annotative }; bt.UpgradeOpen(); btrId = bt.Add(btr); trans.AddNewlyCreatedDBObject(btr, true); foreach (Entity ent in entities) { btr.AppendEntity(ent); trans.AddNewlyCreatedDBObject(ent, true); } }); return(btrId); }
private bool checkBlock(string blName) { try { SymbolUtilityServices.ValidateSymbolName(blName, false); using (var bt = _db.BlockTableId.Open(OpenMode.ForRead) as BlockTable) { return(!bt.Has(blName)); } } catch (Exception ex) { throw new Exception(string.Format("Недопустимое имя блока - {0}", blName), ex); } }
private void btnRename_Click(object sender, EventArgs e) { if (lvBlocks.SelectedItems.Count > 0) { try { SymbolUtilityServices.ValidateSymbolName(txtBlockName.Text, false); lvBlocks.SelectedItems[0].SubItems[1].Text = txtBlockName.Text; allNames[lvBlocks.SelectedItems[0].Text].NewName = txtBlockName.Text; CheckNames(); } catch (System.Exception ex) { MessageBox.Show("Error: " + ex.ToString(), "XCOM", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
public static bool ValidateName(string name) { Editor editor = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; bool result; try { SymbolUtilityServices.ValidateSymbolName(name, false); result = true; } catch { editor.WriteMessage("Name contains invalid symbols.\n"); result = false; } return(result); }
public void LayerOps() { string layerName = ""; PromptStringOptions propStrOps = new PromptStringOptions("请输入图层名称:\n"); do { var propStrRes = Ed.GetString(propStrOps); if (propStrRes.Status == PromptStatus.OK) { layerName = propStrRes.StringResult; } } while (layerName == ""); try { SymbolUtilityServices.ValidateSymbolName(layerName, false); ObjectId lyId = AddLayer(Db, layerName); if (lyId != null) { PromptIntegerOptions propIntOps = new PromptIntegerOptions("请输入层的颜色索引:\n"); propIntOps.AllowNegative = false; propIntOps.AllowNone = false; propIntOps.AllowZero = true; var propIntRes = Ed.GetInteger(propIntOps); if (propIntRes.Status == PromptStatus.OK) { SetLayerColor(Db, layerName, (short)propIntRes.Value); } SetCurrentLayer(Db, layerName); } } catch (Autodesk.AutoCAD.Runtime.Exception e) { Ed.WriteMessage(e.Message + "\n"); } }
/// <summary> /// 添加图层 /// </summary> /// <param name="db">图形数据库</param> /// <param name="layerName">图层名</param> /// <returns>AddLayerResult</returns> public static AddLayerResult AddLayer(this Database db, string layerName) { //声明AddLayerResult类型的数据,用户返回 AddLayerResult res = new AddLayerResult(); try { SymbolUtilityServices.ValidateSymbolName(layerName, false); } catch (Exception) { res.statuts = AddLayerStatuts.IllegalLayerName; return(res); } using (Transaction trans = db.TransactionManager.StartTransaction()) { //打开层表 LayerTable lt = (LayerTable)trans.GetObject(db.LayerTableId, OpenMode.ForRead); //新建层表记录 if (!lt.Has(layerName)) { LayerTableRecord ltr = new LayerTableRecord(); //判断要创建的图层名是否已经存在,不存在则创建 ltr.Name = layerName; //升级层表打开权限 lt.UpgradeOpen(); lt.Add(ltr); //降低层表打开权限 lt.DowngradeOpen(); trans.AddNewlyCreatedDBObject(ltr, true); trans.Commit(); res.statuts = AddLayerStatuts.AddLayerOK; res.layerName = layerName; } else { res.statuts = AddLayerStatuts.LayerNameExist; } } return(res); }
public static ObjectId CreateLayer(this Database database, string layName, short colorIndex, string description, bool layerIsLocked = false, bool isPlottable = true, bool isHidden = false, LineWeight lineWeight = LineWeight.ByLineWeightDefault) { using (var transAction = database.TransactionManager.StartOpenCloseTransaction()) { // Get the layer table from the drawing using (var layerTable = (LayerTable)transAction.GetObject(database.LayerTableId, OpenMode.ForRead)) { //make sure name is valid according to the SymbolUtilityService SymbolUtilityServices.ValidateSymbolName(layName, false); if (layerTable.Has(layName)) { //we return the object-id of the layer, we have the layer already... (so you could say it has been created) return(layerTable[layName]); } ObjectId id; //create the layer using (var newLayerTableRecord = new LayerTableRecord()) { // Add the new layer to the layer table layerTable.UpgradeOpen(); id = layerTable.Add(newLayerTableRecord); transAction.AddNewlyCreatedDBObject(newLayerTableRecord, true); // ... and set its properties newLayerTableRecord.Name = layName; newLayerTableRecord.Color = Autodesk.AutoCAD.Colors.Color.FromColorIndex(Autodesk.AutoCAD.Colors.ColorMethod.ByAci, colorIndex); newLayerTableRecord.Description = description; newLayerTableRecord.IsLocked = layerIsLocked; newLayerTableRecord.IsHidden = isHidden; newLayerTableRecord.IsPlottable = isPlottable; newLayerTableRecord.LineWeight = lineWeight; transAction.Commit(); } return(id); } } }
public static void AddTextStyle(TextStyle textStyle) { Document document = Active.Document; Database database = document.Database; try { TextStyleTable textStyleTable = GetTextStyleTable(); using (Transaction transaction = database.TransactionManager.StartTransaction()) { SymbolUtilityServices.ValidateSymbolName(textStyle.Name, false); if (!textStyleTable.Has(textStyle.Name)) { TextStyleTableRecord textStyleTableRecord = new TextStyleTableRecord(); textStyleTableRecord.Name = textStyle.Name; if (textStyle.FileName.EndsWith(".shx")) { textStyleTableRecord.FileName = textStyle.FileName; } else { textStyleTableRecord.Font = new FontDescriptor(textStyle.Name, false, false, 0, 0); } textStyleTableRecord.TextSize = textStyle.TextSize; textStyleTableRecord.ObliquingAngle = textStyle.ObliquingAngle; textStyleTable.Add(textStyleTableRecord); transaction.AddNewlyCreatedDBObject(textStyleTableRecord, true); } transaction.Commit(); }//using } catch (Exception ex) { Active.WriteMessage(ex.Message); throw; } }
public void CreateLayer(string layerName) { using (Transaction ts = Db.TransactionManager.StartTransaction()) { LayerTable lt = ts.GetObject(Db.LayerTableId, OpenMode.ForWrite) as LayerTable; try { // Validate the provided symbol table name SymbolUtilityServices.ValidateSymbolName(layerName, false); // Only set the layer name if it isn't in use if (lt.Has(layerName)) { Ed.WriteMessage( "\nA layer with this name already exists." ); } else { LayerTableRecord ltr = new LayerTableRecord(); ltr.Name = layerName; lt.UpgradeOpen(); ObjectId ltId = lt.Add(ltr); ts.AddNewlyCreatedDBObject(ltr, true); ts.Commit(); } } catch { // An exception has been thrown, indicating the // name is invalid Ed.WriteMessage( "\nInvalid layer name." ); } } }
public static void CreateBlock() { string strBlockName = "Присоска квадратная"; using (Document.LockDocument()) { using (var trans = TransactionManager.StartTransaction()) { BlockTable blockTable = trans.GetObject(Database.BlockTableId, OpenMode.ForRead, false) as BlockTable; //BlockTableRecord blockTableRecord = trans.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForWrite, false) as BlockTableRecord; try { // проверка на корректность символов в имени блока SymbolUtilityServices.ValidateSymbolName(strBlockName, false); } catch { WriteMessage("nInvalid block name."); return; } BlockTableRecord btrRecord; ObjectId btrId; if (!blockTable.Has(strBlockName)) { // создаем ОПРЕДЕЛЕНИЕ блока // создаем примитивы, которые будет содержать блок Polyline acPoly = new Polyline(); acPoly.AddVertexAt(0, new Point2d(0, 0), 0, 0, 0); acPoly.AddVertexAt(1, new Point2d(100, 0), 0, 0, 0); acPoly.AddVertexAt(2, new Point2d(100, 100), 0, 0, 0); acPoly.AddVertexAt(3, new Point2d(0, 100), 0, 0, 0); acPoly.Closed = true; acPoly.ColorIndex = 3; // создаем определение аттрибута AttributeDefinition adAttr = new AttributeDefinition(); /* adAttr.Position = new Point3d(0, 0, 0); * adAttr.Tag = "ATTRDEF"; * adAttr.TextString = "Присоска";*/ // создаем новое определение блока btrRecord = new BlockTableRecord(); btrRecord.Name = strBlockName; btrRecord.Comments = "Присоска для закрепления детали на станке"; blockTable.UpgradeOpen(); // добавляем его в таблицу блоков btrId = blockTable.Add(btrRecord); trans.AddNewlyCreatedDBObject(btrRecord, true); // добавляем в определение блока примитивы btrRecord.AppendEntity(acPoly); trans.AddNewlyCreatedDBObject(acPoly, true); // и аттрибут // btrRecord.AppendEntity(adAttr); // trans.AddNewlyCreatedDBObject(adAttr, true); } else { btrId = blockTable[strBlockName]; btrRecord = (BlockTableRecord)trans.GetObject(blockTable[strBlockName], OpenMode.ForWrite); } // теперь создадим экземпляр блока на чертеже // получаем пространство модели BlockTableRecord btrModelSpace = (BlockTableRecord)trans.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForWrite); // создаем новый экземпляр блока на основе его определения BlockReference brRefBlock = new BlockReference(new Point3d(2000, 1500, 0), btrId); // добавляем экземпляр блока в базу данных пространства модели btrModelSpace.AppendEntity(brRefBlock); trans.AddNewlyCreatedDBObject(brRefBlock, true); // задаем значение аттрибуета // AttributeReference arAttr = new AttributeReference(); // arAttr.SetAttributeFromBlock(adAttr, brRefBlock.BlockTransform); // arAttr.TextString = "Атрибут!"; // brRefBlock.AttributeCollection.AppendAttribute(arAttr); // trans.AddNewlyCreatedDBObject(arAttr, true); // закрываем транзакцию trans.Commit(); } } }
/// <summary> /// http://through-the-interface.typepad.com/through_the_interface/2010/01/creating-an-autocad-layer-using-net.html /// </summary> public static void CreateHiddenLayer(string layerName, bool isHidden = false, bool isFrozen = false) { short _colorIndex = 0; Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; Transaction tr = db.TransactionManager.StartTransaction(); using (tr) { LayerTable lt = (LayerTable)tr.GetObject( db.LayerTableId, OpenMode.ForRead ); try { SymbolUtilityServices.ValidateSymbolName( layerName, false ); if (lt.Has(layerName)) { ed.WriteMessage( "\nA layer with this name already exists." ); return; } } catch { ed.WriteMessage( "\nInvalid layer name." ); return; } LayerTableRecord ltr = new LayerTableRecord(); ltr.Name = layerName; ltr.Color = Color.FromColorIndex(ColorMethod.ByAci, _colorIndex); ltr.IsFrozen = isFrozen; ltr.IsHidden = isHidden; lt.UpgradeOpen(); ObjectId ltId = lt.Add(ltr); tr.AddNewlyCreatedDBObject(ltr, true); tr.Commit(); ed.WriteMessage( "\nCreated layer named \"{0}\" with " + "a color index of {1}.", layerName, _colorIndex++ ); } }
public static ObjectId CreateBlockTableRecordEx(Point3d origin, string name, List <Entity> entities, AnnotativeStates aState, Transaction trans, bool commit, bool rewriteBlock = false) { var bt = (BlockTable)trans.GetObject(Tools.GetAcadDatabase().BlockTableId, OpenMode.ForRead); // Validate the provided symbol table name if (name != "*U") { SymbolUtilityServices.ValidateSymbolName( name, false ); // Only set the block name if it isn't in use if (bt.Has(name)) { //throw new ArgumentException(string.Format("A block with this name \"{0}\" already exists.", name)); if (!rewriteBlock) { return(bt[name]); } else { throw new ArgumentException(string.Format("A block with this name \"{0}\" already exists.", name)); } } } // Create our new block table record... BlockTableRecord btr = new BlockTableRecord(); // ... and set its properties btr.Name = name; btr.Origin = origin; btr.Annotative = aState; // Add the new block to the block table bt.UpgradeOpen(); ObjectId btrId = bt.Add(btr); trans.AddNewlyCreatedDBObject(btr, true); foreach (Entity ent in entities) { btr.AppendEntity(ent); trans.AddNewlyCreatedDBObject(ent, true); } // Commit the transaction if (commit) { trans.Commit(); } return(btr.Id); }
public void CreateBlock(string oldBlockName, DBObjectCollection objectCollection, Point3d downLeftP) { Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; Transaction tr = db.TransactionManager.StartTransaction(); using (tr) { // Get the block table from the drawing BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead); string monthT = ""; if (DateTime.Now.Month < 10) { monthT = "0" + DateTime.Now.Month; } else { monthT = DateTime.Now.Month.ToString(); } string dayT = ""; if (DateTime.Now.Day < 10) { dayT = "0" + DateTime.Now.Day; } else { dayT = DateTime.Now.Day.ToString(); } string blockToTestName = oldBlockName.Split('M')[0] + "M" + monthT + dayT + "V"; string blkName = ""; //string blkName = oldBlockName + "M" + DateTime.Now.Month + "-" + DateTime.Now.Day; //调试性能,以后再改进 try { // Validate the provided symbol table name SymbolUtilityServices.ValidateSymbolName(blockToTestName, false); // Only set the block name if it isn't in use if (bt.Has(blockToTestName)) { ed.WriteMessage("\nA block with this name already exists."); } else { blkName = blockToTestName; } } catch { // An exception has been thrown, indicating the name is invalid ed.WriteMessage("\nInvalid block name."); } // Create our new block table record... BlockTableRecord btr = new BlockTableRecord(); // ... and set its properties btr.Name = blkName; // Add the new block to the block table bt.UpgradeOpen(); ObjectId btrId = bt.Add(btr); tr.AddNewlyCreatedDBObject(btr, true); // 在块定义中添加实体 DBObjectCollection ents = objectCollection; foreach (Entity ent in ents) { btr.AppendEntity(ent); tr.AddNewlyCreatedDBObject(ent, true); } // Add a block reference to the model space //添加块参照 BlockTableRecord ms = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); BlockReference br = new BlockReference(new Point3d(Point3d.Origin.X - downLeftP.X, Point3d.Origin.Y - downLeftP.Y, Point3d.Origin.Z - downLeftP.Z), btrId); ms.AppendEntity(br); tr.AddNewlyCreatedDBObject(br, true); // Commit the transaction tr.Commit(); // Report what we've done ed.WriteMessage("\nCreated block named \"{0}\" containing {1} entities.", blkName, ents.Count); } }
public void CreateBlock() { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; Transaction tr = db.TransactionManager.StartTransaction(); using (tr) { // Get the block table from the drawing BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead); // Check the block name, to see whether it's // already in use PromptStringOptions pso = new PromptStringOptions("\nEnter new block name: "); pso.AllowSpaces = true; // A variable for the block's name string blkName = ""; do { PromptResult pr = ed.GetString(pso); // Just return if the user cancelled // (will abort the transaction as we drop out of the using // statement's scope) if (pr.Status != PromptStatus.OK) { return; } try { // Validate the provided symbol table name SymbolUtilityServices.ValidateSymbolName(pr.StringResult, false); // Only set the block name if it isn't in use if (bt.Has(pr.StringResult)) { ed.WriteMessage("\nA block with this name already exists."); } else { blkName = pr.StringResult; } } catch { // An exception has been thrown, indicating the // name is invalid ed.WriteMessage("\nInvalid block name."); } } while (blkName == ""); // Create our new block table record... BlockTableRecord btr = new BlockTableRecord(); // ... and set its properties btr.Name = blkName; //input insert point PromptPointOptions ppo = new PromptPointOptions("\nSelect point to insert block"); PromptPointResult ppr = ed.GetPoint(ppo); Point3d pt = ppr.Value; // Add the new block to the block table bt.UpgradeOpen(); ObjectId btrId = bt.Add(btr); tr.AddNewlyCreatedDBObject(btr, true); // Add some lines to the block to form a square // (the entities belong directly to the block) Circle circle = new Circle(); circle.Center = pt; circle.Radius = 20; btr.AppendEntity(circle); tr.AddNewlyCreatedDBObject(circle, true); // Add a block reference to the model space BlockTableRecord ms = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); BlockReference br = new BlockReference(Point3d.Origin, btrId); ms.AppendEntity(br); tr.AddNewlyCreatedDBObject(br, true); // Commit the transaction tr.Commit(); // Report what we've done ed.WriteMessage("\nCreated block named \"{0}\" .", blkName); } }