static public void GetCenter() { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; PromptEntityOptions peopt = new PromptEntityOptions("\nSelect curve to get center : "); peopt.SetRejectMessage("\nSelect only a curve."); peopt.AddAllowedClass(typeof(Circle), false); peopt.AddAllowedClass(typeof(Arc), false); peopt.AllowNone = false; PromptEntityResult peres = ed.GetEntity(peopt); using (Transaction tx = db.TransactionManager.StartTransaction()) { BlockTableRecord btrec = tx.GetObject(peres.ObjectId, OpenMode.ForRead) as BlockTableRecord; Entity en = tx.GetObject(btrec.ObjectId, OpenMode.ForRead) as Entity; if (en is Arc) { } if (en is Circle) { } } }
private static PromptEntityResult PromptSourceEntity(Document doc, ref bool deleteSource) { // Выберите объект-исходник (текст, выноска, таблица или размер): var peo = new PromptEntityOptions($"\n{Language.GetItem(LangItem, "msg1")}"); peo.SetMessageAndKeywords($"\n{Language.GetItem(LangItem, "msg2")}", "Delete"); peo.AppendKeywordsToMessage = true; peo.SetRejectMessage($"\n{Language.GetItem(LangItem, "msg3")}"); peo.AddAllowedClass(typeof(DBText), false); peo.AddAllowedClass(typeof(MText), false); peo.AddAllowedClass(typeof(MLeader), false); peo.AddAllowedClass(typeof(Table), false); peo.AddAllowedClass(typeof(Dimension), false); peo.AllowNone = true; var per = doc.Editor.GetEntity(peo); if (per.Status == PromptStatus.Keyword) { // Удалять объект-исходник (для таблиц - содержимое ячейки)? deleteSource = MessageBox.ShowYesNo(Language.GetItem(LangItem, "msg4"), MessageBoxIcon.Question); // Сохраняем текущее значение как значение по умолчанию ModPlus.Helpers.XDataHelpers.SetStringXData("mpTxtCopyPaste", deleteSource.ToString()); return(PromptSourceEntity(doc, ref deleteSource)); } if (per.Status == PromptStatus.OK) { return(per); } throw new OperationCanceledException(); }
selectEntity(string message, string reject, out bool escape) { escape = true; ObjectId idEnt = ObjectId.Null; BaseObjs.acadActivate(); PromptEntityOptions PEOS = new PromptEntityOptions(message); PEOS.SetRejectMessage(reject); PEOS.AddAllowedClass(typeof(Line), true); PEOS.AddAllowedClass(typeof(Arc), true); PEOS.AddAllowedClass(typeof(Polyline), true); PEOS.AllowNone = false; PromptEntityResult PER = BaseObjs._editor.GetEntity(PEOS); if (PER.Status == PromptStatus.OK) { try { using (Transaction tr = BaseObjs.startTransactionDb()) { Entity ENT = (Entity)tr.GetObject(PER.ObjectId, OpenMode.ForRead); idEnt = ENT.ObjectId; escape = false; tr.Commit(); } } catch (System.Exception ex) { BaseObjs.writeDebug(ex.Message + " Select.cs: line: 635"); } } return(idEnt); }
private static bool GetNumberOfFloors(Editor ed, ref int numberOfFloors) { // Select text (or type number of floors) PromptEntityOptions entityOptions = new PromptEntityOptions("\nSelect Text (or Enter to skip): "); entityOptions.SetRejectMessage("Not Text or MText"); entityOptions.AddAllowedClass(typeof(DBText), true); entityOptions.AddAllowedClass(typeof(MText), true); entityOptions.AllowNone = true; PromptEntityResult entityResult = ed.GetEntity(entityOptions); if (entityResult.Status == PromptStatus.None) { PromptIntegerOptions integerOptions = new PromptIntegerOptions("\nEnter number of floors:"); integerOptions.DefaultValue = 1; PromptIntegerResult integerResult = ed.GetInteger(integerOptions); if (integerResult.Status != PromptStatus.OK) { return(false); } numberOfFloors = integerResult.Value; } else if (entityResult.Status != PromptStatus.OK) { return(false); } else { using (DBObject obj = entityResult.ObjectId.Open(OpenMode.ForRead)) { DBText t1 = obj as DBText; MText t2 = obj as MText; string s = null; if (t1 != null) { s = t1.TextString; } else if (t2 != null) { s = t2.Text; } else { throw new NotSupportedException("Entity not supported!"); } if (!string.IsNullOrEmpty(s)) { numberOfFloors = FloorCount.GetCount(s); } ed.WriteMessage($"\nNumber of floors: {numberOfFloors}"); } } return(true); }
private static PromptEntityOptions GetDestinationEntityOptions() { // Выберите объект (текст, выноска или таблица) для замены содержимого: var peo = new PromptEntityOptions($"\n{Language.GetItem(LangItem, "msg5")}"); peo.SetRejectMessage($"\n{Language.GetItem(LangItem, "msg3")}"); peo.AddAllowedClass(typeof(DBText), false); peo.AddAllowedClass(typeof(MText), false); peo.AddAllowedClass(typeof(MLeader), false); peo.AddAllowedClass(typeof(Table), false); peo.AllowNone = false; return(peo); }
selectEntity(System.Type classType, string message, string reject, out Point3d pnt3dPicked, out PromptStatus ps) { Entity ent = null; BaseObjs.acadActivate(); PromptEntityOptions peos = new PromptEntityOptions(message); peos.SetRejectMessage(reject); peos.AddAllowedClass(classType, true); peos.AllowNone = true; PromptEntityResult per = BaseObjs._editor.GetEntity(peos); pnt3dPicked = per.PickedPoint; ps = per.Status; switch (ps) { case PromptStatus.OK: try { using (Transaction tr = BaseObjs.startTransactionDb()) { ent = (Entity)tr.GetObject(per.ObjectId, OpenMode.ForRead); tr.Commit(); } } catch (System.Exception ex) { BaseObjs.writeDebug(ex.Message + " Select.cs: line: 599"); } break; } return(ent); }
public SampleLine GetSampleLine() { PromptEntityOptions peo = new PromptEntityOptions("\nSelect the SampleLine"); peo.SetRejectMessage("\nOnly SampleLine"); peo.AddAllowedClass(typeof(SampleLine), true); PromptEntityResult res = Ed.GetEntity(peo); if (res.Status != PromptStatus.OK) { return(null); } using (Transaction ts = Dwg.TransactionManager.StartTransaction()) { try { SampleLine smpLine = ts.GetObject(res.ObjectId, OpenMode.ForRead) as SampleLine; return(smpLine); } catch (System.Exception) { throw; } } }
public void SolMassProp() { Document doc = Application.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; // The Database object contains all of the graphical and most of the nongraphical AutoCAD objects Database db = doc.Database; // Ask user to select a solid (which is an Entity) // To prompt, we use the PromptXXXOptions class, where XXX is the value type we want to prompt // (e.g. Angle, String, Distance, Entity ...) PromptEntityOptions peo = new PromptEntityOptions("Select a 3D solid."); // Set the message in case of an error (this MUST come before definind the allowed class) peo.SetRejectMessage("\nA 3D solid must be selected."); // Set the class of the entity we want to select peo.AddAllowedClass(typeof(Solid3d), true); // After creating the prompt, we actually show it using the GetXXX function of the Editor PromptEntityResult per = ed.GetEntity(peo); if (per.Status != PromptStatus.OK) { return; } ed.WriteMessage("Ok, cool, thanks."); }
private Polyline GetSlopeLine(Editor ed, out bool cont) { var op = new PromptEntityOptions("\n选择一条边坡线以进行信息读写"); op.SetRejectMessage($"\n选择的多段线必须包含{SlopeData.AppName}的外部扩展数据"); op.AddAllowedClass(typeof(Polyline), exactMatch: true); var res = ed.GetEntity(op); cont = true; if (res.Status == PromptStatus.OK) { var pl = res.ObjectId.GetObject(OpenMode.ForRead) as Polyline; if (pl != null) { if (SlopeLine.IsSlopeLineLayer(pl.Layer, left: null)) { cont = true; return(pl); } } } else if (res.Status == PromptStatus.Cancel) { cont = false; } return(null); }
selectPointEntity(string cmd, int osMode) { object mode = SnapMode.getOSnap(); SnapMode.setOSnap(osMode); ObjectId idPnt = ObjectId.Null; Database db = BaseObjs._db; Editor ed = BaseObjs._editor; PromptEntityOptions peo = new PromptEntityOptions(string.Format("\nSelect {0} Point:", cmd)); peo.AllowNone = false; peo.SetRejectMessage("\nSelected Entity is not a Cogo Point."); peo.AddAllowedClass(typeof(CogoPoint), true); try { idPnt = ed.GetEntity(peo).ObjectId; } catch (System.Exception ex) { BaseObjs.writeDebug(string.Format("{0} Pnt.cs: line: 118", ex.Message)); } finally { SnapMode.setOSnap((int)mode); } return(idPnt); }
public static BlockTableRecord GetBlockTableRecord(Document acDoc, string PromptMessage, string PromptRejectMessage) { Database acCurDb = acDoc.Database; Editor acDocEd = acDoc.Editor; using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { PromptEntityOptions pEntOpt = new PromptEntityOptions("\n" + PromptMessage); pEntOpt.SetRejectMessage("\n" + PromptRejectMessage); pEntOpt.AddAllowedClass(typeof(BlockReference), true); PromptEntityResult pEntRes = acDocEd.GetEntity(pEntOpt); if (pEntRes.Status == PromptStatus.OK) { Entity acEnt = (Entity)acTrans.GetObject(pEntRes.ObjectId, OpenMode.ForRead); BlockReference acBlkRef = (BlockReference)acEnt; BlockTableRecord acBlkTblRec; if (!acBlkRef.IsDynamicBlock) { acBlkTblRec = (BlockTableRecord)acTrans.GetObject(acBlkRef.BlockTableRecord, OpenMode.ForRead); } else { acBlkTblRec = (BlockTableRecord)acTrans.GetObject(acBlkRef.DynamicBlockTableRecord, OpenMode.ForRead); } Application.ShowAlertDialog("Title block was chosen: " + acBlkTblRec.Name); return(acBlkTblRec); } else { Application.ShowAlertDialog("Bạn đã thoát lệnh!"); return(null); } } }
public static void test25() { Document doc = Application.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; PromptEntityOptions opts = new PromptEntityOptions("\n请选择一个块:"); opts.SetRejectMessage("只能选择块参照"); opts.AddAllowedClass(typeof(BlockReference), false); PromptEntityResult res = ed.GetEntity(opts); if (res.Status != PromptStatus.OK) { return; } Database db = doc.Database; using (Transaction tr = db.TransactionManager.StartTransaction()) { BlockReference bref = tr.GetObject(res.ObjectId, OpenMode.ForRead) as BlockReference; BlockTableRecord btr = tr.GetObject(bref.BlockTableRecord, OpenMode.ForRead) as BlockTableRecord; foreach (ObjectId id in btr) { Entity ent = tr.GetObject(id, OpenMode.ForRead) as Entity; ed.WriteMessage($"\n{ent.GetType().Name}"); //Circle cir = tr.GetObject(id, OpenMode.ForRead) as Circle; //if (cir != null) //{ // Point3d pt = cir.Center.TransformBy(bref.BlockTransform); // ed.DrawPoint(pt.Convert2d(new Plane()), 1, 1, 8); //} } } }
/// <summary> 从 AutoCAD 界面中选择横断面轴线 </summary> public static SubgradeSection GetSection(DocumentModifier docMdf) { SubgradeSection sec = null; var op = new PromptEntityOptions("\n选择要提取的横断面轴线"); op.AddAllowedClass(typeof(Line), true); var res = docMdf.acEditor.GetEntity(op); if (res.Status == PromptStatus.OK) { var line = res.ObjectId.GetObject(OpenMode.ForRead) as Line; if (line != null && line.Layer == Options_LayerNames.LayerName_CenterAxis) { var si = SectionInfo.FromCenterLine(line); if (si != null && si.FullyCalculated) { sec = new SubgradeSection(docMdf, line, si); } else { MessageBox.Show($"选择的道路中心线对象所对应的横断面未进行构造," + $"\r\n请先调用“{SectionsConstructor.CommandName}”命令,以构造整个项目的横断面系统。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } return(sec); }
public Alignment GetAlignment() { PromptEntityOptions opt = new PromptEntityOptions("\nSelect the Alignment:"); opt.SetRejectMessage("\nOnly alignment"); opt.AddAllowedClass(typeof(Alignment), true); PromptEntityResult res = Ed.GetEntity(opt); if (res.Status != PromptStatus.OK) { return(null); } ; using (Transaction ts = Dwg.TransactionManager.StartTransaction()) { try { Alignment al = ts.GetObject(res.ObjectId, OpenMode.ForRead) as Alignment; return(al); } catch (System.Exception) { throw; } } }
/// <summary> 从界面中选择一个块参照 </summary> public static BlockReference PickBlockReference() { // 创建一个 TypedValue 数组,用于定义过滤条件 var filterTypes = new TypedValue[] { new TypedValue((int)DxfCode.Start, "INSERT"), }; // Create our options object var op = new PromptEntityOptions("\n请选择一个块参照对象"); op.SetRejectMessage("请选择一个块参照对象"); op.AddAllowedClass(typeof(BlockReference), true); //获取当前文档编辑器 Editor acDocEd = Application.DocumentManager.MdiActiveDocument.Editor; // 请求在图形区域选择对象 var res = acDocEd.GetEntity(op); // 如果提示状态OK,表示对象已选 if (res.Status == PromptStatus.OK) { var obj = res.ObjectId.GetObject(OpenMode.ForRead) as BlockReference; if (obj != null) { return(obj); } } return(null); }
TestImageAngle() { Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; PromptEntityOptions prOpts = new PromptEntityOptions("\nSelect an Image"); prOpts.SetRejectMessage("\nSelected entity must by of type RasterImage"); prOpts.AddAllowedClass(typeof(RasterImage), false); PromptEntityResult prRes = ed.GetEntity(prOpts); if (prRes.Status == PromptStatus.OK) { Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = prRes.ObjectId.Database.TransactionManager; using (Autodesk.AutoCAD.DatabaseServices.Transaction tr = tm.StartTransaction()) { RasterImage imgObj = (RasterImage)tr.GetObject(prRes.ObjectId, OpenMode.ForRead); CoordinateSystem3d entEcs = imgObj.Orientation; Vector3d arbXAxis = Utils.Db.GetEcsXAxis(entEcs.Zaxis); // get AutoCAD's arbitrary X-Axis double rotAngle1 = arbXAxis.GetAngleTo(entEcs.Xaxis, entEcs.Zaxis); ed.WriteMessage(string.Format("\nECS rotation angle: {0}", Autodesk.AutoCAD.Runtime.Converter.AngleToString(rotAngle1, AngularUnitFormat.Current, -1))); Plane ucsPlane = Utils.Db.GetUcsPlane(prRes.ObjectId.Database); double rotAngle2 = entEcs.Xaxis.AngleOnPlane(ucsPlane); ed.WriteMessage(string.Format("\nRotation angle relative to UCS: {0}", Autodesk.AutoCAD.Runtime.Converter.AngleToString(rotAngle2, AngularUnitFormat.Current, -1))); tr.Commit(); } } }
public Profile GetProfile() { PromptEntityOptions peo = new PromptEntityOptions("\nSelect the profile view"); peo.SetRejectMessage("\nOnly profile view"); peo.AddAllowedClass(typeof(Profile), true); PromptEntityResult res = Ed.GetEntity(peo); if (res.Status != PromptStatus.OK) { return(null); } using (Transaction ts = Dwg.TransactionManager.StartTransaction()) { try { Profile prf = ts.GetObject(res.ObjectId, OpenMode.ForRead) as Profile; return(prf); } catch (System.Exception) { throw; } } }
static public void GetObjectMng() { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; PromptEntityOptions peo = new PromptEntityOptions("\nSelect custom object: "); peo.SetRejectMessage("\nInvalid selection..."); peo.AddAllowedClass(typeof(asdkCustomCircleMgd), true); PromptEntityResult per = ed.GetEntity(peo); if (per.Status != PromptStatus.OK) { return; } using (Transaction Tx = db.TransactionManager.StartTransaction()) { asdkCustomCircleMgd entity = Tx.GetObject(per.ObjectId, OpenMode.ForWrite) as asdkCustomCircleMgd; entity.ColorIndex = 1; Tx.Commit(); } }
private string _getTextFromEntity <T>(string msg, string rmsg) where T : DBObject { PromptEntityOptions entOpt = new PromptEntityOptions(msg); entOpt.SetRejectMessage(rmsg); entOpt.AllowNone = false; entOpt.AddAllowedClass(typeof(T), true); PromptEntityResult entRes = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetEntity(entOpt); if (entRes.Status != PromptStatus.OK) { return(null); } var id = entRes.ObjectId; if (id.IsNull) { return(null); } using (Transaction trans = Tools.StartTransaction()) { System.Reflection.MethodInfo mi = typeof(T).GetMethod("TextString"); Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage(mi.ReturnParameter.Name); object obj = trans.GetObject(id, OpenMode.ForRead); string data = mi.Invoke((DBObject)obj, null) as string; return(data); } }
private string _getDbTextString(string msg, string rmsg) { PromptEntityOptions entOpt = new PromptEntityOptions(msg); entOpt.SetRejectMessage(rmsg); entOpt.AllowNone = false; entOpt.AddAllowedClass(typeof(DBText), true); PromptEntityResult entRes = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetEntity(entOpt); if (entRes.Status != PromptStatus.OK) { return(null); } var id = entRes.ObjectId; if (id.IsNull) { return(null); } using (Transaction trans = Tools.StartTransaction()) { string data = ((DBText)trans.GetObject(id, OpenMode.ForRead)).TextString; return(data); } }
private void GetPoint(object s, EventArgs e) { _ = ParentProcessUtilities.GetParentProcess(); var doc = AcApp.DocumentManager.MdiActiveDocument; _ = doc.Editor; _ = new PromptSelectionOptions { AllowDuplicates = false }; PromptEntityOptions peo = new PromptEntityOptions("Select a point."); peo.AddAllowedClass(typeof(CogoPoint), true); peo.AddAllowedClass(typeof(Autodesk.AutoCAD.Geometry.Point3d), true); }
public void TestWEdding() { var doc = Application.DocumentManager.MdiActiveDocument; var db = doc.Database; var ed = doc.Editor; var selOpt = new PromptEntityOptions("\nВыбери полилинию для прополки"); selOpt.SetRejectMessage("\nТолько полилинию"); selOpt.AddAllowedClass(typeof(Polyline), true); var selRes = ed.GetEntity(selOpt); if (selRes.Status != PromptStatus.OK) { return; } using (var t = db.TransactionManager.StartTransaction()) { var pl = selRes.ObjectId.GetObject(OpenMode.ForWrite) as Polyline; pl.TestDrawVertexNumbers(Color.FromColor(System.Drawing.Color.Green)); pl.Wedding(new Autodesk.AutoCAD.Geometry.Tolerance(0.02, 0.1)); pl.TestDrawVertexNumbers(Color.FromColor(System.Drawing.Color.Red)); t.Commit(); } }
private void blockDwgBtn_Click(object sender, EventArgs e) { Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; Database db = doc.Database; this.Hide(); PromptEntityOptions prmtOpt = new PromptEntityOptions("\n\nSelect block"); prmtOpt.SetRejectMessage("\n\nCan only select a block definition"); prmtOpt.AddAllowedClass(typeof(BlockReference), false); PromptEntityResult result = ed.GetEntity(prmtOpt); if (result.Status == PromptStatus.OK) { using (Transaction tr = db.TransactionManager.StartTransaction()) { BlockReference blkReference = tr.GetObject(result.ObjectId, OpenMode.ForRead) as BlockReference; BlockTableRecord blockRecord = null; if (blkReference.IsDynamicBlock) { blockRecord = tr.GetObject(blkReference.DynamicBlockTableRecord, OpenMode.ForRead) as BlockTableRecord; } else { blockRecord = tr.GetObject(blkReference.BlockTableRecord, OpenMode.ForRead) as BlockTableRecord; } blockName = blockRecord.Name; blockDwgBtn.Text = blockRecord.Name; this.Show(); this.Focus(); plotButton.Enabled = true; } } }
public static List <Block> SelectBlock(string message) { PromptEntityOptions options = new PromptEntityOptions(message); options.SetRejectMessage("\nThe selected object is not a Block.\n"); options.AddAllowedClass(typeof(BlockReference), false); PromptEntityResult peo = Active.Editor.GetEntity(options); List <Block> result = null; using (Transaction tr = Active.Database.TransactionManager.StartTransaction()) { switch (peo.Status) { case PromptStatus.OK: BlockReference br = tr.GetObject(peo.ObjectId, OpenMode.ForRead) as BlockReference; result = Block.GetAttributesInBlock(tr, br); break; case PromptStatus.Cancel: Active.Editor.WriteMessage("Select canceled"); return(null); } tr.Commit(); return(result); } }
/// <summary> /// 사용자가 선택한 객체를 가져오는 메소드 입니다. /// </summary> /// <param name="message">선택 전, 프롬프트에 표시할 메시지</param> /// <param name="Filter">선택이 가능하게 할 객체의 종류(클래스)</param> /// <returns>선택한 객체의 ObjectId를 리턴하며, ESC 등의 취소를 받았을 경우, ObjectId.Null 값을 리턴합니다.</returns> public static ObjectId GetEntity(string message = "객체 선택", params Type[] Filter) { ActivateApplication(); Document doc = AcadApp.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; PromptEntityOptions peo = new PromptEntityOptions("\n" + message); peo.SetRejectMessage("\n" + sRejectMsg); foreach (Type tType in Filter) { peo.AddAllowedClass(tType, true); } PromptEntityResult per = ed.GetEntity(peo); if (per.Status != PromptStatus.OK) { return(ObjectId.Null); } return(per.ObjectId); }
public static void ExplodeToOwnerSpace() { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; PromptEntityOptions options = new PromptEntityOptions("\nSelect block reference"); options.SetRejectMessage("\nSelect only block reference"); options.AddAllowedClass(typeof(BlockReference), false); PromptEntityResult acSSPrompt = ed.GetEntity(options); using (Transaction tx = db.TransactionManager.StartTransaction()) { BlockReference blockRef = tx.GetObject(acSSPrompt.ObjectId, OpenMode.ForRead) as BlockReference; //add event ids.Clear(); db.ObjectAppended += new ObjectEventHandler(db_ObjectAppended); blockRef.ExplodeToOwnerSpace(); //remove event db.ObjectAppended -= new ObjectEventHandler(db_ObjectAppended); foreach (ObjectId id in ids) { //get each entity.... ed.WriteMessage("\n" + id.ToString()); } tx.Commit(); } }
public void FilterBlocks() { Document doc = Active.Document; Database db = doc.Database; Editor ed = doc.Editor; PromptEntityOptions opts = new PromptEntityOptions("\nSelect a block: "); opts.SetRejectMessage("Only a block."); opts.AddAllowedClass(typeof(BlockReference), true); PromptEntityResult per = ed.GetEntity(opts); if (per.Status != PromptStatus.OK) { return; } using (Transaction tr = db.TransactionManager.StartTransaction()) { BlockReference br = (BlockReference)tr.GetObject(per.ObjectId, OpenMode.ForRead); blockName = GetEffectiveName(br); TypedValue[] filterList = new TypedValue[3] { new TypedValue(0, "INSERT"), new TypedValue(2, "`*U*," + blockName), new TypedValue(8, br.Layer) }; ed.SelectionAdded += onSelectionAdded; PromptSelectionResult psr = ed.SelectAll(new SelectionFilter(filterList)); ed.SelectionAdded -= onSelectionAdded; ed.SetImpliedSelection(psr.Value); ed.WriteMessage("\nNumber of selected objects: {0}", psr.Value.Count); tr.Commit(); } }
public Corridor OdabraniCorridor() { using (Transaction tr = db.TransactionManager.StartTransaction()) { try { PromptEntityOptions prEntOpts = new PromptEntityOptions("\nOdaberite corridor plovnog puta: "); prEntOpts.AllowNone = true; prEntOpts.SetRejectMessage("\nOdabrani objekat mora biti corridor"); prEntOpts.AddAllowedClass(typeof(Corridor), true); PromptEntityResult prEntRes = ed.GetEntity(prEntOpts); if (prEntRes.Status != PromptStatus.OK) { return(null); } else { Corridor cor = tr.GetObject(prEntRes.ObjectId, OpenMode.ForRead) as Corridor; ed.WriteMessage("\n Odabrali ste corridor imena: " + cor.Name); tr.Commit(); return(cor); } } catch (System.Exception ex) { ed.WriteMessage("Error encountered: " + ex.Message); tr.Abort(); return(null); } } }
public void DimRadiusArrowStyle() { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; Arc arc = new Arc(); //初始化圆弧 using (Transaction trans = db.TransactionManager.StartTransaction()) //开始事务处理 { //1.选择圆弧 PromptEntityOptions arcOpt = new PromptEntityOptions("\n选择圆弧"); arcOpt.SetRejectMessage("请选择圆弧对象!"); arcOpt.AddAllowedClass(typeof(Arc), false); PromptEntityResult arcRes = ed.GetEntity(arcOpt); if (arcRes.Status != PromptStatus.OK) { return; } arc = arcRes.ObjectId.GetObject(OpenMode.ForRead) as Arc; CircularArc3d arc3d = new CircularArc3d(arc.StartPoint, arc.Center.PolarPoint((arc.StartAngle + arc.EndAngle) / 2, arc.Radius), arc.EndPoint); //2.设置标注比例 PromptDoubleOptions scaleOpt = new PromptDoubleOptions($"\n设置标注比例<{scale}>"); scaleOpt.AllowNegative = false; scaleOpt.AllowZero = false; scaleOpt.AllowNone = true; PromptDoubleResult scaleRes = ed.GetDouble(scaleOpt); if (scaleRes.Status == PromptStatus.OK) { scale = scaleRes.Value; } //3.绘制圆弧半径箭头标注 db.ArrowRadiusDim(arc3d, scale); trans.Commit();//执行事务处理 } }
static public void Test() { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; Transaction tr = db.TransactionManager.StartTransaction(); using (tr) { try { // Prompt for selection of a solid to be traversed PromptEntityOptions prEntOpt = new PromptEntityOptions("\nSelect a 3D solid:"); prEntOpt.SetRejectMessage("\nMust be a 3D solid."); prEntOpt.AddAllowedClass(typeof(Solid3d), true); PromptEntityResult prEntRes = ed.GetEntity(prEntOpt); Solid3d sol = (Solid3d)tr.GetObject(prEntRes.ObjectId, OpenMode.ForRead); Acad3DSolid oSol = (Acad3DSolid)sol.AcadObject; ed.WriteMessage("\nSolid type: {0}", oSol.SolidType); //ElementCollection result = SolidOperator.Analyze(sol); //ed.WriteMessage("\nElement count: {0}", result.Elements.Count); } catch (System.Exception ex) { ed.WriteMessage("\nException during analysis: {0}", ex.Message); } } }
public void BeginTriangulate() { buildTriangulations buildT = new buildTriangulations(); AC_Transactions tr = new AC_Transactions(); PromptEntityOptions options = new PromptEntityOptions("Pick a Line to Triangulate"); options.SetRejectMessage("not valid Object \n"); options.AddAllowedClass(typeof(Line), true); PromptEntityResult sel = tr.AC_Doc.Editor.GetEntity(options); if (sel.Status == PromptStatus.OK) { tr.AC_Doc.Editor.WriteMessage("Line " + sel.ObjectId.ToString() + " Selected \n"); buildT.Create((AC_Line)tr.openObjectErased(sel.ObjectId)); } }
public void TestWEdding() { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; var selOpt = new PromptEntityOptions("\nВыбери полилинию для прополки"); selOpt.SetRejectMessage("\nТолько полилинию"); selOpt.AddAllowedClass(typeof(Polyline), true); var selRes = ed.GetEntity(selOpt); if (selRes.Status != PromptStatus.OK) return; using (var t = db.TransactionManager.StartTransaction()) { var pl = selRes.ObjectId.GetObject(OpenMode.ForWrite) as Polyline; pl.TestDrawVertexNumbers(Color.FromColor(System.Drawing.Color.Green)); pl.Wedding(new Autodesk.AutoCAD.Geometry.Tolerance (0.02,0.1)); pl.TestDrawVertexNumbers(Color.FromColor(System.Drawing.Color.Red)); t.Commit(); } }
public static String PromptSelectAlignment(String alignmentStatus) { String algnName = ""; try { using (var tr = AcadApp.StartTransaction()) { var opt = new PromptEntityOptions("\nВыберите " + alignmentStatus + " трассу: "); opt.SetRejectMessage("\nОбъект должен быть трассой.\n"); opt.AddAllowedClass(typeof(Alignment), false); var ent = AcadApp.AcaEd.GetEntity(opt); if (ent.Status == PromptStatus.OK) { var alignId = ent.ObjectId; if (alignId == ObjectId.Null) { return ""; } var curAlgn = tr.GetObject(alignId, OpenMode.ForRead) as Alignment; algnName = curAlgn.Name; return algnName; // All OK. Return alignment name } // If PromptStatus.OK } } catch (Autodesk.AutoCAD.Runtime.Exception ex) { AcadApp.AcaEd.WriteMessage("ERROR: CivApp.PromptSelectAlignment()\n" + ex + "\n"); } return ""; //There have been some errors }
public void getang() { Autodesk.AutoCAD.ApplicationServices.Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; string filepath = "D:\\tdoc.docx"; using (WordprocessingDocument docX = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document)) { try { // Add a main document part. MainDocumentPart mainPart = docX.AddMainDocumentPart(); StyleDefinitionsPart styleDefinitionsPart = mainPart.AddNewPart<StyleDefinitionsPart>(); Styles styles1 = new Styles(); DocDefaults docDefaults = new DocDefaults( new RunPropertiesDefault(new RunPropertiesBaseStyle(new RunFonts() { Ascii = "Times New Roman", HighAnsi = "Times New Roman", ComplexScript = "Times New Roman" }, new FontSize() { Val = "24" }, new FontSizeComplexScript() { Val = "24" })), new ParagraphPropertiesDefault(new SpacingBetweenLines() { After = "0", Line = "240", LineRule = LineSpacingRuleValues.Auto })); styles1.AppendChild(docDefaults); styleDefinitionsPart.Styles = styles1; mainPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document(); DocumentFormat.OpenXml.Wordprocessing.Body body = mainPart.Document.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Body()); ParagraphProperties paragraphProperties1 = new ParagraphProperties( new Justification() { Val = JustificationValues.Center }, new ParagraphMarkRunProperties( new RunFonts() { Ascii = "Times New Roman", HighAnsi = "Times New Roman", ComplexScript = "Times New Roman" }, new FontSize() { Val = "24" }, new FontSizeComplexScript() { Val = "24" } )); Paragraph para = body.AppendChild(new Paragraph()); para.AppendChild(paragraphProperties1); Run run = para.AppendChild(new Run()); RunProperties runProperties1 = new RunProperties( new Bold()); // String msg contains the text, "Hello, Word!" run.AppendChild(runProperties1); run.AppendChild(new Text("ПРИЛОЖЕНИЕ Ф")); run.AppendChild(new Break()); run.AppendChild(new Text("Ведомость углов поворотов")); run.AppendChild(new Break()); var table = new DocumentFormat.OpenXml.Wordprocessing.Table(); // Create a TableProperties object and specify its border information. TableProperties tblProp = new TableProperties( new TableWidth() { Width = "9782", Type = TableWidthUnitValues.Dxa }, new TableIndentation() { Width = -318, Type = TableWidthUnitValues.Dxa }, new TableBorders( new TopBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 }, new BottomBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 }, new LeftBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 }, new RightBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 }, new InsideHorizontalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 }, new InsideVerticalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 }), new DocumentFormat.OpenXml.Wordprocessing.TableStyle() { Val = "TableGrid" } ); // Append the TableProperties object to the empty table. table.AppendChild<TableProperties>(tblProp); // Add 3 columns to the table. TableGrid tg = new TableGrid(new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn()); table.AppendChild(tg); TableRow tr1 = new TableRow( new TableRowProperties(new TableRowHeight() { Val = 430 }), new TableCell( new TableCellProperties( new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1709" }, new VerticalMerge() { Val = MergedCellValues.Restart }, new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }), new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Обозначение точки")))), //new TableCellProperties(new TableCellWidth() {Type = TableWidthUnitValues.Pct, Width = "500"}) new TableCell( new TableCellProperties( new GridSpan() { Val = 2 }, new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }, new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "3922" }), new Paragraph( new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Run(new Text("Координаты точки")))), new TableCell( new TableCellProperties( new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1358" }, new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }, new VerticalMerge() { Val = MergedCellValues.Restart }), new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Пикетаж")))), new TableCell( new TableCellProperties( new GridSpan() { Val = 2 }, new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }, new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2368" }), new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Угол")))), new TableCell(new TableCellProperties( new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "425" }, new VerticalMerge() { Val = MergedCellValues.Restart }, new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }), new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Прямая вставка, м")))) ); table.AppendChild(tr1); TableRow tr2 = new TableRow( new TableRowProperties(new TableRowHeight() { Val = 419 }), new TableCell(new TableCellProperties(new VerticalMerge()), new Paragraph(new Run())), new TableCell( new TableCellProperties(new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }), new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Paragraph(new Run(new Text("Y")))), new TableCell( new TableCellProperties(new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }), new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Paragraph(new Run(new Text("X")))), new TableCell(new TableCellProperties(new VerticalMerge()), new Paragraph(new Run())), new TableCell( new TableCellProperties( new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1260" }, new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }), new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Лево")))), new TableCell( new TableCellProperties( new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1108" }, new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }), new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Право")))), new TableCell(new TableCellProperties(new VerticalMerge()), new Paragraph(new Run()))); table.AppendChild(tr2); TableCellProperties tcp = new TableCellProperties(new GridSpan() { Val = 7 }); while (true) { double dist = 0, paste = 0; table.AppendChild(new TableRow( new TableCell( new TableCellProperties( new GridSpan() { Val = 7 }), new Paragraph( new ParagraphProperties( new ParagraphMarkRunProperties(new Bold()), new Justification() { Val = JustificationValues.Center }), new Run(new RunProperties( new Bold()), new Text("Трасса")))))); PromptEntityOptions peo = new PromptEntityOptions("\nВыбери polyline: "); peo.SetRejectMessage("Можно только polyline."); peo.AddAllowedClass(typeof(Polyline), true); PromptEntityResult per = ed.GetEntity(peo); if (per.Status != PromptStatus.OK) { break; } PromptPointResult pPtRes; PromptPointOptions pPtOpts = new PromptPointOptions(""); // Prompt for the start point pPtOpts.Message = "\nВведи начало: "; pPtRes = doc.Editor.GetPoint(pPtOpts); PromptDoubleOptions getpik = new PromptDoubleOptions("\nВведи пикетаж (в формате числа, а не 0+00): "); PromptDoubleResult getpikRes = doc.Editor.GetDouble(getpik); dist = 100 * getpikRes.Value; /* PromptStringOptions pStrOpts = new PromptStringOptions("\nEnter your name: "); pStrOpts.AllowSpaces = true; PromptResult pStrRes = doc.Editor.GetString(pStrOpts); Application.ShowAlertDialog("The name entered was: " + pStrRes.StringResult); */ Point3d curr = pPtRes.Value, next = pPtRes.Value; try { using (Transaction tr = db.TransactionManager.StartTransaction()) { Polyline pline = (Polyline)tr.GetObject(per.ObjectId, OpenMode.ForRead); if ((pPtRes.Value == pline.GetLineSegmentAt(0).StartPoint) || (pPtRes.Value == pline.GetLineSegmentAt(0).EndPoint)) for (int i = 0; i < pline.NumberOfVertices - 2; i++) { TrassaRecord temp = new TrassaRecord(); temp.Name = "ВТ" + (i + 1).ToString(); LineSegment3d l1 = pline.GetLineSegmentAt(i); LineSegment3d l2 = pline.GetLineSegmentAt(i + 1); double angle = GetPolylineShape(l1, l2, pline.Normal); if (angle > Math.PI) { if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint)) { ed.WriteMessage("\n({0:0.00}, {1:0.00}): ", l1.StartPoint.X, l1.StartPoint.Y); next = l1.StartPoint; temp.CoordsX = l1.StartPoint.X.ToString("F"); temp.CoordsY = l1.StartPoint.Y.ToString("F"); } else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint)) { ed.WriteMessage("\n({0:0.00}, {1:0.00}): ", l1.EndPoint.X, l1.EndPoint.Y); next = l1.EndPoint; temp.CoordsX = l1.EndPoint.X.ToString("F"); temp.CoordsY = l1.EndPoint.Y.ToString("F"); } angle = -(angle - Math.PI * 2.0) * 180.0 / Math.PI; ed.WriteMessage("{0},{1:0}", (int)angle / 1, (angle % 1) * 60); temp.AngleT = TrassaRecord.Angle.Right; temp.AngleVal = ((int)angle / 1).ToString("F0") + "°" + ((angle % 1) * 60).ToString("F0") + "’"; } else { if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint)) { ed.WriteMessage("\n({0:0.00}, {1:0.00}): ", l1.StartPoint.X, l1.StartPoint.Y); next = l1.StartPoint; temp.CoordsX = l1.StartPoint.X.ToString("F"); temp.CoordsY = l1.StartPoint.Y.ToString("F"); } else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint)) { ed.WriteMessage("\n({0:0.00}, {1:0.00}): ", l1.EndPoint.X, l1.EndPoint.Y); next = l1.EndPoint; temp.CoordsX = l1.EndPoint.X.ToString("F"); temp.CoordsY = l1.EndPoint.Y.ToString("F"); } angle = angle * 180.0 / Math.PI; ed.WriteMessage("{0},{1:0}", (int)angle / 1, (angle % 1) * 60); temp.AngleT = TrassaRecord.Angle.Left; temp.AngleVal = ((int)angle / 1).ToString("F0") + "°" + ((angle % 1) * 60).ToString("F0") + "’"; } paste = curr.DistanceTo(next); dist += paste; curr = next; ed.WriteMessage(" {0:0.00} {1:0.00}", dist, paste); temp.Piketaz = ((int)dist / 100).ToString("F0") + "+" + (dist % 100).ToString("F"); temp.DirectInsert = paste.ToString("F"); tr2 = new TableRow( new TableRowProperties(new TableRowHeight() { Val = 300 }), new TableCell(new Paragraph(new Run())), new TableCell(new Paragraph(new Run())), new TableCell(new Paragraph(new Run())), new TableCell(new Paragraph(new Run())), new TableCell(new Paragraph(new Run())), new TableCell(new Paragraph(new Run())), new TableCell(new Paragraph(new Run(new Text(temp.DirectInsert)))) ); table.AppendChild(tr2); tr1 = new TableRow( new TableRowProperties(new TableRowHeight() { Val = 300 }), new TableCell(new Paragraph(new Run(new Text(temp.Name)))), new TableCell(new Paragraph(new Run(new Text(temp.CoordsX)))), new TableCell(new Paragraph(new Run(new Text(temp.CoordsY)))), new TableCell(new Paragraph(new Run(new Text(temp.Piketaz)))), new TableCell(new Paragraph(new Run(new Text((temp.AngleT == TrassaRecord.Angle.Left) ? temp.AngleVal.ToString() : "")))), new TableCell(new Paragraph(new Run(new Text((temp.AngleT == TrassaRecord.Angle.Right) ? temp.AngleVal.ToString() : "")))), new TableCell(new Paragraph(new Run())) ); table.AppendChild(tr1); } else for (int i = pline.NumberOfVertices - 3; i >= 0; i--) { TrassaRecord temp = new TrassaRecord(); temp.Name = "ВУ" + (pline.NumberOfVertices - 2 - i).ToString(); LineSegment3d l1 = pline.GetLineSegmentAt(i); LineSegment3d l2 = pline.GetLineSegmentAt(i + 1); double angle = GetPolylineShape(l1, l2, pline.Normal); if (angle > Math.PI) { if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint)) { ed.WriteMessage("\n({0:0.00}, {1:0.00}): ", l1.StartPoint.X, l1.StartPoint.Y); next = l1.StartPoint; temp.CoordsX = l1.StartPoint.X.ToString("F"); temp.CoordsY = l1.StartPoint.Y.ToString("F"); } else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint)) { ed.WriteMessage("\n({0:0.00}, {1:0.00}): ", l1.EndPoint.X, l1.EndPoint.Y); next = l1.EndPoint; temp.CoordsX = l1.EndPoint.X.ToString("F"); temp.CoordsY = l1.EndPoint.Y.ToString("F"); } angle = -(angle - Math.PI * 2.0) * 180.0 / Math.PI; ed.WriteMessage("{0},{1:0}", (int)angle / 1, (angle % 1) * 60); temp.AngleT = TrassaRecord.Angle.Left; temp.AngleVal = ((int)angle / 1).ToString("F0") + "°" + ((angle % 1) * 60).ToString("00") + "’"; } else { if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint)) { ed.WriteMessage("\n({0:0.00}, {1:0.00}): ", l1.StartPoint.X, l1.StartPoint.Y); next = l1.StartPoint; temp.CoordsX = l1.StartPoint.X.ToString("F"); temp.CoordsY = l1.StartPoint.Y.ToString("F"); } else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint)) { ed.WriteMessage("\n({0:0.00}, {1:0.00}): ", l1.EndPoint.X, l1.EndPoint.Y); next = l1.EndPoint; temp.CoordsX = l1.EndPoint.X.ToString("F"); temp.CoordsY = l1.EndPoint.Y.ToString("F"); } angle = angle * 180.0 / Math.PI; ed.WriteMessage("{0},{1:0}", (int)angle / 1, (angle % 1) * 60); temp.AngleT = TrassaRecord.Angle.Right; temp.AngleVal = ((int)angle / 1).ToString("F0") + "°" + ((angle % 1) * 60).ToString("00") + "’"; } paste = curr.DistanceTo(next); dist += paste; curr = next; ed.WriteMessage(" {0:0.00} {1:0.00}", dist, paste); temp.Piketaz = ((int)dist / 100).ToString("F0") + "+" + (dist % 100).ToString("F"); temp.DirectInsert = paste.ToString("F"); tr2 = new TableRow( new TableRowProperties(new TableRowHeight() { Val = 300 }), new TableCell(new Paragraph(new Run())), new TableCell(new Paragraph(new Run())), new TableCell(new Paragraph(new Run())), new TableCell(new Paragraph(new Run())), new TableCell(new Paragraph(new Run())), new TableCell(new Paragraph(new Run())), new TableCell(new Paragraph(new Run(new Text(temp.DirectInsert)))) ); table.AppendChild(tr2); tr1 = new TableRow( new TableRowProperties(new TableRowHeight() { Val = 300 }), new TableCell(new Paragraph(new Run(new Text(temp.Name)))), new TableCell(new Paragraph(new Run(new Text(temp.CoordsX)))), new TableCell(new Paragraph(new Run(new Text(temp.CoordsY)))), new TableCell(new Paragraph(new Run(new Text(temp.Piketaz)))), new TableCell(new Paragraph(new Run(new Text((temp.AngleT == TrassaRecord.Angle.Left) ? temp.AngleVal.ToString() : "")))), new TableCell(new Paragraph(new Run(new Text((temp.AngleT == TrassaRecord.Angle.Right) ? temp.AngleVal.ToString() : "")))), new TableCell(new Paragraph(new Run())) ); table.AppendChild(tr1); } } } catch { ed.WriteMessage("\nInvalid polyline."); } } body.AppendChild(table); body.AppendChild( new SectionProperties( new PageMargin() { Top = 1134, Right = (UInt32Value)850U, Bottom = 1134, Left = (UInt32Value)1418U, Header = (UInt32Value)708U, Footer = (UInt32Value)708U, Gutter = (UInt32Value)0U })); ed.WriteMessage("\nДокумент сохранен в D:\\tdoc.docx"); } catch { ed.WriteMessage("\nError."); } } }
public void GetIntersectionsRiver() { Database db = HostApplicationServices.WorkingDatabase; Autodesk.AutoCAD.ApplicationServices.Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; Transaction tr = db.TransactionManager.StartTransaction(); #region For Word string filepath = "D:\\intersections_rivers.docx"; using (WordprocessingDocument docX = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document)) { try { // Add a main document part. MainDocumentPart mainPart = docX.AddMainDocumentPart(); StyleDefinitionsPart styleDefinitionsPart = mainPart.AddNewPart<StyleDefinitionsPart>(); Styles styles1 = new Styles(); DocDefaults docDefaults = new DocDefaults( new RunPropertiesDefault(new RunPropertiesBaseStyle(new RunFonts() { Ascii = "Times New Roman", HighAnsi = "Times New Roman", ComplexScript = "Times New Roman" }, new FontSize() { Val = "24" }, new FontSizeComplexScript() { Val = "24" })), new ParagraphPropertiesDefault(new SpacingBetweenLines() { After = "0", Line = "240", LineRule = LineSpacingRuleValues.Auto })); styles1.AppendChild(docDefaults); styleDefinitionsPart.Styles = styles1; mainPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document(); DocumentFormat.OpenXml.Wordprocessing.Body body = mainPart.Document.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Body()); ParagraphProperties paragraphProperties1 = new ParagraphProperties( new Justification() { Val = JustificationValues.Center }, new ParagraphMarkRunProperties( new RunFonts() { Ascii = "Times New Roman", HighAnsi = "Times New Roman", ComplexScript = "Times New Roman" }, new FontSize() { Val = "24" }, new FontSizeComplexScript() { Val = "24" } )); Paragraph para = body.AppendChild(new Paragraph()); para.AppendChild(paragraphProperties1); Run run = para.AppendChild(new Run()); RunProperties runProperties1 = new RunProperties( new Bold()); // String msg contains the text, "Hello, Word!" run.AppendChild(runProperties1); run.AppendChild(new Text("ПРИЛОЖЕНИЕ")); run.AppendChild(new Break()); run.AppendChild(new Text("Ведомость пересечений")); run.AppendChild(new Break()); var table = new DocumentFormat.OpenXml.Wordprocessing.Table(); // Create a TableProperties object and specify its border information. TableProperties tblProp = new TableProperties( new TableWidth() { Width = "9782", Type = TableWidthUnitValues.Dxa }, new TableIndentation() { Width = -318, Type = TableWidthUnitValues.Dxa }, new TableBorders( new TopBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 }, new BottomBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 }, new LeftBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 }, new RightBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 }, new InsideHorizontalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 }, new InsideVerticalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 }), new DocumentFormat.OpenXml.Wordprocessing.TableStyle() { Val = "TableGrid" } ); // Append the TableProperties object to the empty table. table.AppendChild<TableProperties>(tblProp); // Add 3 columns to the table. TableGrid tg = new TableGrid(new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn()); table.AppendChild(tg); TableRow tr1 = new TableRow( new TableRowProperties(new TableRowHeight() { Val = 430 }), new TableCell( new TableCellProperties( new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1709" }, new VerticalMerge() { Val = MergedCellValues.Restart }, new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }), new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Наимен. водотока")))), //new TableCellProperties(new TableCellWidth() {Type = TableWidthUnitValues.Pct, Width = "500"}) new TableCell( new TableCellProperties( new GridSpan() { Val = 2 }, new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }, new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "3922" }), new Paragraph( new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Run(new Text("Пикетное положение пересечения")))), new TableCell( new TableCellProperties( new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }), new Paragraph( new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Run(new Text("Ширина водотока в межень")))), new TableCell( new TableCellProperties( new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1358" }, new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }, new VerticalMerge() { Val = MergedCellValues.Restart }), new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Глуб. водотока")))), new TableCell( new TableCellProperties( new GridSpan() { Val = 3 }, new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }, new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2368" }), new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Горизонт воды")))), new TableCell(new TableCellProperties( new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "425" }, new VerticalMerge() { Val = MergedCellValues.Restart }, new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }), new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Прим.")))) ); table.AppendChild(tr1); TableRow tr2 = new TableRow( new TableRowProperties(new TableRowHeight() { Val = 419 }), new TableCell(new TableCellProperties(new VerticalMerge()), new Paragraph(new Run())), new TableCell( new TableCellProperties(new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }), new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Paragraph(new Run(new Text("От")))), new TableCell( new TableCellProperties(new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }), new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Paragraph(new Run(new Text("До")))), new TableCell( new TableCellProperties(new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }), new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Paragraph(new Run(new Text("половодье")))), new TableCell(new TableCellProperties(new VerticalMerge()), new Paragraph(new Run())), new TableCell( new TableCellProperties( new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1260" }, new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }), new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Дата съемки")))), new TableCell( new TableCellProperties( new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1108" }, new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }), new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("На день съемки")))), new TableCell( new TableCellProperties( new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1108" }, new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }), new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Макс.")))), new TableCell(new TableCellProperties(new VerticalMerge()), new Paragraph(new Run()))); table.AppendChild(tr2); TableCellProperties tcp = new TableCellProperties(new GridSpan() { Val = 9 }); #endregion while (true) { //using (tr) //{ try { #region Поиск пересечений BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite); PromptEntityOptions peo = new PromptEntityOptions("\nВыбери polyline >>"); peo.SetRejectMessage("\nМожно только polyline >>"); peo.AddAllowedClass(typeof(Polyline), false); PromptEntityResult res; res = ed.GetEntity(peo); if (res.Status != PromptStatus.OK) { break; } DBObject ent = (DBObject)tr.GetObject(res.ObjectId, OpenMode.ForRead); if (ent == null) return; PromptPointResult pPtRes; PromptPointOptions pPtOpts = new PromptPointOptions(""); // Prompt for the start point pPtOpts.Message = "\nВведи начало: "; pPtRes = doc.Editor.GetPoint(pPtOpts); PromptDoubleOptions getpik = new PromptDoubleOptions("\nВведи пикетаж (в формате числа, а не 0+00): "); PromptDoubleResult getpikRes = doc.Editor.GetDouble(getpik); //zoom /*PromptEntityResult per = ed.GetEntity(peo); if (per.Status != PromptStatus.OK) return;*/ // Extract its extents Extents3d ext; Transaction trans = db.TransactionManager.StartTransaction(); using (trans) { Entity enti = (Entity)trans.GetObject(res.ObjectId, OpenMode.ForRead); ext = enti.GeometricExtents; trans.Commit(); } ext.TransformBy(ed.CurrentUserCoordinateSystem.Inverse()); ZoomWin(ed, ext.MinPoint, ext.MaxPoint); // //Polyline poly = (Polyline)ent as Polyline; Curve curv = ent as Curve; DBObjectCollection pcurves = new DBObjectCollection(); curv.Explode(pcurves); TypedValue[] values = new TypedValue[] { new TypedValue(0, "lwpolyline") //might be added layer name to select curve: //, new TypedValue(8, "mylayer") }; SelectionFilter filter = new SelectionFilter(values); Point3dCollection fence = new Point3dCollection(); double leng = curv.GetDistanceAtParameter(curv.EndParam) - curv.GetDistanceAtParameter(curv.StartParam); // number of divisions along polyline to create fence selection double step = leng / 256;// set number of steps to your suit int num = Convert.ToInt32(leng / step); for (int i = 0; i < num; i++) { Point3d pp = curv.GetPointAtDist(step * i); fence.Add(curv.GetClosestPointTo(pp, false)); } PromptSelectionResult selres = ed.SelectFence(fence, filter); if (selres.Status != PromptStatus.OK) return; Point3dCollection intpts = new Point3dCollection(); DBObjectCollection qcurves = new DBObjectCollection(); //ed.WriteMessage("\nCheck"); foreach (SelectedObject selobj in selres.Value) { DBObject obj = tr.GetObject(selobj.ObjectId, OpenMode.ForRead, false) as DBObject; if (selobj.ObjectId != curv.ObjectId) { DBObjectCollection icurves = new DBObjectCollection(); Curve icurv = obj as Curve; icurv.Explode(icurves); foreach (DBObject dbo in icurves) { if (!qcurves.Contains(dbo)) qcurves.Add(dbo); } } } //ed.WriteMessage("\n{0}", qcurves.Count); int j = 0; Point3dCollection polypts = new Point3dCollection(); for (int i = 0; i < pcurves.Count; ++i) { for (j = 0; j < qcurves.Count; ++j) { Curve curve1 = pcurves[i] as Curve; Curve curve2 = qcurves[j] as Curve; Point3dCollection pts = new Point3dCollection(); curve1.IntersectWith(curve2, Intersect.OnBothOperands, pts, IntPtr.Zero, IntPtr.Zero); foreach (Point3d pt in pts) { if (!polypts.Contains(pt)) polypts.Add(pt); } } } #endregion try { using (Transaction tran = db.TransactionManager.StartTransaction()) { Polyline pline = (Polyline)tran.GetObject(res.ObjectId, OpenMode.ForRead); table.AppendChild(new TableRow( new TableCell( new TableCellProperties( new GridSpan() { Val = 9 }), new Paragraph( new ParagraphProperties( new ParagraphMarkRunProperties(new Bold()), new Justification() { Val = JustificationValues.Center }), new Run(new RunProperties( new Bold()), new Text("ПК" + ((int)(getpikRes.Value)).ToString("F0") + "-ПК" + ((int)(100 * getpikRes.Value + pline.Length) / 100).ToString("F0") + "+" + ((100 * getpikRes.Value + pline.Length) % 100).ToString("F"))))))); } } catch { ed.WriteMessage("\nError."); } Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("osmode", 0);// optional // for debug only Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(string.Format("\nНайдено пересечений: {0}", polypts.Count)); if (polypts.Count == 0) { try { using (Transaction tran = db.TransactionManager.StartTransaction()) { Polyline pline = (Polyline)tran.GetObject(res.ObjectId, OpenMode.ForRead); table.AppendChild(new TableRow( new TableCell( new TableCellProperties( new GridSpan() { Val = 9 }), new Paragraph( new ParagraphProperties( new Justification() { Val = JustificationValues.Center }), new Run(new Text("На данном участке трассы пересечения отсутствуют")))))); } } catch { ed.WriteMessage("\nError."); } } else { //List<double> pik = new List<double>(polypts.Count); double[] pik = new double[polypts.Count]; int numInter = 0; foreach (Point3d inspt in polypts) { double dist = 0; dist = 100 * getpikRes.Value; // test for visulization only /*Circle circ = new Circle(inspt, Vector3d.ZAxis, 10 * db.Dimtxt); circ.ColorIndex = 1; btr.AppendEntity(circ); tr.AddNewlyCreatedDBObject(circ, true);*/ Point3d curr = pPtRes.Value, next = pPtRes.Value; try { using (Transaction tran = db.TransactionManager.StartTransaction()) { Polyline pline = (Polyline)tran.GetObject(res.ObjectId, OpenMode.ForRead); if ((pPtRes.Value == pline.GetLineSegmentAt(0).StartPoint) || (pPtRes.Value == pline.GetLineSegmentAt(0).EndPoint)) for (int i = 0; i < pline.NumberOfVertices - 2; i++) { LineSegment3d l1 = pline.GetLineSegmentAt(i); LineSegment3d l2 = pline.GetLineSegmentAt(i + 1); double angle = GetPolylineShape(l1, l2, pline.Normal); if (angle > Math.PI) { if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint)) next = l1.StartPoint; else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint)) next = l1.EndPoint; } else { if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint)) next = l1.StartPoint; else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint)) next = l1.EndPoint; } if (Math.Abs(inspt.DistanceTo(curr) + inspt.DistanceTo(next) - curr.DistanceTo(next)) < 1) { dist += inspt.DistanceTo(curr); ed.WriteMessage(((int)dist / 100).ToString("F0") + "+" + (dist % 100).ToString("F") + "\n"); break; } else dist += curr.DistanceTo(next); curr = next; } else for (int i = pline.NumberOfVertices - 3; i >= 0; i--) { LineSegment3d l1 = pline.GetLineSegmentAt(i); LineSegment3d l2 = pline.GetLineSegmentAt(i + 1); double angle = GetPolylineShape(l1, l2, pline.Normal); if (angle > Math.PI) { if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint)) next = l1.StartPoint; else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint)) next = l1.EndPoint; } else { if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint)) next = l1.StartPoint; else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint)) next = l1.EndPoint; } if (Math.Abs(inspt.DistanceTo(curr) + inspt.DistanceTo(next) - curr.DistanceTo(next)) < 1) { dist += inspt.DistanceTo(curr); ed.WriteMessage(((int)dist / 100).ToString("F0") + "+" + (dist % 100).ToString("F") + "\n"); break; } else dist += curr.DistanceTo(next); curr = next; } } } catch { ed.WriteMessage("\nInvalid polyline."); } pik[numInter] = dist; numInter++; //ed.WriteMessage(" {0:0.00}\n", dist); } //pik.Sort(); Array.Sort(pik); for (int i = 0; i < polypts.Count; i++) { tr1 = new TableRow( new TableRowProperties(new TableRowHeight() { Val = 300 }), new TableCell(new Paragraph(new Run())), new TableCell( new TableCellProperties( new GridSpan() { Val = 2 }), new Paragraph( new ParagraphProperties( new Justification() { Val = JustificationValues.Center }), new Run(new Text(((int)pik[i] / 100).ToString("F0") + "+" + (pik[i] % 100).ToString("F"))))), new TableCell(new Paragraph(new Run())), new TableCell(new Paragraph(new Run())), new TableCell(new Paragraph(new Run())), new TableCell(new Paragraph(new Run())), new TableCell(new Paragraph(new Run())), new TableCell(new Paragraph(new Run())) ); table.AppendChild(tr1); } } } catch { ed.WriteMessage("\nError"); } //} } tr.Commit(); body.AppendChild(table); body.AppendChild( new SectionProperties( new PageMargin() { Top = 1134, Right = (UInt32Value)850U, Bottom = 1134, Left = (UInt32Value)1418U, Header = (UInt32Value)708U, Footer = (UInt32Value)708U, Gutter = (UInt32Value)0U })); ed.WriteMessage("\nДокумент сохранен в D:\\intersections_rivers.docx"); } catch { ed.WriteMessage("\nError."); } } }
private void btnAlign_Click(object sender, EventArgs e) { Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; using (EditorUserInteraction UI = ed.StartUserInteraction(this)) { PromptEntityOptions opts = new PromptEntityOptions("\nSelect entity: "); opts.AllowNone = false; opts.SetRejectMessage("\nSelect a LINE, ARC or POLYLINE entity."); opts.AddAllowedClass(typeof(Curve), false); PromptEntityResult per = ed.GetEntity(opts); if (per.Status == PromptStatus.OK) { Point3d pt = per.PickedPoint; ObjectId id = per.ObjectId; bool posUp = false; Vector3d dir = new Vector3d(), up = new Vector3d(), normal = new Vector3d(); Database db = HostApplicationServices.WorkingDatabase; using (Transaction tr = db.TransactionManager.StartTransaction()) { try { RebarPos pos = (RebarPos)tr.GetObject(m_Pos, OpenMode.ForRead); Curve curve = (Curve)tr.GetObject(id, OpenMode.ForRead); pt = curve.GetClosestPointTo(pt, curve.GetPlane().Normal, false); dir = curve.GetFirstDerivative(pt); dir = dir * pos.DirectionVector.Length / dir.Length; normal = pos.NormalVector; normal = normal * pos.DirectionVector.Length / normal.Length; up = dir.CrossProduct(normal); up = up * pos.DirectionVector.Length / up.Length; posUp = (dir.DotProduct(pos.UpVector) > 0); } catch (System.Exception ex) { System.Windows.Forms.MessageBox.Show("Error: " + ex.Message, "RebarPos", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); } } double offset = 0.0; double offset1 = -0.75, offset2 = 1.75; if (posUp) { AlignPos(pt + offset1 * up, dir, up, normal); offset = offset2; } else { AlignPos(pt + offset2 * up, dir, up, normal); offset = offset1; } PromptKeywordOptions kopts = new PromptKeywordOptions("\nDiğer tarafa yerleştirilsin mi? [Evet/Hayır] <Hayir>: ", "Yes No"); kopts.AllowNone = true; PromptResult kres = ed.GetKeywords(kopts); if (kres.Status == PromptStatus.None || kres.StringResult == "Yes") { AlignPos(pt + offset * up, dir, up, normal); ed.UpdateScreen(); } } } }
private void GetLengthFromEntity(TextBox txt) { Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; using (EditorUserInteraction UI = ed.StartUserInteraction(this)) { PromptEntityOptions opts = new PromptEntityOptions("\nSelect entity: "); opts.SetRejectMessage("\nSelect a LINE, ARC, TEXT, MTEXT, POLYLINE or DIMENSION entity."); opts.AddAllowedClass(typeof(Line), false); opts.AddAllowedClass(typeof(Arc), false); opts.AddAllowedClass(typeof(DBText), false); opts.AddAllowedClass(typeof(MText), false); opts.AddAllowedClass(typeof(Dimension), false); opts.AddAllowedClass(typeof(Polyline), false); PromptEntityResult per = ed.GetEntity(opts); if (per.Status == PromptStatus.OK) { ObjectId id = per.ObjectId; Database db = HostApplicationServices.WorkingDatabase; using (Transaction tr = db.TransactionManager.StartTransaction()) { try { DBObject obj = tr.GetObject(per.ObjectId, OpenMode.ForRead); if (obj is Line) { Line dobj = obj as Line; txt.Text = dobj.Length.ToString(); } else if (obj is Arc) { Arc dobj = obj as Arc; txt.Text = dobj.Length.ToString(); } else if (obj is DBText) { DBText dobj = obj as DBText; txt.Text = dobj.TextString; } else if (obj is MText) { MText dobj = obj as MText; txt.Text = dobj.Text; } else if (obj is Dimension) { Dimension dobj = obj as Dimension; txt.Text = dobj.Measurement.ToString(); } else if (obj is Polyline) { Polyline dobj = obj as Polyline; txt.Text = dobj.Length.ToString(); } CheckPosLength(txt); } catch (System.Exception ex) { System.Windows.Forms.MessageBox.Show("Error: " + ex.Message, "RebarPos", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); } } } } }
public static String PromptSelectTINSurface(String sufraceStatus) { String surfName = ""; try { using (var tr = AcadApp.StartTransaction()) { var opt = new PromptEntityOptions("\nВыберите " + sufraceStatus + " поверхность TIN: "); opt.SetRejectMessage("\nОбъект должен быть поверхностью TIN.\n"); opt.AddAllowedClass(typeof(TinSurface), false); var ent = AcadApp.AcaEd.GetEntity(opt); if (ent.Status == PromptStatus.OK) { var tinsurfId = ent.ObjectId; if (tinsurfId == ObjectId.Null) { return ""; } var tinsurf = tinsurfId.GetObject(OpenMode.ForRead) as TinSurface; surfName = tinsurf.Name; return surfName; // All OK. Return surface name } // If PromptStatus.OK } // using } catch (Autodesk.AutoCAD.Runtime.Exception ex) { AcadApp.AcaEd.WriteMessage("ERROR: CivApp.PromptSelectTINSurface()\n" + ex + "\n"); } return ""; //There have been some errors }
public void DrawGroupLeader() { Editor ed = dwg.Editor; PromptEntityOptions prmtEntityOpts = new PromptEntityOptions("Укажите линию"); prmtEntityOpts.AllowNone = false; prmtEntityOpts.SetRejectMessage("Должна быть линия или полилиния!"); prmtEntityOpts.AddAllowedClass(typeof(Line), true); prmtEntityOpts.AddAllowedClass(typeof(Polyline), true); PromptEntityResult entRes = ed.GetEntity(prmtEntityOpts); if (entRes.Status!= PromptStatus.OK) { return; } using (Transaction tr = CurrentDatabase.TransactionManager.StartTransaction()) { GroupsInformation groupEntities = new GroupsInformation(tr, CurrentDatabase); List<string> groupList = groupEntities.GetGroupsOfObject(entRes.ObjectId); if (groupList == null) { ed.WriteMessage("За указанным объектом не значится никаких групп!"); return; } PromptPointOptions pointOpts = new PromptPointOptions("\nУкажите точку вставки блока: "); PromptPointResult pointRes = ed.GetPoint(pointOpts); if (pointRes.Status!= PromptStatus.OK) { return; } BlockTable bt = (BlockTable)CurrentDatabase.BlockTableId.GetObject(OpenMode.ForRead); BlockTableRecord btrSpace = (BlockTableRecord)CurrentDatabase.CurrentSpaceId .GetObject(OpenMode.ForWrite); if (!bt.Has("group_vinoska")) { ed.WriteMessage("\nВ файле не определён блок выноски!!"); return; } BlockTableRecord gleaderBtr = (BlockTableRecord)bt["group_vinoska"].GetObject(OpenMode.ForRead); BlockReference gleader = new BlockReference(pointRes.Value, gleaderBtr.ObjectId); btrSpace.AppendEntity(gleader); tr.AddNewlyCreatedDBObject(gleader, true); //Если блок аннотативный - добавляем в таблицу аннотативных масштабов блока текущий масштаб ObjectContextManager ocm = CurrentDatabase.ObjectContextManager; ObjectContextCollection occ = ocm.GetContextCollection("ACDB_ANNOTATIONSCALES"); if (gleaderBtr.Annotative == AnnotativeStates.True) { ObjectContexts.AddContext(gleader, occ.CurrentContext); } gleader.SetDatabaseDefaults(); if (gleaderBtr.HasAttributeDefinitions) { var attDefs = gleaderBtr.Cast<ObjectId>() .Where(n => n.ObjectClass.Name == "AcDbAttributeDefinition") .Select(n => (AttributeDefinition)n.GetObject(OpenMode.ForRead)); foreach (AttributeDefinition attdef in attDefs) { AttributeReference attref = new AttributeReference(); attref.SetAttributeFromBlock(attdef, gleader.BlockTransform); gleader.AttributeCollection.AppendAttribute(attref); tr.AddNewlyCreatedDBObject(attref, true); if (gleaderBtr.Annotative == AnnotativeStates.True) { ObjectContexts.AddContext(attref, occ.CurrentContext); } int attCount = int.Parse(attref.Tag.Remove(0,10)); if (attCount<=groupList.Count) { attref.TextString = groupList[attCount-1]; } } } if (gleaderBtr.IsDynamicBlock) { DynamicBlockReferencePropertyCollection dynBRefColl = gleader.DynamicBlockReferencePropertyCollection; foreach (DynamicBlockReferenceProperty prop in dynBRefColl) { if (prop.PropertyName == "Lookup1") { prop.Value = prop.GetAllowedValues()[groupList.Count-1]; } } } tr.Commit(); } }
public void ModifyTriangulate() { Triangulations triangulation = new Triangulations(); AC_Transactions tr = new AC_Transactions(); PromptEntityOptions options = new PromptEntityOptions("Pick a Line to modify Triangulations"); options.SetRejectMessage("not valid Object \n"); options.AddAllowedClass(typeof(Line), true); PromptEntityResult sel = tr.AC_Doc.Editor.GetEntity(options); if (sel.Status == PromptStatus.OK) { triangulation.Modify((AC_Line)tr.openObjectErased(sel.ObjectId)); } }