public override void Prompt(string message, Action<PromptResult> promptResult, string title, string okText, string cancelText, string placeholder, int lines) { this.Dispatch(() => { var result = new PromptResult(); var dlg = new UIAlertView(title ?? String.Empty, message, null, cancelText, okText) { AlertViewStyle = UIAlertViewStyle.PlainTextInput }; var txt = dlg.GetTextField(0); txt.Placeholder = placeholder; //UITextView = editable dlg.Clicked += (s, e) => { result.Ok = (dlg.CancelButtonIndex != e.ButtonIndex); result.Text = txt.Text; promptResult(result); }; dlg.Show(); }); }
public override void Prompt(PromptConfig config) { this.Dispatch(() => { var result = new PromptResult(); var dlg = new UIAlertView(config.Title ?? String.Empty, config.Message, null, config.CancelText, config.OkText) { AlertViewStyle = config.InputType == InputType.Password ? UIAlertViewStyle.SecureTextInput : UIAlertViewStyle.PlainTextInput }; var txt = dlg.GetTextField(0); txt.SecureTextEntry = config.InputType == InputType.Password; txt.Placeholder = config.Placeholder; txt.KeyboardType = Utils.GetKeyboardType(config.InputType); dlg.Clicked += (s, e) => { result.Ok = (dlg.CancelButtonIndex != e.ButtonIndex); result.Text = txt.Text; config.OnResult(result); }; dlg.Show(); }); }
public override void Prompt(PromptConfig config) { var result = new PromptResult(); var dlg = UIAlertController.Create(config.Title ?? String.Empty, config.Message, UIAlertControllerStyle.Alert); UITextField txt = null; dlg.AddAction(UIAlertAction.Create(config.OkText, UIAlertActionStyle.Default, x => { result.Ok = true; result.Text = txt.Text.Trim(); config.OnResult(result); })); dlg.AddAction(UIAlertAction.Create(config.CancelText, UIAlertActionStyle.Default, x => { result.Ok = false; result.Text = txt.Text.Trim(); config.OnResult(result); })); dlg.AddTextField(x => { x.SecureTextEntry = config.IsSecure; x.Placeholder = config.Placeholder ?? String.Empty; txt = x; }); this.Present(dlg); }
// Ask the user to enter an optional string field private static string GetOptionalString( Editor ed, string prompt, object defVal ) { PromptStringOptions pso = new PromptStringOptions( "\n" + prompt + " (optional): " ); pso.AllowSpaces = true; if (defVal != null) { pso.DefaultValue = (string)defVal; pso.UseDefaultValue = true; } PromptResult pr = ed.GetString(pso); if (pr.Status != PromptStatus.OK) { throw new CancellationException(); } return(pr.StringResult); }
public void GenerateSnapshot() // This method can have any name { Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; PromptResult pr = ed.GetString("\nOutput Path: "); if (pr.Status != PromptStatus.OK) { ed.WriteMessage("No path was provided.\n"); return; } var result = doc.Editor.SelectAll(); if (result.Status == PromptStatus.OK) { Autodesk.AutoCAD.Internal.Utils.SelectObjects(result.Value.GetObjectIds()); } #if C3D2014 doc.SendStringToExecute(string.Format("_.PNGOUT\n{0}\n\n\x03\x03", pr.StringResult), true, false, false); #else doc.Editor.Command("_.PNGOUT", pr.StringResult, ""); #endif }
private string GetInputCommand() { Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; PromptKeywordOptions pko = new PromptKeywordOptions("Input the command:"); pko.Keywords.Add("InitSample"); pko.Keywords.Add("StretchBody"); pko.Keywords.Add("AddBody"); pko.Keywords.Add("ListBody"); pko.Keywords.Add("SectionBody"); pko.Keywords.Add("MultiplyBody"); pko.Keywords.Add("SubBody"); pko.Keywords.Add("Clear"); pko.Keywords.Add("BooleanOp"); pko.Keywords.Add("CombineBody"); pko.Keywords.Add("TranslateBody"); pko.Keywords.Add("RotateBody"); pko.Keywords.Add("ScaleBody"); pko.Keywords.Add("ListPickBody"); pko.Keywords.Add("Quit"); PromptResult result = ed.GetKeywords(pko); return(result.StringResult); }
public void DrawSurface() { if (!CheckLicense.Check()) { return; } Autodesk.AutoCAD.ApplicationServices.Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Topography topo = Topography.Instance; Topography.SurfaceType surface = Topography.PickSurface(); if (surface == Topography.SurfaceType.None) { return; } if (!Topography.EnsureSurfaceNotEmpty(surface)) { return; } TriangleNet.Mesh mesh = (surface == Topography.SurfaceType.Original ? topo.OriginalTIN : topo.ProposedTIN); // Object type PromptKeywordOptions opts = new PromptKeywordOptions("\nÇizim nesneleri [Geçici/3dFace/Point/polyfaceMesh] <Geçici>: ", "Temporary 3dFace Point polyfaceMesh"); opts.Keywords.Default = "Temporary"; opts.AllowNone = true; PromptResult res = doc.Editor.GetKeywords(opts); string outputType = res.StringResult; if (res.Status == PromptStatus.None) { outputType = "Temporary"; } else if (res.Status != PromptStatus.OK) { return; } // Color option opts = new PromptKeywordOptions("\nRenkli çizim [E/H] <E>: ", "Yes No"); opts.Keywords.Default = "Yes"; opts.AllowNone = true; res = doc.Editor.GetKeywords(opts); bool useColor = true; if (res.Status == PromptStatus.None) { useColor = true; } else if (res.Status != PromptStatus.OK) { return; } else { useColor = (string.Compare(res.StringResult, "Yes", StringComparison.OrdinalIgnoreCase) == 0); } double zmin = double.MaxValue; double zmax = double.MinValue; foreach (TriangleNet.Data.Vertex v in mesh.Vertices) { zmin = Math.Min(zmin, v.Attributes[0]); zmax = Math.Max(zmax, v.Attributes[0]); } using (Transaction tr = db.TransactionManager.StartTransaction()) using (BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite)) { try { if (string.Compare(outputType, "Temporary", StringComparison.OrdinalIgnoreCase) == 0) { EraseTemporaryGraphics(); foreach (TriangleNet.Data.Triangle tri in mesh.Triangles) { TriangleNet.Data.Vertex v1 = tri.GetVertex(0); TriangleNet.Data.Vertex v2 = tri.GetVertex(1); TriangleNet.Data.Vertex v3 = tri.GetVertex(2); Face face = new Face(new Point3d(v1.X, v1.Y, v1.Attributes[0]), new Point3d(v2.X, v2.Y, v2.Attributes[0]), new Point3d(v3.X, v3.Y, v3.Attributes[0]), true, true, true, true); if (useColor) { face.Color = ColorFromZ((v1.Attributes[0] + v2.Attributes[0] + v3.Attributes[0]) / 3, zmin, zmax); } temporaryGraphics.Add(face); } DrawTemporaryGraphics(); } else if (string.Compare(outputType, "3dFace", StringComparison.OrdinalIgnoreCase) == 0) { foreach (TriangleNet.Data.Triangle tri in mesh.Triangles) { TriangleNet.Data.Vertex v1 = tri.GetVertex(0); TriangleNet.Data.Vertex v2 = tri.GetVertex(1); TriangleNet.Data.Vertex v3 = tri.GetVertex(2); Face face = new Face(new Point3d(v1.X, v1.Y, v1.Attributes[0]), new Point3d(v2.X, v2.Y, v2.Attributes[0]), new Point3d(v3.X, v3.Y, v3.Attributes[0]), true, true, true, true); if (useColor) { face.Color = ColorFromZ((v1.Attributes[0] + v2.Attributes[0] + v3.Attributes[0]) / 3, zmin, zmax); } btr.AppendEntity(face); tr.AddNewlyCreatedDBObject(face, true); } } else if (string.Compare(outputType, "Point", StringComparison.OrdinalIgnoreCase) == 0) { foreach (TriangleNet.Data.Vertex v in mesh.Vertices) { DBPoint point = new DBPoint(new Point3d(v.X, v.Y, v.Attributes[0])); if (useColor) { point.Color = ColorFromZ(v.Attributes[0], zmin, zmax); } btr.AppendEntity(point); tr.AddNewlyCreatedDBObject(point, true); } } else if (string.Compare(outputType, "polyfaceMesh", StringComparison.OrdinalIgnoreCase) == 0) { PolyFaceMesh pfm = new PolyFaceMesh(); btr.AppendEntity(pfm); tr.AddNewlyCreatedDBObject(pfm, true); // Vertices SortedDictionary <int, Point3d> vertices = new SortedDictionary <int, Point3d>(); foreach (TriangleNet.Data.Vertex v in mesh.Vertices) { vertices.Add(v.ID, new Point3d(v.X, v.Y, v.Attributes[0])); } foreach (KeyValuePair <int, Point3d> v in vertices) { PolyFaceMeshVertex point = new PolyFaceMeshVertex(v.Value); pfm.AppendVertex(point); tr.AddNewlyCreatedDBObject(point, true); } // Faces foreach (TriangleNet.Data.Triangle tri in mesh.Triangles) { FaceRecord face = new FaceRecord((short)(tri.P0 + 1), (short)(tri.P1 + 1), (short)(tri.P2 + 1), 0); if (useColor) { face.Color = ColorFromZ((tri.GetVertex(0).Attributes[0] + tri.GetVertex(1).Attributes[0] + tri.GetVertex(2).Attributes[0]) / 3, zmin, zmax); } pfm.AppendFaceRecord(face); tr.AddNewlyCreatedDBObject(face, true); } } } catch (System.Exception ex) { MessageBox.Show("Error: " + ex.ToString(), "XCOM", MessageBoxButtons.OK, MessageBoxIcon.Error); } tr.Commit(); } }
public static void UpdateAttribute() { string blockName = ""; Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; Transaction tr = doc.TransactionManager.StartTransaction(); using (tr) { BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; //check to see wich Title block is in the drawing if any if (bt != null) { if (bt.Has("Title-AE.dwg")) { blockName = "TITLE-AE.DWG"; } if (bt.Has("Title-C.dwg")) { blockName = "TITLE-C.DWG"; } if (bt.Has("Title-D.dwg")) { blockName = "TITLE-D.DWG"; } if (bt.Has("Title-B.dwg")) { blockName = "TITLE-B.DWG"; } //the old 2008 lisp command put the title blocks without the .dwg at the end //so basically I have half the drawings out there without it and this is the only easy fix I can think of if (bt.Has("Title-AE")) { blockName = "TITLE-AE"; } if (bt.Has("Title-C")) { blockName = "TITLE-C"; } if (bt.Has("Title-D")) { blockName = "TITLE-D"; } if (bt.Has("Title-B")) { blockName = "TITLE-B"; } tr.Commit(); } else { MessageBox.Show("Something has gone wrong. Block Table is null."); } } PromptStringOptions pso = new PromptStringOptions(""); pso.AllowSpaces = true; //gets the attribute name to change from the menu macro PromptResult pr = ed.GetString(pso); if (pr.Status != PromptStatus.OK) { return; } string attbName = pr.StringResult.ToUpper(); //get the attribute value from the menu macro pr = ed.GetString(pso); if (pr.Status != PromptStatus.OK) { return; } string attbValue = pr.StringResult; UpdateAttributesInDatabase(db, blockName, attbName, attbValue); }
public void TcGJHJ_LM() { int num; int num10; object obj; try { IL_01: ProjectData.ClearProjectError(); num = -2; IL_09: int num2 = 2; bool flag; ObjectId[] array; short num5; short num6; checked { this.long_0 = (long)Math.Round(Conversion.Val(Interaction.InputBox("输入钢筋桁架高度:", "田草CAD工具箱-绘制钢筋桁架", "100", -1, -1))); IL_32: num2 = 3; if (this.long_0 != 0L) { goto IL_4C; } IL_47: goto IL_253; IL_4C: num2 = 6; this.double_0 = CAD.GetScale(); IL_59: num2 = 7; this.point3d_0 = CAD.GetPoint("选择插入点: "); IL_6B: num2 = 8; Point3d point3d; if (!(this.point3d_0 == point3d)) { goto IL_80; } IL_7B: goto IL_253; IL_80: num2 = 11; CAD.CreateLayer("钢筋桁架", 14, "continuous", -1, false, true); IL_98: num2 = 12; flag = false; IL_9E: num2 = 13; Database workingDatabase = HostApplicationServices.WorkingDatabase; IL_A7: num2 = 14; Editor editor = Application.DocumentManager.MdiActiveDocument.Editor; IL_BA: num2 = 15; PromptResult promptResult = editor.Drag(this); IL_C6: num2 = 16; if (promptResult.Status != 5100) { goto IL_179; } IL_DC: num2 = 17; short num3 = (short)(this.entity_0.Length - 1); IL_EC: num2 = 18; if (num3 != 0) { goto IL_109; } IL_F6: num2 = 19; CAD.AddEnt(this.entity_0[0]); goto IL_179; IL_109: num2 = 21; IL_10C: num2 = 22; array = new ObjectId[(int)(num3 + 1)]; IL_11A: num2 = 23; short num4 = 0; num5 = (short)(this.entity_0.Length - 1); num6 = num4; } for (;;) { short num7 = num6; short num8 = num5; if (num7 > num8) { break; } IL_12F: num2 = 24; array[(int)num6] = CAD.AddEnt(this.entity_0[(int)num6]).ObjectId; IL_153: num2 = 25; num6 += 1; } IL_167: num2 = 26; if (!flag) { goto IL_179; } IL_16E: num2 = 27; Class36.smethod_55(array); IL_179: goto IL_253; IL_17E: int num9 = num10 + 1; num10 = 0; @switch(ICSharpCode.Decompiler.ILAst.ILLabel[], num9); IL_20A: goto IL_248; IL_20C: num10 = num2; if (num <= -2) { goto IL_17E; } @switch(ICSharpCode.Decompiler.ILAst.ILLabel[], num); IL_225 :; } catch when(endfilter(obj is Exception & num != 0 & num10 == 0)) { Exception ex = (Exception)obj2; goto IL_20C; } IL_248: throw ProjectData.CreateProjectError(-2146828237); IL_253: if (num10 != 0) { ProjectData.ClearProjectError(); } }
protected PromptDialog(string promptMessage, PromptResult prompResult, ILogger logger) : base(logger) { _promptMessage = promptMessage; _prompResult = prompResult; }
public void OHDBlank() { try { // Get the current document and database Document acDoc = Application.DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; pointOptions = new PromptPointOptions(""); flaPoint = new Point3d(flagPoint); //Getting lower corner point Point3d gtPoint = GetPoint("Please select the inside corner point :"); if (gtPoint == flaPoint) { return; } Point3d cornerPointInRev = gtPoint; //Getting upper corner point gtPoint = GetPoint("Please select the any point on outside line :"); if (gtPoint == flaPoint) { return; } Point3d cornerPointOutRev = gtPoint; PromptStringOptions stringPrompt = new PromptStringOptions("\nEnter the start distance from inside corner :"); stringPrompt.AllowSpaces = false; //start distance PromptResult distanceString = ed.GetString(stringPrompt); if (distanceString.Status != PromptStatus.OK && decimal.TryParse(distanceString.StringResult, out _)) { return; } decimal startDistance; decimal.TryParse(distanceString.StringResult, out startDistance); //door width stringPrompt.Message = "\nEnter the trimming width :"; distanceString = ed.GetString(stringPrompt); if (distanceString.Status != PromptStatus.OK && decimal.TryParse(distanceString.StringResult, out _)) { return; } decimal.TryParse(distanceString.StringResult, out trimWidth); //Getting direction gtPoint = GetPoint("Select the direction "); if (gtPoint == flaPoint) { return; } Point3d directionPoint = gtPoint; direction = GetDirection(cornerPointInRev, directionPoint); //Wall offset calc double wallOffset = Math.Abs(cornerPointOutRev.Y - cornerPointInRev.Y); ed.WriteMessage("\noffset distance :" + wallOffset); //Getting wall lines Line outsideLine = new Line(); Line insideLine = new Line(); using (Transaction tr = acCurDb.TransactionManager.StartTransaction()) { // Open the Block table for read BlockTable acBlkTbl; acBlkTbl = tr.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; // Open the Block table record Model space for write BlockTableRecord acBlkTblRec; acBlkTblRec = tr.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; // Request for objects to be selected in the drawing area PromptSelectionOptions promptSelectionOptions = new PromptSelectionOptions(); promptSelectionOptions.MessageForAdding = "\nSelect Outside && inside line and press enter"; PromptSelectionResult SSPrompt = acDoc.Editor.GetSelection(promptSelectionOptions); //SelectionSet selectionSet = SSPrompt.Value; //Line outsideLine = new Line(); //Line insideLine = new Line(); if (SSPrompt.Status == PromptStatus.OK && SSPrompt.Value.Count == 2) { foreach (ObjectId id in SSPrompt.Value.GetObjectIds()) { if (id.ObjectClass.DxfName == "LINE") { Line tempL = tr.GetObject(id, OpenMode.ForWrite) as Line; if (IsPointOnPolyline(ConvertToPolyline(tempL), cornerPointInRev)) { insideLine = tr.GetObject(id, OpenMode.ForWrite) as Line; } else if (IsPointOnPolyline(ConvertToPolyline(tempL), cornerPointOutRev)) { outsideLine = tr.GetObject(id, OpenMode.ForWrite) as Line; } } } } else { ed.WriteMessage("\nCancelled or selected more than two line"); return; } //Trim operation Point3d lineStartPoint = insideLine.StartPoint; Point3d lineEndPoint = insideLine.EndPoint; Polyline polyl = ConvertToPolyline(outsideLine); //Calculate trimming points Point3d inTrimStart = new Point3d(), inTrimEnd = new Point3d(), outTrimStart = new Point3d(), outTrimEnd = new Point3d(); switch (direction) { case direction.right: inTrimStart = new Point3d(cornerPointInRev.X + Convert.ToDouble(startDistance), cornerPointInRev.Y, 0); inTrimEnd = new Point3d(inTrimStart.X + Convert.ToDouble(trimWidth), cornerPointInRev.Y, 0); outTrimStart = new Point3d(inTrimStart.X, cornerPointOutRev.Y, 0); outTrimEnd = new Point3d(inTrimEnd.X, cornerPointOutRev.Y, 0); break; case direction.left: inTrimStart = new Point3d(cornerPointInRev.X - Convert.ToDouble(startDistance), cornerPointInRev.Y, 0); inTrimEnd = new Point3d(inTrimStart.X - Convert.ToDouble(trimWidth), cornerPointInRev.Y, 0); outTrimStart = new Point3d(inTrimStart.X, cornerPointOutRev.Y, 0); outTrimEnd = new Point3d(inTrimEnd.X, cornerPointOutRev.Y, 0); break; case direction.top: inTrimStart = new Point3d(cornerPointInRev.X, cornerPointInRev.Y + Convert.ToDouble(startDistance), 0); inTrimEnd = new Point3d(cornerPointInRev.X, inTrimStart.Y + Convert.ToDouble(trimWidth), 0); outTrimStart = new Point3d(cornerPointOutRev.X, inTrimStart.Y, 0); outTrimEnd = new Point3d(cornerPointOutRev.X, inTrimEnd.Y, 0); break; case direction.bottom: inTrimStart = new Point3d(cornerPointInRev.X, cornerPointInRev.Y - Convert.ToDouble(startDistance), 0); inTrimEnd = new Point3d(cornerPointInRev.X, inTrimStart.Y - Convert.ToDouble(trimWidth), 0); outTrimStart = new Point3d(cornerPointOutRev.X, inTrimStart.Y, 0); outTrimEnd = new Point3d(cornerPointOutRev.X, inTrimEnd.Y, 0); break; } Line tempLine = new Line(lineStartPoint, inTrimStart); if (IsPointOnPolyline(ConvertToPolyline(tempLine), inTrimEnd)) { Point3d tempPoint = lineStartPoint; lineStartPoint = lineEndPoint; lineEndPoint = tempPoint; } Line line1 = new Line(lineStartPoint, inTrimStart); Line line2 = new Line(inTrimEnd, lineEndPoint); line1.SetDatabaseDefaults(); line2.SetDatabaseDefaults(); polyl.SetDatabaseDefaults(); acBlkTblRec.AppendEntity(line1); acBlkTblRec.AppendEntity(line2); acBlkTblRec.AppendEntity(polyl); tr.AddNewlyCreatedDBObject(line1, true); tr.AddNewlyCreatedDBObject(line2, true); tr.AddNewlyCreatedDBObject(polyl, true); //Upperline trim lineStartPoint = outsideLine.StartPoint; lineEndPoint = outsideLine.EndPoint; Polyline polyl2 = ConvertToPolyline(outsideLine); //Need to check trimStartPoint and trimEndPoint lies into the line or not if (!(IsPointOnPolyline(polyl2, outTrimStart) && IsPointOnPolyline(polyl2, outTrimEnd))) { ed.WriteMessage("\nTrim startpoint and endpoint are not on the line to trim"); return; } tempLine = new Line(lineStartPoint, outTrimStart); if (IsPointOnPolyline(ConvertToPolyline(tempLine), outTrimEnd)) { Point3d tempPoint = lineStartPoint; lineStartPoint = lineEndPoint; lineEndPoint = tempPoint; } Line line3 = new Line(lineStartPoint, outTrimStart); Line line4 = new Line(outTrimEnd, lineEndPoint); line3.SetDatabaseDefaults(); line4.SetDatabaseDefaults(); polyl.SetDatabaseDefaults(); polyl2.SetDatabaseDefaults(); acBlkTblRec.AppendEntity(line3); acBlkTblRec.AppendEntity(line4); acBlkTblRec.AppendEntity(polyl2); tr.AddNewlyCreatedDBObject(line3, true); tr.AddNewlyCreatedDBObject(line4, true); tr.AddNewlyCreatedDBObject(polyl2, true); //Delete the base line to complete trimming operation polyl.Erase(); polyl2.Erase(); outsideLine.Erase(); insideLine.Erase(); //Add two more line connecting four trimming points Line startTrimConnection = new Line(inTrimStart, outTrimStart); Line endTrimConnection = new Line(inTrimEnd, outTrimEnd); startTrimConnection.SetDatabaseDefaults(); endTrimConnection.SetDatabaseDefaults(); acBlkTblRec.AppendEntity(startTrimConnection); acBlkTblRec.AppendEntity(endTrimConnection); tr.AddNewlyCreatedDBObject(startTrimConnection, true); tr.AddNewlyCreatedDBObject(endTrimConnection, true); ed.Regen(); tr.Commit(); ed.Regen(); } }catch { ed.WriteMessage("Invalid Operation. Try Again"); } //Point3d insertionPoint = GetPoint("Select window block insertion point"); //Point3d modifiedPos = new Point3d(insertionPoint.X + 905, insertionPoint.Y - 544, 0); //InsertBlock(modifiedPos, "OHD Window"); }
public static void CopyTree() { try { StructuresExtensionApplication.Current.Logger.LogCommand(typeof(TreeRingCommands), nameof(CopyTree)); Document acDoc = Application.DocumentManager.MdiActiveDocument; using (Transaction acTrans = acDoc.TransactionManager.StartTransaction()) { PromptStringOptions pStrOptsPlot = new PromptStringOptions("\nEnter tree ID: ") { AllowSpaces = false }; PromptResult pStrResPlot = acDoc.Editor.GetString(pStrOptsPlot); if (pStrResPlot.Status != PromptStatus.OK) { acTrans.Abort(); return; } string id = pStrResPlot.StringResult; TreeRingManager treeRingManager = DataService.Current.GetStore <StructureDocumentStore>(acDoc.Name).GetManager <TreeRingManager>(); Tree treeToBeCopied = treeRingManager.ManagedObjects.FirstOrDefault(t => t.ID == id); if (treeToBeCopied == null) { StructuresExtensionApplication.Current.Logger.Entry($"No tree found matching ID {id}", Severity.Warning); acTrans.Abort(); return; } PromptPointOptions pPtOpts = new PromptPointOptions("\nEnter location: "); PromptPointResult pPtRes = acDoc.Editor.GetPoint(pPtOpts); while (pPtRes.Status == PromptStatus.OK) { Tree newTree = new Tree { Height = treeToBeCopied.Height, Phase = treeToBeCopied.Phase, Species = treeToBeCopied.Species, TreeType = treeToBeCopied.TreeType, WaterDemand = treeToBeCopied.WaterDemand, ID = treeRingManager.ManagedObjects.Count.ToString(), Location = new Point3d(pPtRes.Value.X, pPtRes.Value.Y, 0) }; newTree.AddLabel(); treeRingManager.AddTree(newTree); acDoc.TransactionManager.QueueForGraphicsFlush(); pPtRes = acDoc.Editor.GetPoint(pPtOpts); } acTrans.Commit(); } } catch (System.Exception e) { StructuresExtensionApplication.Current.Logger.LogException(e); throw; } }
WblockObjects1() { m_db = Utils.Db.GetCurDwg(); if (m_db == null) { return; } PromptKeywordOptions prOpts = new PromptKeywordOptions("\nWblock a block or objects"); prOpts.Keywords.Add("Block", "Block", "Block", true, true); prOpts.Keywords.Add("Objects", "Objects", "Objects", true, true); Editor ed = AcadApp.Application.DocumentManager.MdiActiveDocument.Editor; PromptResult prRes = ed.GetKeywords(prOpts); if (prRes.Status != PromptStatus.OK) { return; } Database db = null; using (TransactionHelper trHlp = new TransactionHelper(m_db)) { trHlp.Start(); ObjectIdCollection objIds; if (!Utils.AcadUi.GetSelSetFromUser(out objIds)) { return; } if (prRes.StringResult == "Block") { if (objIds.Count > 1) { ed.WriteMessage("\nSelect only one block"); return; } DBObject obj = trHlp.Transaction.GetObject(objIds[0], OpenMode.ForRead); BlockReference bRef = obj as BlockReference; if (bRef != null) { db = m_db.Wblock(bRef.BlockTableRecord); } } if (prRes.StringResult == "Objects") { db = m_db.Wblock(objIds, new Point3d(0, 0, 0)); } trHlp.Commit(); } if (db == null) { return; } using (TransactionHelper trHlp = new TransactionHelper(db)) { trHlp.Start(); Snoop.Forms.Database dbForm = new MgdDbg.Snoop.Forms.Database(db, trHlp); dbForm.Text = "Destination Database (In memory only)"; dbForm.ShowDialog(); trHlp.Commit(); } }
public void QB() { PromptEntityOptions selectCalloutOptions; PromptEntityResult selectedCalloutResults; BlockReference blkRef = null; string msAndKwds; string kwds; string verbose = "default"; //string station; string lineNumber; //need editor to prompt user Editor ed = doc.Editor; //Prompt options for running line PromptNestedEntityOptions promptRunningLineOpt = new PromptNestedEntityOptions("\nSelect Running Line"); promptRunningLineOpt.AllowNone = false; PromptNestedEntityResult runningLineResults = ed.GetNestedEntity(promptRunningLineOpt); if (runningLineResults.Status != PromptStatus.OK) { ed.WriteMessage("\nThe selected object is not running line"); return; } //prompt for line number PromptStringOptions pStrOpts = new PromptStringOptions("\nEnter Line Number: "); pStrOpts.AllowSpaces = false; PromptResult pStrRes = ed.GetString(pStrOpts); //prompt user to select object only allow DFWT blocks PromptEntityOptions peo = new PromptEntityOptions("\nSelect DFWT Block"); //check prompt results from user else return PromptEntityResult per = ed.GetEntity(peo); if (per.Status != PromptStatus.OK) { return; } while (true) { // Transaction trans = database.TransactionManager.StartTransaction(); using (trans) { //access block table and create block table record BlockTable bt = trans.GetObject(database.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; //get the running line Polyline runningLine = trans.GetObject(runningLineResults.ObjectId, OpenMode.ForRead) as Polyline; //get the block reference //Entity nestedBlockEntity = trans.GetObject(per.ObjectId, OpenMode.ForRead) as Entity; //try { //BlockReference blkRef = trans.GetObject(per.ObjectId, OpenMode.ForRead) as BlockReference; //} //catch //{ //} // ObjectId[] containerIds = per.GetContainers(); // foreach (ObjectId id in containerIds) // { //DBObject container = trans.GetObject(id, OpenMode.ForRead); //if (container is BlockReference) //{ // blkRef = container as BlockReference; //} // } try { Entity entity = trans.GetObject(per.ObjectId, OpenMode.ForRead) as Entity; blkRef = trans.GetObject(per.ObjectId, OpenMode.ForRead) as BlockReference; } catch (InvalidCastException) { ed.WriteMessage("error when selecting block"); } string str = String.Format("{0:0}", runningLine.GetDistAtPoint(blkRef.Position)); switch (str.Length) { case 1: str = "0+0" + str; break; case 2: str = "0+" + str; break; default: str = str.Substring(0, str.Length - 2) + "+" + str.Substring(str.Length - 2); break; } if (pStrRes.StringResult != "") { str = str + " LINE " + pStrRes.StringResult; } // switch (blkRef.BlockName.ToUpper()) { case "CPR": msAndKwds = "\nSelect Type:[Drop Bucket/Tap pedestal/ Splitter Pedestal]"; kwds = "'Drop Bucket' 'Tap Pedestal' 'Tap Splitter'"; selectCalloutOptions = new PromptEntityOptions(msAndKwds, kwds); selectedCalloutResults = ed.GetEntity(selectCalloutOptions); switch (selectedCalloutResults.StringResult.ToUpper()) { case "DROP BUCKET": verbose = DROP_BUCKET; break; case "TAP PEDESTAL": verbose = TAP_PED; break; default: break; } break; case "CPS": break; default: ed.WriteMessage(blkRef.BlockName); break; } //.string msAndKwds = "\nCPR or [A/B/C]"; //string kwds = "Apple Bob Cat"; //peo.SetMessageAndKeywords(msAndKwds, kwds); //ed.WriteMessage(per1.StringResult); /************************************************************************************************ * Prompting for callout box insertion point * Set geometry for placing box ***********************************************************************************************/ PromptPointOptions pPtOpt = new PromptPointOptions("\nEnter Insertion Point"); PromptPointResult pPtRes = ed.GetPoint(pPtOpt); Point3d insPt = pPtRes.Value; CoordinateSystem3d cs = Application.DocumentManager.MdiActiveDocument.Editor.CurrentUserCoordinateSystem.CoordinateSystem3d; Plane plane = new Plane(Point3d.Origin, cs.Zaxis); //create polyline Polyline rec = new Polyline(); rec.AddVertexAt(0, insPt.Convert2d(plane), 0, 0, 0); bool Xdir = true; bool Ydir = true; if (insPt.X < blkRef.Position.X) { Xdir = false; } // if (insPt.Y < blkRef.Position.Y) { Ydir = false; } if (Xdir) { if (Ydir) { //quadrant I rec.AddVertexAt(0, new Point2d(insPt.X + recLength, insPt.Y), 0, 0, 0); rec.AddVertexAt(1, new Point2d(insPt.X + recLength, insPt.Y + recWidth), 0, 0, 0); rec.AddVertexAt(2, new Point2d(insPt.X, insPt.Y + recWidth), 0, 0, 0); } else { //quadrant IV rec.AddVertexAt(0, new Point2d(insPt.X + recLength, insPt.Y), 0, 0, 0); rec.AddVertexAt(1, new Point2d(insPt.X + recLength, insPt.Y - recWidth), 0, 0, 0); rec.AddVertexAt(2, new Point2d(insPt.X, insPt.Y - recWidth), 0, 0, 0); } } else { if (Ydir) { //quadrant II rec.AddVertexAt(0, new Point2d(insPt.X - recLength, insPt.Y), 0, 0, 0); rec.AddVertexAt(1, new Point2d(insPt.X - recLength, insPt.Y + recWidth), 0, 0, 0); rec.AddVertexAt(2, new Point2d(insPt.X, insPt.Y + recWidth), 0, 0, 0); } else { //quadrant III rec.AddVertexAt(0, new Point2d(insPt.X - recLength, insPt.Y), 0, 0, 0); rec.AddVertexAt(1, new Point2d(insPt.X - recLength, insPt.Y - recWidth), 0, 0, 0); rec.AddVertexAt(2, new Point2d(insPt.X, insPt.Y - recWidth), 0, 0, 0); } } rec.Closed = true; rec.SetDatabaseDefaults(); /************************************************************************************************ * Add object to block table and Commit Transaction * ***********************************************************************************************/ MText mt = new MText(); mt.Contents = verbose; btr.AppendEntity(rec); btr.AppendEntity(mt); trans.AddNewlyCreatedDBObject(rec, true); trans.AddNewlyCreatedDBObject(mt, true); trans.Commit(); } } }
private async void btnSave_Clicked(object sender, EventArgs e) { if (qList.Count == 0) { await DisplayAlert("", "カラーを選択して下さい", "確定"); return; } if (seletedimg == null) { return; } PromptResult promptResult = await UserDialogs.Instance.PromptAsync("保存タイトル名", "iroaiリスト", "保存", "キャンセル", "", InputType.Name); if (promptResult.Ok) { string sTitle = promptResult.Text; List <CataLogInfo> catologInfoList = await SqliteUtil.Current.QueryCataLogsByTitle(sTitle); if (catologInfoList.Count > 0) { await DisplayAlert("", "保存名称が重複しています。", "確定"); return; } arrayList.Clear(); _listinfo.Clear(); arrayList.AddRange(qList); lock (arrayList.SyncRoot) { for (int k = 0; k < arrayList.Count; k++) { _listinfo.Add(arrayList[k] as ImageColorInfo); } } string docDir = DirectoryUtil.Current.GetDir(); using (SKImage image = SKImage.FromBitmap(bitmap)) { using (UserDialogs.Instance.Loading("保存中", null, null, true, MaskType.Black)) { await Task.Delay(2000); SKData data = image.Encode(); DateTime dt = DateTime.Now; string filename = String.Format("{0:D4}{1:D2}{2:D2}-{3:D2}{4:D2}{5:D2}{6:D3}.png", dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, dt.Millisecond); //_ImagePath = Path.Combine(Path.Combine(docDir, "Iroai"), filename); if (!string.IsNullOrWhiteSpace(sTitle)) { OnSaveTitle(sTitle, data); } else { await DisplayAlert("", "保存名称を入力して下さい。", "確定"); } } } } }
/// <summary>Constructor.</summary> public PromptButtonClickEventArgs(PromptResult buttonType) { ButtonType = buttonType; }
private Task<PromptResult<string>> internalPromptAsync(string message, string title, string defaultText, bool password) { var tcs = new TaskCompletionSource<PromptResult<string>>(); Guide.BeginShowKeyboardInput(PlayerIndex.One, title, message, defaultText, result => { var str = Guide.EndShowKeyboardInput(result); var promptResult = new PromptResult<string>(str != null, str); tcs.SetResult(promptResult); }, null, password); return tcs.Task; }
private void FireClick(PromptResult button) { if (Click != null) Click(this, new PromptButtonClickEventArgs(button)); }
private IButton CreateButton(PromptResult type) { var item = new ButtonItem { Button = importer.ButtonFactory.CreateExport().Value, Type = type, }; item.Button.Click += delegate { FireClick(item.Type); }; buttons.Add(item); return item.Button; }
public IButton GetButton(PromptResult buttonType) { switch (buttonType) { case PromptResult.Accept:return AcceptButton; case PromptResult.Decline: return DeclineButton; case PromptResult.Cancel: return CancelButton; case PromptResult.Back: return BackButton; case PromptResult.Next: return NextButton; default: throw new NotSupportedException(buttonType.ToString()); } }
public static void NRL() { try { // Current AutoCAD Document, Database and Editor. Autodesk.AutoCAD.ApplicationServices.Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; // Get running Visual Studio instances (using helper class). IDictionary <string, _DTE> vsInstances = RunningObjectTable.GetRunningVSIDETable(); // Check for no Visual Studio instances. if (vsInstances.Count == 0) { ed.WriteMessage("\nNo running Visual Studio instances were found. *Cancel*"); return; } // Create list of solution names. List <string> solNames = new List <string>(); foreach (KeyValuePair <string, _DTE> item in vsInstances) { solNames.Add(Path.GetFileNameWithoutExtension(item.Value.Solution.FullName)); } // Check if all solution names equal "". // i.e. no solutions loaded in any of the Visual Studio instances. bool allSolNamesEmpty = true; foreach (string name in solNames) { if (name != "") { allSolNamesEmpty = false; break; } } if (allSolNamesEmpty == true) { ed.WriteMessage("\nNo active Visual Studio solutions were found. *Cancel*"); return; } // Prompt user to select solution. PromptKeywordOptions pko = new PromptKeywordOptions("\nSelect Visual Studio instance to increment:"); pko.AllowNone = false; foreach (string name in solNames) { if (name != "") { pko.Keywords.Add(name); } } if (defaultKeyword == "" || solNames.Contains(defaultKeyword) == false) { int index = 0; while (solNames[index] == "") { index++; } pko.Keywords.Default = solNames[index]; } else { pko.Keywords.Default = defaultKeyword; } PromptResult pr = ed.GetKeywords(pko); if (pr.Status != PromptStatus.OK) { return; } defaultKeyword = pr.StringResult; // Use prompt result to set Visual Studio instance variable. _DTE dte = vsInstances.ElementAt(solNames.IndexOf(pr.StringResult)).Value; // Use custom WaitCursor class for long operation. using (WaitCursor wc = new WaitCursor()) { // Active Visual Studio Document. EnvDTE.Document vsDoc = dte.ActiveDocument; if (vsDoc == null) { ed.WriteMessage(String.Format("\nNo active document found for the '{0}' solution. *Cancel*", pr.StringResult)); return; } // Active Visual Studio Project. Project prj = vsDoc.ProjectItem.ContainingProject; // Debug directory - i.e. \bin\Debug. string debugDir = prj.FullName; debugDir = Path.GetDirectoryName(debugDir); debugDir = Path.Combine(debugDir, @"bin\Debug"); // NetReload directory - i.e. \bin\Debug\NetReload. string netReloadDir = Path.Combine(debugDir, "NetReload"); // Create NetReload directory if it doens't exist. if (Directory.Exists(netReloadDir) == false) { Directory.CreateDirectory(netReloadDir); } // Temporary random assembly file name (check it doesn't already exist). string tempAssemblyName; do { tempAssemblyName = Path.GetRandomFileName(); } while (File.Exists(Path.Combine(netReloadDir, tempAssemblyName + ".dll"))); // Project's initial "AssemblyName" property setting. string initAssemblyName = prj.Properties.Item("AssemblyName").Value as string; // Set project's "AssemblyName" property to temp value. prj.Properties.Item("AssemblyName").Value = tempAssemblyName; // Build solution. SolutionBuild solBuild = dte.Solution.SolutionBuild; solBuild.Build(true); // Re-set project's "AssemblyName" property back to initial value. prj.Properties.Item("AssemblyName").Value = initAssemblyName; // Check if build was successful. // # Note: LastBuildInfo property reports number of projects in the solution that failed to build. if (solBuild.LastBuildInfo != 0) { ed.WriteMessage(String.Format("\nBuild failed for the '{0}' solution. *Cancel*", pr.StringResult)); return; } // Move new assembly (.dll) from Debug directory to NetReload directory. File.Move( Path.Combine(debugDir, tempAssemblyName + ".dll"), Path.Combine(netReloadDir, tempAssemblyName + ".dll") ); // Move new .pdb file from Debug directory to NetReload directory. File.Move( Path.Combine(debugDir, tempAssemblyName + ".pdb"), Path.Combine(netReloadDir, tempAssemblyName + ".pdb") ); // NETLOAD new assembly file. System.Reflection.Assembly.LoadFrom(Path.Combine(netReloadDir, tempAssemblyName + ".dll")); // Output summary. ed.WriteMessage("\nNETRELOAD complete for {0}.dll.", initAssemblyName); } } catch (Autodesk.AutoCAD.Runtime.Exception ex) { // Catch AutoCAD exception. Application.ShowAlertDialog(String.Format("ERROR" + "\nMessage: {0}\nErrorStatus: {1}", ex.Message, ex.ErrorStatus)); } catch (System.Exception ex) { // Catch Windows exception. Application.ShowAlertDialog(String.Format("ERROR" + "\nMessage: {0}", ex.Message)); } }
//public override void DateTimePrompt(DateTimePromptConfig config) { // var sheet = new ActionSheetDatePicker { // Title = config.Title, // DoneText = config.OkText // }; // switch (config.SelectionType) { // case DateTimeSelectionType.Date: // sheet.DatePicker.Mode = UIDatePickerMode.Date; // break; // case DateTimeSelectionType.Time: // sheet.DatePicker.Mode = UIDatePickerMode.Time; // break; // case DateTimeSelectionType.DateTime: // sheet.DatePicker.Mode = UIDatePickerMode.DateAndTime; // break; // } // if (config.MinValue != null) // sheet.DatePicker.MinimumDate = config.MinValue.Value; // if (config.MaxValue != null) // sheet.DatePicker.MaximumDate = config.MaxValue.Value; // sheet.DateTimeSelected += (sender, args) => { // // TODO: stop adjusting date/time // config.OnResult(new DateTimePromptResult(sheet.DatePicker.Date)); // }; // var top = Utils.GetTopView(); // sheet.Show(top); // //sheet.DatePicker.MinuteInterval //} //public override void DurationPrompt(DurationPromptConfig config) { // var sheet = new ActionSheetDatePicker { // Title = config.Title, // DoneText = config.OkText // }; // sheet.DatePicker.Mode = UIDatePickerMode.CountDownTimer; // sheet.DateTimeSelected += (sender, args) => config.OnResult(new DurationPromptResult(args.TimeOfDay)); // var top = Utils.GetTopView(); // sheet.Show(top); //} public override void Prompt(PromptConfig config) { Device.BeginInvokeOnMainThread(() => { var result = new PromptResult(); var dlg = new UIAlertView(config.Title ?? String.Empty, config.Message, null, config.CancelText, config.OkText) { AlertViewStyle = config.IsSecure ? UIAlertViewStyle.SecureTextInput : UIAlertViewStyle.PlainTextInput }; var txt = dlg.GetTextField(0); txt.SecureTextEntry = config.IsSecure; txt.Placeholder = config.Placeholder; //UITextView = editable dlg.Clicked += (s, e) => { result.Ok = (dlg.CancelButtonIndex != e.ButtonIndex); result.Text = txt.Text; config.OnResult(result); }; dlg.Show(); }); }
public void project() { /* * int userInput_a = 10; * int userInput_b = 5; * int userInput_c = 2; * int length = 10; * int distance = 2; */ Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor edt = doc.Editor; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Takeing "a" value PromptStringOptions prompt_a = new PromptStringOptions("Enter a value: "); prompt_a.AllowSpaces = true; //get the results of the user input using a PromptResult PromptResult result_a = edt.GetString(prompt_a); string name_a = result_a.StringResult; int userInput_a = Int16.Parse(name_a); edt.WriteMessage("a Value: " + userInput_a + " "); /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Takeing "b" value PromptStringOptions prompt_b = new PromptStringOptions("Enter b value: "); prompt_b.AllowSpaces = true; //get the results of the user input using b PromptResult PromptResult result_b = edt.GetString(prompt_b); string name_b = result_b.StringResult; int userInput_b = Int16.Parse(name_b); edt.WriteMessage("b Value: " + userInput_b + " "); /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Takeing "c" value PromptStringOptions prompt_c = new PromptStringOptions("Enter c value: "); prompt_b.AllowSpaces = true; //get the results of the user input using b PromptResult PromptResult result_c = edt.GetString(prompt_c); string name_c = result_c.StringResult; int userInput_c = Int16.Parse(name_c); edt.WriteMessage("c Value: " + userInput_c + " "); /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Takeing lenth value PromptStringOptions prompt_length = new PromptStringOptions("Enter the length: "); prompt_length.AllowSpaces = true; //get the results of the user input using b PromptResult PromptResult result_length = edt.GetString(prompt_length); string name_length = result_length.StringResult; int length = Int16.Parse(name_length); edt.WriteMessage("length: " + length + " "); ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Takeing Distance value PromptStringOptions prompt_distance = new PromptStringOptions("Enter the distance: "); prompt_distance.AllowSpaces = true; //get the results of the user input using b PromptResult PromptResult result_distance = edt.GetString(prompt_distance); string name_distance = result_distance.StringResult; int distance = Int16.Parse(name_distance); edt.WriteMessage("distance: " + distance + " "); for (int i = distance; i <= length; i += distance) { Point3d line_01_pt_01 = new Point3d(0, i, 0); Point3d line_01_pt_02 = new Point3d(0, i, userInput_a); Point3d line_01_pt_03 = new Point3d(userInput_b / 2, i, userInput_a + userInput_c); Point3d line_01_pt_04 = new Point3d(userInput_b, i, userInput_a); Point3d line_01_pt_05 = new Point3d(userInput_b, i, 0); //Line 01: Horizontal using (Transaction trans = db.TransactionManager.StartTransaction()) { try { BlockTable bt; bt = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord btr; btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; //Point3d line_01_pt_01 = new Point3d(0, i, 0); //Point3d line_01_pt_02 = new Point3d(0,i, userInput_a); Point3d point_01 = new Point3d(0, i - distance, 0); Line line_01_h = new Line(line_01_pt_01, point_01); btr.AppendEntity(line_01_h); trans.AddNewlyCreatedDBObject(line_01_h, true); trans.Commit(); } catch (System.Exception ex) { edt.WriteMessage("Error Encountered:" + ex); trans.Abort(); } } //Line 02 //Line 02: Horizontal using (Transaction trans = db.TransactionManager.StartTransaction()) { try { BlockTable bt; bt = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord btr; btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; //Point3d line_01_pt_01 = new Point3d(0, i, 0); //Point3d line_01_pt_02 = new Point3d(0,i, userInput_a); Point3d point_02 = new Point3d(0, i - distance, userInput_a); Line line_02_h = new Line(line_01_pt_02, point_02); btr.AppendEntity(line_02_h); trans.AddNewlyCreatedDBObject(line_02_h, true); trans.Commit(); } catch (System.Exception ex) { edt.WriteMessage("Error Encountered:" + ex); trans.Abort(); } } //Line 03: Horizontal using (Transaction trans = db.TransactionManager.StartTransaction()) { try { BlockTable bt; bt = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord btr; btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; //Point3d line_01_pt_01 = new Point3d(0, i, 0); //Point3d line_01_pt_02 = new Point3d(0,i, userInput_a); Point3d point_03 = new Point3d(userInput_b / 2, i - distance, userInput_a + userInput_c); Line line_03_h = new Line(line_01_pt_03, point_03); btr.AppendEntity(line_03_h); trans.AddNewlyCreatedDBObject(line_03_h, true); trans.Commit(); } catch (System.Exception ex) { edt.WriteMessage("Error Encountered:" + ex); trans.Abort(); } } //Line 04: Horizontal using (Transaction trans = db.TransactionManager.StartTransaction()) { try { BlockTable bt; bt = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord btr; btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; //Point3d line_01_pt_01 = new Point3d(0, i, 0); //Point3d line_01_pt_02 = new Point3d(0,i, userInput_a); Point3d point_04 = new Point3d(userInput_b, i - distance, userInput_a); Line line_04_h = new Line(line_01_pt_04, point_04); btr.AppendEntity(line_04_h); trans.AddNewlyCreatedDBObject(line_04_h, true); trans.Commit(); } catch (System.Exception ex) { edt.WriteMessage("Error Encountered:" + ex); trans.Abort(); } } //Line 05: Horizontal using (Transaction trans = db.TransactionManager.StartTransaction()) { try { BlockTable bt; bt = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord btr; btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; //Point3d line_01_pt_01 = new Point3d(0, i, 0); //Point3d line_01_pt_02 = new Point3d(0,i, userInput_a); Point3d point_05 = new Point3d(userInput_b, i - distance, 0); Line line_05_h = new Line(line_01_pt_05, point_05); btr.AppendEntity(line_05_h); trans.AddNewlyCreatedDBObject(line_05_h, true); trans.Commit(); } catch (System.Exception ex) { edt.WriteMessage("Error Encountered:" + ex); trans.Abort(); } } //Line 01 using (Transaction trans = db.TransactionManager.StartTransaction()) { try { BlockTable bt; bt = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord btr; btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; //Point3d line_01_pt_01 = new Point3d(0, i, 0); //Point3d line_01_pt_02 = new Point3d(0,i, userInput_a); Line line_01 = new Line(line_01_pt_01, line_01_pt_02); btr.AppendEntity(line_01); trans.AddNewlyCreatedDBObject(line_01, true); trans.Commit(); } catch (System.Exception ex) { edt.WriteMessage("Error Encountered:" + ex); trans.Abort(); } } //Line 02 using (Transaction trans = db.TransactionManager.StartTransaction()) { try { BlockTable bt; bt = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord btr; btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; //Point3d line_01_pt_02 = new Point3d(0, i, userInput_a); //Point3d line_01_pt_03 = new Point3d(userInput_b / 2, i, userInput_a + userInput_c); Line line_02 = new Line(line_01_pt_02, line_01_pt_03); btr.AppendEntity(line_02); trans.AddNewlyCreatedDBObject(line_02, true); trans.Commit(); } catch (System.Exception ex) { edt.WriteMessage("Error Encountered:" + ex); trans.Abort(); } } //Line 03 using (Transaction trans = db.TransactionManager.StartTransaction()) { try { BlockTable bt; bt = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord btr; btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; //Point3d line_01_pt_03 = new Point3d(userInput_b / 2, i, userInput_a + userInput_c); //Point3d line_01_pt_04 = new Point3d(userInput_b, i, userInput_a); Line line_03 = new Line(line_01_pt_03, line_01_pt_04); btr.AppendEntity(line_03); trans.AddNewlyCreatedDBObject(line_03, true); trans.Commit(); } catch (System.Exception ex) { edt.WriteMessage("Error Encountered:" + ex); trans.Abort(); } } //Line 04 using (Transaction trans = db.TransactionManager.StartTransaction()) { try { BlockTable bt; bt = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord btr; btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; //Point3d line_01_pt_04 = new Point3d(userInput_b, i, userInput_a); //Point3d line_01_pt_05 = new Point3d(userInput_b, i,0); Line line_04 = new Line(line_01_pt_04, line_01_pt_05); btr.AppendEntity(line_04); trans.AddNewlyCreatedDBObject(line_04, true); trans.Commit(); } catch (System.Exception ex) { edt.WriteMessage("Error Encountered:" + ex); trans.Abort(); } } } //First Frame //Line 01 using (Transaction trans = db.TransactionManager.StartTransaction()) { try { BlockTable bt; bt = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord btr; btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; Point3d line_01_pt_01 = new Point3d(0, 0, 0); Point3d line_01_pt_02 = new Point3d(0, 0, userInput_a); Line line_01 = new Line(line_01_pt_01, line_01_pt_02); btr.AppendEntity(line_01); trans.AddNewlyCreatedDBObject(line_01, true); trans.Commit(); } catch (System.Exception ex) { edt.WriteMessage("Error Encountered:" + ex); trans.Abort(); } } //Line 02 using (Transaction trans = db.TransactionManager.StartTransaction()) { try { BlockTable bt; bt = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord btr; btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; Point3d line_01_pt_02 = new Point3d(0, 0, userInput_a); Point3d line_01_pt_03 = new Point3d(userInput_b / 2, 0, userInput_a + userInput_c); Line line_02 = new Line(line_01_pt_02, line_01_pt_03); btr.AppendEntity(line_02); trans.AddNewlyCreatedDBObject(line_02, true); trans.Commit(); } catch (System.Exception ex) { edt.WriteMessage("Error Encountered:" + ex); trans.Abort(); } } //Line 03 using (Transaction trans = db.TransactionManager.StartTransaction()) { try { BlockTable bt; bt = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord btr; btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; Point3d line_01_pt_03 = new Point3d(userInput_b / 2, 0, userInput_a + userInput_c); Point3d line_01_pt_04 = new Point3d(userInput_b, 0, userInput_a); Line line_03 = new Line(line_01_pt_03, line_01_pt_04); btr.AppendEntity(line_03); trans.AddNewlyCreatedDBObject(line_03, true); trans.Commit(); } catch (System.Exception ex) { edt.WriteMessage("Error Encountered:" + ex); trans.Abort(); } } //Line 04 using (Transaction trans = db.TransactionManager.StartTransaction()) { try { BlockTable bt; bt = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord btr; btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; Point3d line_01_pt_04 = new Point3d(userInput_b, 0, userInput_a); Point3d line_01_pt_05 = new Point3d(userInput_b, 0, 0); Line line_04 = new Line(line_01_pt_04, line_01_pt_05); btr.AppendEntity(line_04); trans.AddNewlyCreatedDBObject(line_04, true); trans.Commit(); } catch (System.Exception ex) { edt.WriteMessage("Error Encountered:" + ex); trans.Abort(); } } }
public void fSLCF() { Editor ed = acApp.DocumentManager.MdiActiveDocument.Editor; try { Utils.Utils.Init(true); if (!Utils.Layers.CurrentLayer().Contains("!FDS_SLCF")) { Utils.Layers.SetLayerType("!FDS_SLCF"); } while (true) { PromptKeywordOptions orientationOptions = new PromptKeywordOptions("\nChoose orientation"); orientationOptions.Keywords.Add("Horizontal"); orientationOptions.Keywords.Add("Vertical"); orientationOptions.AllowNone = false; PromptResult orientation = ed.GetKeywords(orientationOptions); Extents3d ext = Utils.Utils.GetAllElementsBoundingBox(); if (orientation.Status != PromptStatus.OK || orientation.Status == PromptStatus.Cancel) { Utils.Utils.End(); return; } ; if (orientation.Status == PromptStatus.OK) { if (orientation.StringResult == "Vertical") { while (true) { PromptPointOptions p1Option = new PromptPointOptions("\nSpecify first point:"); p1Option.AllowNone = false; PromptPointResult p1 = ed.GetPoint(p1Option); if (p1.Status != PromptStatus.OK || p1.Status == PromptStatus.Cancel) { goto End; } PromptPointOptions p2Option = new PromptPointOptions("\nSpecify second point:"); p2Option.AllowNone = false; p2Option.UseBasePoint = true; p2Option.BasePoint = p1.Value; PromptPointResult p2 = ed.GetPoint(p2Option); if (p2.Status != PromptStatus.OK || p2.Status == PromptStatus.Cancel) { goto End; } Utils.Utils.CreateExtrudedSurface(new Point3d(p1.Value.X, p1.Value.Y, ext.MinPoint.Z), new Point3d(p2.Value.X, p2.Value.Y, ext.MaxPoint.Z)); } } else if (orientation.StringResult == "Horizontal") { while (true) { PromptDoubleOptions zlevelOption = new PromptDoubleOptions("Enter Z level (min: " + ext.MinPoint.Z + ", max: " + ext.MaxPoint.Z + ")"); zlevelOption.AllowNone = false; zlevelOption.DefaultValue = zSlcfOld; PromptDoubleResult zlevel = ed.GetDouble(zlevelOption); if (zlevel.Status != PromptStatus.OK || zlevel.Status == PromptStatus.Cancel) { goto End; } if (zlevel.Status == PromptStatus.OK) { zSlcfOld = zlevel.Value; } Utils.Utils.CreateExtrudedSurface(new Point3d(ext.MinPoint.X - (Utils.Utils.snapUnit[0] * 4), ext.MinPoint.Y - (Utils.Utils.snapUnit[1] * 4), zlevel.Value), new Point3d(ext.MaxPoint.X + (Utils.Utils.snapUnit[0] * 4), ext.MaxPoint.Y + (Utils.Utils.snapUnit[1] * 4), zlevel.Value)); } } } End :; } } catch (System.Exception e) { ed.WriteMessage("\nProgram exception: " + e.ToString()); } }
public static ObjectId Insert(string blockPath, string blockName, bool scaleBlock = false, Scale3d scaleFactor = default(Scale3d)) { ObjectId id = new ObjectId(); using (World.Docu.LockDocument()) { using (Database db = World.Docu.Database) { using (Transaction tr = db.TransactionManager.StartTransaction()) { using (BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead)) { if (AcadIO.Insert.DB.AddBlock(blockPath + "\\" + blockName) == false) { return(id); } using (BlockReference br = new BlockReference(Point3d.Origin, bt[blockName])) { PromptResult pr = World.Docu.Editor.Drag(new Jigs.InsertBlockJig(br)); if (pr.Status == PromptStatus.Cancel | pr.Status == PromptStatus.Error | pr.Status == PromptStatus.None) { return(id); } pr = World.Docu.Editor.Drag(new Jigs.RotateBlockJig(br)); if (pr.Status == PromptStatus.Cancel | pr.Status == PromptStatus.Error | pr.Status == PromptStatus.None) { return(id); } using (BlockTableRecord drawingSpace = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite)) { if (scaleBlock == true) { //br.ScaleFactors = new Autodesk.AutoCAD.Geometry.Scale3d(World.UnitFactor); br.ScaleFactors = scaleFactor; } drawingSpace.AppendEntity(br); tr.AddNewlyCreatedDBObject(br, true); if (AcadIO.Layers.IsObjectLayerLocked(br.ObjectId)) { World.Docu.Editor.WriteMessage(Environment.NewLine + "BCAD: Cannot insert on locked layer" + Environment.NewLine); return(id); } using (BlockTableRecord attributeBlockTableRecord = (BlockTableRecord)tr.GetObject(br.BlockTableRecord, OpenMode.ForWrite)) { foreach (ObjectId attributeId in attributeBlockTableRecord) { if (attributeId.ObjectClass.Name == "AcDbAttributeDefinition") { using (AttributeDefinition attributedef = (AttributeDefinition)tr.GetObject(attributeId, OpenMode.ForWrite)) { AttributeReference attributeref = new AttributeReference(); attributeref.SetAttributeFromBlock(attributedef, br.BlockTransform); br.AttributeCollection.AppendAttribute(attributeref); tr.AddNewlyCreatedDBObject(attributeref, true); } } } } id = br.ObjectId; } } } tr.Commit(); } } } return(id); }
public void iCmd_CreateAcadPointsFromBuffer() { PromptKeywordOptions kwOpt = new PromptKeywordOptions("\nSelect"); kwOpt.AllowNone = false; kwOpt.Keywords.Add("FromText"); //kwOpt.Keywords.Add("FromExl"); kwOpt.Keywords.Add("FromAcadText"); //kwOpt.Keywords.Add("FromAcadMText"); PromptResult kwRes = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetKeywords(kwOpt); string data = ""; if (kwRes.Status != PromptStatus.OK) { return; } PromptIntegerOptions scaleOpt = new PromptIntegerOptions("\nSpecify the scale, 1: "); scaleOpt.UseDefaultValue = true; scaleOpt.DefaultValue = 1000; scaleOpt.AllowNegative = false; scaleOpt.AllowZero = false; scaleOpt.AllowNone = false; PromptIntegerResult scaleRes = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetInteger(scaleOpt); if (scaleRes.Status != PromptStatus.OK) { return; } double scale = scaleRes.Value / 1000d; PromptIntegerOptions digCountOpt = new PromptIntegerOptions("\nNumber of decimal places: "); digCountOpt.UseDefaultValue = true; digCountOpt.DefaultValue = 2; digCountOpt.AllowNegative = false; PromptIntegerResult digCountRes = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetInteger(digCountOpt); if (digCountRes.Status != PromptStatus.OK) { return; } PromptKeywordOptions groupingOpt = new PromptKeywordOptions("\nGroup data? : "); groupingOpt.AllowNone = false; groupingOpt.Keywords.Add("Yes"); groupingOpt.Keywords.Add("No"); groupingOpt.Keywords.Default = "Yes"; PromptResult groupingRes = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetKeywords(groupingOpt); if (groupingRes.Status != PromptStatus.OK) { return; } string lname = "__CLIPP" + "POINTS"; string lnameElev = lname + "__Elevations"; string lnameName = lname + "__Names"; Layers.LayerTools.CreateHiddenLayer(lname); Layers.LayerTools.CreateHiddenLayer(lnameElev); Layers.LayerTools.CreateHiddenLayer(lnameName); switch (kwRes.StringResult) { case "FromText": { data = System.Windows.Forms.Clipboard.GetText(); break; } /*case "FromExl": * { * var buff = System.Windows.Forms.Clipboard.GetData(System.Windows.Forms.DataFormats.CommaSeparatedValue.ToString()); * if (buff is String) * data = (String)buff; * break; * }*/ case "FromAcadText": { data = "\t" + _getDbTextString("\nSelect text", "is't DBText"); data += "\t" + _getDbTextString("\nSelect text", "is't DBText"); break; } default: return; } data = data.Replace(',', '.'); Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage(data); string[] lines = data.Split(new string[] { System.Environment.NewLine }, StringSplitOptions.None); System.Globalization.CultureInfo culture = System.Globalization.CultureInfo.GetCultureInfo("en-US"); using (Transaction trans = Tools.StartTransaction()) { BlockTable acBlkTbl; acBlkTbl = trans.GetObject(Application.DocumentManager.MdiActiveDocument.Database.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord acBlkTblRec; acBlkTblRec = trans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; int count = lines.Length; foreach (string l in lines) { string[] coords = l.Split(new char[] { '\t' }, StringSplitOptions.None); try { string name = coords[0]; double y = double.Parse(coords[1], culture); double x = double.Parse(coords[2], culture); double h = 0d; ObjectId nameId = ObjectId.Null; ObjectId pointId = ObjectId.Null; ObjectId elevId = ObjectId.Null; if (coords.Length > 3) { try { h = double.Parse(coords[3], culture); } catch { } if (coords[3].Length > 0) { string f = "#0"; if (digCountRes.Value > 0) { f = (f += ".").PadRight(f.Length + digCountRes.Value, '0'); } var text = _CreateText(new Point3d(x + 2d * scale, y, 0d), h.ToString(f), lnameElev, scale); elevId = acBlkTblRec.AppendEntity(text); trans.AddNewlyCreatedDBObject(text, true); } } DBPoint point = new DBPoint(new Point3d(x, y, h)); point.SetDatabaseDefaults(); point.Layer = lname; pointId = acBlkTblRec.AppendEntity(point); trans.AddNewlyCreatedDBObject(point, true); if (name.Length > 0) { var text = _CreateText(new Point3d(x + 2d * scale, y + 3.0d * scale, 0d), name, lnameName, scale); nameId = acBlkTblRec.AppendEntity(text); trans.AddNewlyCreatedDBObject(text, true); } if (groupingRes.StringResult == "Yes") { Group gr = new Group(); if (!nameId.IsNull) { gr.Append(nameId); } if (!elevId.IsNull) { gr.Append(elevId); } Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Database.AddDBObject(gr); trans.AddNewlyCreatedDBObject(gr, true); } } catch { count -= 1; } } Application.DocumentManager.MdiActiveDocument.Database.Pdmode = 32; Application.DocumentManager.MdiActiveDocument.Database.Pdsize = 2 * scale; trans.Commit(); } }
public void AddAnEnt() { Document doc = Application.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; // Declare a PromptKeywordOptions variable and instantiate it by creating // a new PromptKeywordOptions. Use a string similar to the following for the // messageAndKeywords string. // "Which entity do you want to create? [Circle/Block] : ", "Circle Block" PromptKeywordOptions poEntity = new PromptKeywordOptions( "Which entity do you want to create? [Circle/Block] : ", "Circle Block"); // String with the options separated with a space // Instantiate the PromptResult by making it equal to the return value of the GetKeywords method. PromptResult prEntity = ed.GetKeywords(poEntity); if (prEntity.Status == PromptStatus.OK) { switch (prEntity.StringResult) { case "Circle": // Ask for a point, which will be the center of the circle PromptPointOptions poCenterPoint = new PromptPointOptions("Pick Center Point: "); // Pass the prompt to the editor and get the resulting point PromptPointResult prCenterPoint = ed.GetPoint(poCenterPoint); if (prCenterPoint.Status == PromptStatus.OK) { // Ask for a distance (radius) PromptDistanceOptions poRadius = new PromptDistanceOptions("Pick Radius: "); // Make the point selected earlier the base point of the distance prompt poRadius.BasePoint = prCenterPoint.Value; // Tell the prompt to actually use the base point poRadius.UseBasePoint = true; // Get the distance PromptDoubleResult prRadius = ed.GetDistance(poRadius); if (prRadius.Status == PromptStatus.OK) { // Add the circle to the DWG Database dwg = ed.Document.Database; // Start a transaction (as you would with a database) Transaction trans = dwg.TransactionManager.StartTransaction(); try { // Create the circle. // The second parameter is the normal (perpendicular) vector. Circle circle = new Circle(prCenterPoint.Value, Vector3d.ZAxis, prRadius.Value); // Create a new block // A BlockTableRecord is similar to using the "BLOCK" command on AutoCAD. // When we add a record to the current space, we ARE NOT adding it to the "Blocks" utility. BlockTableRecord curSpace = (BlockTableRecord)trans.GetObject(dwg.CurrentSpaceId, OpenMode.ForWrite); // Add the circle to the new block curSpace.AppendEntity(circle); // Tell the transaction about the new object (entity) trans.AddNewlyCreatedDBObject(circle, true); // Commit trans.Commit(); } catch (Autodesk.AutoCAD.Runtime.Exception ex) { // Write exception on the AutoCAD command line ed.WriteMessage("EXCEPTION: " + ex.Message); } finally { // Dispose of the transaction (whether an error has occurred or not) trans.Dispose(); } } } break; case "Block": // Add a prompt to name the block PromptStringOptions poBlockName = new PromptStringOptions("Enter the name of the Block to create: "); // Don't allow spaces, as a block's name can't have spaces poBlockName.AllowSpaces = false; // Get the name PromptResult prBlockName = ed.GetString(poBlockName); if (prBlockName.Status == PromptStatus.OK) { // Add the block to the dwg Database dwg = ed.Document.Database; Transaction trans = dwg.TransactionManager.StartTransaction(); try { // Create new BTR from scratch BlockTableRecord btr = new BlockTableRecord(); // Set name to the prompt result btr.Name = prBlockName.StringResult; // First verify if a block with the same name already exists in the Block Table // We open the Block Table in read, because we won't be changing it right now BlockTable blockTable = (BlockTable)trans.GetObject(dwg.BlockTableId, OpenMode.ForRead); if (blockTable.Has(prBlockName.StringResult)) { throw new Autodesk.AutoCAD.Runtime.Exception( ErrorStatus.InvalidInput, "Cannot create block. Block with same name already exists."); } else { // Update OpenMode to ForWrite blockTable.UpgradeOpen(); // Add to the block table (this will make the block available for the user in the "Block" utility) blockTable.Add(btr); // Tell the transaction about the new object, so that it auto-closes it trans.AddNewlyCreatedDBObject(btr, true); // We defined that the block consists of two circles, so we'll add them Circle circle1 = new Circle(new Point3d(0, 0, 0), Vector3d.ZAxis, 10); Circle circle2 = new Circle(new Point3d(20, 10, 0), Vector3d.ZAxis, 10); btr.AppendEntity(circle1); btr.AppendEntity(circle2); trans.AddNewlyCreatedDBObject(circle1, true); trans.AddNewlyCreatedDBObject(circle2, true); // Prompt for insertion point PromptPointOptions poPoint = new PromptPointOptions("Pick insertion point of BlockRef : "); PromptPointResult prPoint = ed.GetPoint(poPoint); if (prPoint.Status != PromptStatus.OK) { // If point is not valid, return trans.Dispose(); return; } // The BlockTableRecord is the BLOCK (i.e., a template) // The BlockReference is the result of using INSERT (i.e., an instance of a block) BlockReference blockRef = new BlockReference(prPoint.Value, btr.ObjectId); // Add to the current space BlockTableRecord curSpace = (BlockTableRecord)trans.GetObject(dwg.CurrentSpaceId, OpenMode.ForWrite); curSpace.AppendEntity(blockRef); // Finish transaction trans.AddNewlyCreatedDBObject(blockRef, true); trans.Commit(); } } catch (Autodesk.AutoCAD.Runtime.Exception ex) { ed.WriteMessage("EXCEPTION: " + ex.Message); } finally { trans.Dispose(); } } break; } } }
internal void AllowControlCToCancelResult(PromptResult result) { this.execution = result; this.execution.CancellationTokenSource = new CancellationTokenSource(); this.console.CaptureControlC = false; }
public static void ReadICD() { // CAD指针 CivilDocument civildoc = CivilApplication.ActiveDocument; Document doc = Application.DocumentManager.MdiActiveDocument; Database acCurDb = doc.Database; Editor ed = doc.Editor; PromptOpenFileOptions opt = new PromptOpenFileOptions("\n请选择线型文件."); opt.Filter = "ICD File (*.icd)|*.icd|All files (*.*)|*.*"; PromptFileNameResult res = ed.GetFileNameForOpen(opt); if (res.Status != PromptStatus.OK) { return; } SRBA.PM bill = new SRBA.PM(res.StringResult); // 转化平曲线 ObjectId AlgID = Alignment.Create(civildoc, Path.GetFileNameWithoutExtension(res.StringResult), null, "0", "Basic", "All Labels"); using (Transaction ts = acCurDb.TransactionManager.StartTransaction()) { Alignment myAg = ts.GetObject(AlgID, OpenMode.ForWrite) as Alignment; AddICD(ref myAg, ref bill, ref ed); myAg.ReferencePointStation = bill.StartPK; //ed.WriteMessage("\n{0}读取成功.", res.StringResult); // 竖曲线 PromptKeywordOptions pKeyOpts = new PromptKeywordOptions("\n是否加载竖曲线?"); pKeyOpts.Keywords.Add("Y"); pKeyOpts.Keywords.Add("N"); pKeyOpts.Keywords.Default = "Y"; pKeyOpts.AllowNone = true; PromptResult pKeyRes = doc.Editor.GetKeywords(pKeyOpts); switch (pKeyRes.Status) { case PromptStatus.OK: if (pKeyRes.StringResult == "Y") { SRBA.SQX kitty = new SRBA.SQX(Path.ChangeExtension(res.StringResult, "SQX")); ObjectId layerId = myAg.LayerId; ObjectId styleId = civildoc.Styles.ProfileStyles["Basic"]; ObjectId labelSetId = civildoc.Styles.LabelSetStyles.ProfileLabelSetStyles["Complete Label Set"]; ObjectId oProfileId = Profile.CreateByLayout(myAg.Name + "-Profile", myAg.ObjectId, layerId, styleId, labelSetId); Profile oProfile = ts.GetObject(oProfileId, OpenMode.ForWrite) as Profile; AddSQX(ref oProfile, ref kitty, ref ed); } break; default: break; } // 转化对比JD法 //pKeyOpts = new PromptKeywordOptions("\n是否加载交点法平曲线?"); //pKeyOpts.Keywords.Add("Y"); //pKeyOpts.Keywords.Add("N"); //pKeyOpts.Keywords.Default = "Y"; //pKeyOpts.AllowNone = true; //pKeyRes = doc.Editor.GetKeywords(pKeyOpts); //switch (pKeyRes.Status) //{ // case PromptStatus.OK: // if (pKeyRes.StringResult == "Y") // { // PQXnew kitty = new PQXnew("Test"); // kitty.ReadICDFile(res.StringResult); // ObjectId layerId = myAg.LayerId; // ObjectId styleId = civildoc.Styles.ProfileStyles["Basic"]; // ObjectId labelSetId = civildoc.Styles.LabelSetStyles.ProfileLabelSetStyles["Complete Label Set"]; // ObjectId oProfileId = Profile.CreateByLayout(myAg.Name + "-Profile", myAg.ObjectId, layerId, styleId, labelSetId); // Profile oProfile = ts.GetObject(oProfileId, OpenMode.ForWrite) as Profile; // AddPQX( 0,24000,500, ref acCurDb, ref kitty, ref ed); // } // break; // default: // break; //} ts.Commit(); } }
string imagePath = ""; //15-04-2018 // string BaseImagePath = ""; public SymbolLibrary(string region, string typeofSign = "", string xmlName = "", string svOptionFromLisp = "", string folderPathFromLisp = "") { InitializeComponent(); DateTime dtmNow = DateTime.Now; //if (dtmNow.Day <= 31 && dtmNow.Year <= 2017 && dtmNow.Month <= 06) { try { string mainCui = Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("MENUNAME") + ".cuix"; CustomizationSection cs = new CustomizationSection(mainCui); PartialCuiFileCollection pcfc = cs.PartialCuiFiles; foreach (var _pcfc in pcfc) { string cuixPath = System.IO.Path.GetFileNameWithoutExtension(_pcfc); if (cuixPath.Trim().ToLower().EndsWith("_au")) { region = "Aus"; } else if (cuixPath.Trim().ToLower().EndsWith("_sg")) { region = "SG"; } else { region = "NZ"; } } } catch { } _typeofSign = typeofSign; acsc = new AutoCompleteStringCollection(); txtSearch.AutoCompleteCustomSource = acsc; txtSearch.AutoCompleteMode = AutoCompleteMode.Suggest; txtSearch.AutoCompleteSource = AutoCompleteSource.CustomSource; dirPath = System.Reflection.Assembly.GetExecutingAssembly().Location; dirPath = dirPath.Substring(0, dirPath.LastIndexOf("\\")); //settingsFilePath = Path.Combine(dirPath, "Settings.ini"); //if (System.IO.File.Exists(settingsFilePath)) //{ // try // { // IniFile iniFile = new IniFile(settingsFilePath); // BaseImagePath = iniFile.IniReadValue("setting", "ImagePath"); // } // catch { } //} //IniFile iniFile = new IniFile(settingsFilePath); //signsDrawingPath =iniFile.IniReadValue("New Zealand", "Signs"); if (String.IsNullOrWhiteSpace(_typeofSign)) { MessageBox.Show("Type not found"); return; } try { //Code to read path from lisp // signsDrawingPath = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.GetLispSymbol("B:SYM").ToString(); //Autodesk.AutoCAD.Internal.Utils.GetLastCommandLines(10, true); if (string.IsNullOrEmpty(folderPathFromLisp)) { Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; PromptResult pr = ed.GetString("Path:"); if (pr.Status == PromptStatus.OK) { path = pr.StringResult; } try { PromptResult PRSVOPtion = ed.GetString("SV"); if (PRSVOPtion.Status == PromptStatus.OK) { SVOption = PRSVOPtion.StringResult; } //PromptResult PRImagePath = ed.GetString("ImagePath"); //if (PRImagePath.Status == PromptStatus.OK) //{ // imagePath = PRImagePath.StringResult; // //if (BaseImagePath.Length > 0)//Add Base path if exists // // imagePath = System.IO.Path.Combine(BaseImagePath, imagePath); //} } catch { } } else { path = folderPathFromLisp; SVOption = svOptionFromLisp; } //17-05-2018 if (SVOption.Equals("SV-ON", StringComparison.InvariantCultureIgnoreCase)) { SVON = true;// chkScale.Checked = true; } else { SVON = false; chkScale.Checked = false; } if (!string.IsNullOrEmpty(path)) { //Added on 24-10-2017 to remove multiple commands, if the last folder is signs then it is signs if not it is road markings //string dirName = Path.GetFileName(path.TrimEnd(Path.DirectorySeparatorChar)); //if (dirName.Equals("Signs")) // _typeofSign = "Signs"; //else // _typeofSign = "RoadMarkings"; if (region.Equals("NZ", StringComparison.InvariantCultureIgnoreCase) || region.Equals("New Zealand", StringComparison.InvariantCultureIgnoreCase)) { region = "New Zealand"; xmlName = "B-Civil.xml"; } else if (region.Equals("Aus", StringComparison.InvariantCultureIgnoreCase) || region.Equals("Australia", StringComparison.InvariantCultureIgnoreCase)) { region = "Australia"; xmlName = "B-Civil_AU.xml"; } else if (region.Equals("SG", StringComparison.InvariantCultureIgnoreCase) || region.Equals("Singapore", StringComparison.InvariantCultureIgnoreCase)) { region = "Singapore"; xmlName = "B-Civil_SG.xml"; } //foreach (string strDir in path.Split('/')) //{ // if (strDir.Equals("NZ", StringComparison.InvariantCultureIgnoreCase)) // { // region = "New Zealand"; // xmlName = "B-Civil.xml"; // break; // } // else if (strDir.Equals("Aus", StringComparison.InvariantCultureIgnoreCase) || strDir.Equals("Australia", StringComparison.InvariantCultureIgnoreCase)) // { // region = "Australia"; // xmlName = "B-Civil_AU.xml"; // break; // } // else if (strDir.Equals("SG", StringComparison.InvariantCultureIgnoreCase) || strDir.Equals("Singapore", StringComparison.InvariantCultureIgnoreCase)) // { // region = "Singapore"; // xmlName = "B-Civil_SG.xml"; // break; // } //} signsDrawingPath = path; } if (string.IsNullOrEmpty(signsDrawingPath)) { MessageBox.Show("Invalid drawing path"); abortScreenOpen = true; // Environment.Exit(-1); } else if (!System.IO.Directory.Exists(signsDrawingPath)) { MessageBox.Show(signsDrawingPath + " - Path does not exist"); abortScreenOpen = true; // Environment.Exit(-1); } else if (string.IsNullOrEmpty(region)) { MessageBox.Show("Region not recognizable in the folder path"); abortScreenOpen = true; // Environment.Exit(-1); } //15-04-2018 //if (string.IsNullOrEmpty(imagePath)) // MessageBox.Show("Image path not found"); //else if (!System.IO.Directory.Exists(imagePath)) // MessageBox.Show("Invalid Image path"); //30-05-2018 //Read the below from CUIX //xmlPath = Path.Combine(dirPath, xmlName);// "NZSigns.xml"); //if (!System.IO.File.Exists(xmlPath)) // MessageBox.Show(xmlName + " - XML file not found"); } catch (Exception ex) { signsDrawingPath = ""; MessageBox.Show("Invalid drawing path - " + ex.ToString()); } txtRegion.Text = region; lblSigns.Text = _typeofSign; string dirName = ""; if (!string.IsNullOrEmpty(signsDrawingPath.Trim())) { dirName = new DirectoryInfo(signsDrawingPath.Trim()).Name; } this.Text = dirName;//11-11-2018 "Symbol Library - " + region + " - " + _typeofSign; } }
public void TcDDYZ6() { int num; int num9; object obj; try { IL_01: ProjectData.ClearProjectError(); num = -2; IL_09: int num2 = 2; CAD.CreateLayer("Y_引注", 4, "continuous", -3, false, true); IL_20: num2 = 3; CAD.CreateLayer("Y_引线", 5, "continuous", 13, false, true); IL_37: num2 = 4; this.double_0 = CAD.GetScale(); IL_44: num2 = 5; DBText dbtext = new DBText(); IL_4D: num2 = 6; dbtext.Height = 300.0; IL_5F: num2 = 7; dbtext.WidthFactor = 0.7; IL_71: num2 = 8; this.string_0 = Clipboard.GetText(); IL_7E: num2 = 9; if (Operators.CompareString(this.string_0, "", false) != 0) { goto IL_C4; } IL_97: num2 = 10; this.entity_0 = new Entity[3]; IL_A6: num2 = 13; this.double_1 = 300.0 * this.double_0; goto IL_15E; IL_C4: num2 = 15; IL_C7: num2 = 16; this.entity_0 = new Entity[4]; IL_D6: num2 = 19; if (this.string_0.Length <= 50) { goto IL_10B; } IL_EA: num2 = 20; this.string_0 = this.string_0.Substring(0, 40) + "……"; IL_10B: num2 = 22; dbtext.TextString = this.string_0; IL_11B: num2 = 23; this.double_1 = (dbtext.GeometricExtents.MaxPoint.X - dbtext.GeometricExtents.MinPoint.X) * this.double_0; IL_15E: num2 = 25; bool flag = false; IL_164: num2 = 26; Document mdiActiveDocument = Application.DocumentManager.MdiActiveDocument; IL_172: num2 = 27; PromptPointOptions promptPointOptions = new PromptPointOptions("插入点:"); IL_180: num2 = 28; PromptPointResult point = mdiActiveDocument.Editor.GetPoint(promptPointOptions); IL_191: num2 = 29; if (point.Status != 5100) { goto IL_27B; } IL_1A7: num2 = 30; this.point3d_2 = point.Value; IL_1B7: num2 = 31; PromptResult promptResult = mdiActiveDocument.Editor.Drag(this); IL_1C8: num2 = 32; if (promptResult.Status != 5100) { goto IL_27B; } IL_1DE: num2 = 33; ObjectId[] array; short num5; short num6; checked { short num3 = (short)(this.entity_0.Length - 1); IL_1EE: num2 = 34; if (num3 != 0) { goto IL_20B; } IL_1F8: num2 = 35; CAD.AddEnt(this.entity_0[0]); goto IL_27B; IL_20B: num2 = 37; IL_20E: num2 = 38; array = new ObjectId[(int)(num3 + 1)]; IL_21C: num2 = 39; short num4 = 0; num5 = (short)(this.entity_0.Length - 1); num6 = num4; } for (;;) { short num7 = num6; short num8 = num5; if (num7 > num8) { break; } IL_231: num2 = 40; array[(int)num6] = CAD.AddEnt(this.entity_0[(int)num6]).ObjectId; IL_255: num2 = 41; num6 += 1; } IL_269: num2 = 42; if (!flag) { goto IL_27B; } IL_270: num2 = 43; Class36.smethod_55(array); IL_27B: goto IL_39B; IL_280: goto IL_3A6; IL_285: num9 = num2; if (num <= -2) { goto IL_2A0; } @switch(ICSharpCode.Decompiler.ILAst.ILLabel[], num); goto IL_375; IL_2A0: int num10 = num9 + 1; num9 = 0; @switch(ICSharpCode.Decompiler.ILAst.ILLabel[], num10); IL_375: goto IL_3A6; } catch when(endfilter(obj is Exception & num != 0 & num9 == 0)) { Exception ex = (Exception)obj2; goto IL_285; } IL_39B: if (num9 != 0) { ProjectData.ClearProjectError(); } return; IL_3A6: throw ProjectData.CreateProjectError(-2146828237); }
public void TcGJHJ_LM1() { int num; int num9; object obj; try { IL_01: ProjectData.ClearProjectError(); num = -2; IL_09: int num2 = 2; bool flag; ObjectId[] array; short num5; short num6; checked { this.long_0 = (long)Math.Round(Conversion.Val(Interaction.InputBox("输入钢筋桁架高度:", "田草CAD工具箱-绘制钢筋桁架", "100", -1, -1))); IL_32: num2 = 3; if (this.long_0 != 0L) { goto IL_4C; } IL_47: goto IL_24E; IL_4C: num2 = 6; this.point3d_0 = CAD.GetPoint("选择插入点: "); IL_5E: num2 = 7; Point3d point3d; if (!(this.point3d_0 == point3d)) { goto IL_74; } IL_6F: goto IL_24E; IL_74: num2 = 10; CAD.CreateLayer("钢筋桁架_LM", 14, "continuous", -1, false, true); IL_8C: num2 = 11; flag = false; IL_91: num2 = 12; Database workingDatabase = HostApplicationServices.WorkingDatabase; IL_9A: num2 = 13; Editor editor = Application.DocumentManager.MdiActiveDocument.Editor; IL_AD: num2 = 14; PromptResult promptResult = editor.Drag(this); IL_B9: num2 = 15; if (promptResult.Status != 5100) { goto IL_16B; } IL_CF: num2 = 16; short num3 = (short)(this.entity_0.Length - 1); IL_DF: num2 = 17; if (num3 != 0) { goto IL_FC; } IL_E9: num2 = 18; CAD.AddEnt(this.entity_0[0]); goto IL_16B; IL_FC: num2 = 20; IL_FF: num2 = 21; array = new ObjectId[(int)(num3 + 1)]; IL_10D: num2 = 22; short num4 = 0; num5 = (short)(this.entity_0.Length - 1); num6 = num4; } for (;;) { short num7 = num6; short num8 = num5; if (num7 > num8) { break; } IL_122: num2 = 23; array[(int)num6] = CAD.AddEnt(this.entity_0[(int)num6]).ObjectId; IL_146: num2 = 24; num6 += 1; } IL_15A: num2 = 25; if (!flag) { goto IL_16B; } IL_160: num2 = 26; Class36.smethod_55(array); IL_16B: goto IL_24E; IL_170: goto IL_243; IL_175: num9 = num2; if (num <= -2) { goto IL_190; } @switch(ICSharpCode.Decompiler.ILAst.ILLabel[], num); goto IL_21D; IL_190: int num10 = num9 + 1; num9 = 0; @switch(ICSharpCode.Decompiler.ILAst.ILLabel[], num10); IL_21D :; } catch when(endfilter(obj is Exception & num != 0 & num9 == 0)) { Exception ex = (Exception)obj2; goto IL_175; } IL_243: throw ProjectData.CreateProjectError(-2146828237); IL_24E: if (num9 != 0) { ProjectData.ClearProjectError(); } }
public void AddAnEnt() { // 2. Declare an Editor variable named ed. Instantiate it using the Editor property // of the Application.DocumentManager.MdiActiveDocument.Editor Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; // 3. Declare a PromptKeywordOptions variable and instantiate it by creating // a new PromptKeywordOptions. Use a string similar to the following for the // messageAndKeywords string. // "Which entity do you want to create? [Circle/Block] : ", "Circle Block" PromptKeywordOptions getWhichEntityOptions = new PromptKeywordOptions("Which entity do you want to create? [Circle/Block] : ", "Circle Block"); // 4. Declare a PromptResult. Use the GetKeywords method of the Editor variable // created in step 1. Pass in the PromptKeywordOptions created in step 2. Instantiate // the PromptResult by making it equal to the return value of the GetKeywords method. PromptResult getWhichEntityResult = ed.GetKeywords(getWhichEntityOptions); // 5. Add an if statement that tests the Status of the PromptResult created in step 4. // Use the PromptStatus enum for the test. (see if it is equal to PromptStatus.OK) // Note: Move the closing curly brace after step 21. if (getWhichEntityResult.Status == PromptStatus.OK) { // 6. PromptStatus was ok. Now use a switch statement. For the switch argument // use the StringResult property of the PromptResult variable used above // Note: Move the closing curly brace after step 21. // (Above the closing curly brace for the if statement in step 5) switch (getWhichEntityResult.StringResult) { // 7. Use "Circle" for the case. (if the StringResult is "Circle") Below // we will use "Block" for the case. (jump ahead to step 15 to add the break // to resolve the "Control cannot fall through... message") case "Circle": // 8. We want to ask the user for the center of the circle. Declare // a PromptPointOptions variable and instatiate it by making it equal // to a new PromptPointOptions. Use "Pick Center Point : " for message parameter PromptPointOptions getPointOptions = new PromptPointOptions("Pick Center Point : "); // 9. Declare a PromptPointResult variable. Use the GetPoint method of // the Editor created in step 2. (Pass in the PromptPointOptions created // in step 8). Instantiate the PromptPointResult by making it equal to the // return of the GetPoint method. PromptPointResult getPointResult = ed.GetPoint(getPointOptions); // 10. Add an if statement that tests the Status of the PromptPointResult // created in step 9. Use the PromptStatus enum for the test. (make sure it is OK) // Note: Move the closing curly brace right before step 15. if ((getPointResult.Status == PromptStatus.OK)) { // 11. Now we want to ask the user for the radius of the circle. Declare // a PromptDistanceOptions variable. Instatiate it by making it equal // to a new PromptDistanceOptions. Use "Pick Radius : " for the message parameter. PromptDistanceOptions getRadiusOptions = new PromptDistanceOptions("Pick Radius : "); // 12. We want to use the point selected in step 9 as the // base point for the GetDistance call coming up. To do this use // the BasePoint property of the PromptDistanceOptions variable created // in the previous step. Make the BasePoint equal to the Value property // of the PromptPointResult created in step 9. getRadiusOptions.BasePoint = getPointResult.Value; // 13. We need to tell the input mechanism to actually use the basepoint. // Do this by setting the UseBasePoint property of the // PromptDistanceOptions created in step 11 to True. getRadiusOptions.UseBasePoint = true; // 14. Get the radius for the circle. Declare a PromptDoubleResult variable. // Instantiate it using the GetDistance method of the Editor variable created // in step 2. Pass in the PromptDistanceOptions created in step 11 and // modified in the previous steps. PromptDoubleResult getRadiusResult = ed.GetDistance(getRadiusOptions); } // 15. Add break to mark the end of the code for the "Circle" case. break; // 16. Add the Case for the "Block" (jump ahead to step 20 to add the break // to resolve the "Control cannot fall through... message") case "Block": // 17. Now we want to ask the user for the name of the block. Delcare // a PromptStringOptions varable and instatiate it by creating a new // PromptStringOptions. Use "Enter name of the Block to create : " for // the message parameter. PromptStringOptions blockNameOptions = new PromptStringOptions("Enter name of the Block to create : "); // 18. No spaces are allowed in a blockname so disable it. Do this by setting // the AllowSpaces property of the PromptStringOptions created in step 15 // to false. blockNameOptions.AllowSpaces = false; // 19. Get the name the user entered. Declare a PromptResult variable // and instantiate it using the GetString method of the Editor object // created in step 2. Pass in the PromptStringOptions created in step 17. PromptResult blockNameResult = ed.GetString(blockNameOptions); // 20. Add break to mark the end of the code for the "Block" case. break; // 21. Build the project. Place a break point. Use the NETLOAD command // and run the AddAnEnt command. Step through the code and fix any errors. // Remember to run the command and test the code for both circle and block. } } }
public static void CreatePlotType() { Document acDoc = Application.DocumentManager.MdiActiveDocument; Editor acEditor = acDoc.Editor; Database acCurDb = acDoc.Database; if (CurrentOpen == null) { PromptStringOptions pStrOpts = new PromptStringOptions("\nEnter plot type name: ") { AllowSpaces = true }; PromptResult pStrRes = acDoc.Editor.GetString(pStrOpts); //Verify input if (pStrRes.Status == PromptStatus.OK) { //Check the block does not already exist bool exists = false; using (Transaction tr = acCurDb.TransactionManager.StartTransaction()) { //Create all plot specific layers LayerTable acLayerTable = tr.GetObject(acCurDb.LayerTableId, OpenMode.ForWrite) as LayerTable; Core.Utilities.CreateLayer(tr, acLayerTable, Constants.JPP_HS_PlotPerimiter, Constants.JPP_HS_PlotPerimiterColor); //Create the background block BlockTable bt = (BlockTable)tr.GetObject(acCurDb.BlockTableId, OpenMode.ForRead); if (bt.Has(pStrRes.StringResult)) { exists = true; } } if (!exists) { // Prompt for the start point PromptPointOptions pPtOpts = new PromptPointOptions("") { Message = "\nEnter the base point. Basepoint to be located at bottom left corner of the plot: " }; PromptPointResult pPtRes = acDoc.Editor.GetPoint(pPtOpts); if (pPtRes.Status == PromptStatus.OK) { CurrentOpen = new PlotType() { PlotTypeName = pStrRes.StringResult, BasePoint = pPtRes.Value }; using (Transaction tr = acCurDb.TransactionManager.StartTransaction()) { Main.AddRegAppTableRecord(); //Create all plot specific layers LayerTable acLayerTable = tr.GetObject(acCurDb.LayerTableId, OpenMode.ForWrite) as LayerTable; Core.Utilities.CreateLayer(tr, acLayerTable, Constants.JPP_HS_PlotPerimiter, Constants.JPP_HS_PlotPerimiterColor); //Create the background block BlockTable bt = (BlockTable)tr.GetObject(acCurDb.BlockTableId, OpenMode.ForRead); bt.UpgradeOpen(); BlockTableRecord backgroundBlockRecord = new BlockTableRecord { Name = CurrentOpen.PlotTypeName + "Background", Origin = CurrentOpen.BasePoint }; ObjectId objRef = bt.Add(backgroundBlockRecord); tr.AddNewlyCreatedDBObject(backgroundBlockRecord, true); //Prep the block for finalising BlockTableRecord plotTypeBlockRecord = new BlockTableRecord { Name = CurrentOpen.PlotTypeName, Origin = CurrentOpen.BasePoint }; ObjectId blockRef = bt.Add(plotTypeBlockRecord); tr.AddNewlyCreatedDBObject(plotTypeBlockRecord, true); //Insert the background block CurrentOpen.BackgroundBlockID = Core.Utilities.InsertBlock(CurrentOpen.BasePoint, 0, objRef); CurrentOpen.BlockID = blockRef; //Create and add basepoint Circle bp = new Circle { Center = CurrentOpen.BasePoint, Radius = 0.5f }; BlockTableRecord acBlkTblRec = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; if (acBlkTblRec != null) { CurrentOpen.BasepointID = acBlkTblRec.AppendEntity(bp); } else { //This should never, ever come up but best to handle it throw new NullReferenceException("Model space not found", null); } tr.AddNewlyCreatedDBObject(bp, true); tr.Commit(); } //Inform all event handlers the current plot type has changed OnCurrentOpenChanged?.Invoke(); } else { acEditor.WriteMessage("Point selection cancelled\n"); } } else { acEditor.WriteMessage("Plot Type Name already exists as block. Please choose a different name or rename exisitng block\n"); } } else { acEditor.WriteMessage("No plot type name entered\n"); } } else { acEditor.WriteMessage("Plot Type already open for editing. Please finalise before attempting to create a new plot type.\n"); } }
private void OnPromptButtonClick(PromptResult buttonType) { lastClickType = buttonType; switch (buttonType) { case PromptResult.Accept: case PromptResult.Decline: case PromptResult.Cancel: IsShowing = false; break; case PromptResult.Next: case PromptResult.Back: break; default: throw new ArgumentOutOfRangeException(buttonType.ToString()); } }
public static void AddAccessPointd() { Document acDoc = Application.DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; Editor acEditor = acDoc.Editor; if (CurrentOpen != null) { //TODO: Add transient graphics and error checking PromptStringOptions pStrOpts = new PromptStringOptions("\nEnter the access point level realtive to floor level: ") { AllowSpaces = true }; PromptResult pStrRes = acDoc.Editor.GetString(pStrOpts); // Prompt for the start point PromptPointOptions pPtOpts = new PromptPointOptions("") { Message = "\nEnter the access point. Access point to fall on wall segment: " }; PromptPointResult pPtRes = acDoc.Editor.GetPoint(pPtOpts); using (Transaction tr = acCurDb.TransactionManager.StartTransaction()) { if (PlotType.CurrentOpen.WSIntersect(pPtRes.Value)) { //Add the access point BlockTable bt = (BlockTable)tr.GetObject(acCurDb.BlockTableId, OpenMode.ForRead); ObjectId newBlockId = bt[PlotType.CurrentOpen.PlotTypeName + "Background"]; ObjectIdCollection plotObjects = new ObjectIdCollection(); //Add basepoint Circle accessPointCircle = new Circle { Layer = Constants.JPP_HS_PlotPerimiter, //TODO: move to another layer?? Center = pPtRes.Value, Radius = 0.25f }; // Open the Block table record Model space for write BlockTableRecord acBlkTblRec = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; ObjectId temp = acBlkTblRec.AppendEntity(accessPointCircle); PlotType.CurrentOpen.AccessPointLocations.Add(temp); tr.AddNewlyCreatedDBObject(accessPointCircle, true); string id = System.Guid.NewGuid().ToString(); accessPointCircle.XData = new ResultBuffer(new TypedValue(1001, "JPP"), new TypedValue(1000, id)); PlotType.CurrentOpen.AccessPoints.Add(new AccessPoint() { Location = pPtRes.Value, Offset = float.Parse(pStrRes.StringResult), Guid = id }); tr.Commit(); } else { //TODO: say why failed. } } //Triggeer regen to update blocks display //alternatively http://adndevblog.typepad.com/autocad/2012/05/redefining-a-block.html Application.DocumentManager.CurrentDocument.Editor.Regen(); } else { acEditor.WriteMessage("No Plot Type currently open\n"); } }
public void mln() { Editor ed = acDoc.Editor; //prompt select matchline PromptEntityOptions entOpt = new PromptEntityOptions("Select Matchline"); entOpt.SetRejectMessage("Line Selected is not Matchline\n"); entOpt.AddAllowedClass(typeof(Line), false); //check entity results status PromptEntityResult entRst = ed.GetEntity(entOpt); if (entRst.Status != PromptStatus.OK) { return; } //begin transaction Transaction trans = acCurDb.TransactionManager.StartTransaction(); using (trans) { //open blockTable for read BlockTable blockTable; blockTable = trans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord blockTableRecord; blockTableRecord = trans.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; //i think i need to cast the entity to a polyline so i can get the point Line matchLine = trans.GetObject(entRst.ObjectId, OpenMode.ForWrite) as Line; //get the midpoint of line Point3d pts = getMidPoint(matchLine); //create text DBText mText = new DBText(); //System.Diagnostics.Debugger.Launch(); mText.Justify = AttachmentPoint.MiddleCenter; mText.LayerId = matchLine.LayerId; mText.Height = 5; //prompt to select side PromptPointOptions ptOpt = new PromptPointOptions("Select Side "); PromptPointResult ptResult = ed.GetPoint(ptOpt); if (!sideSelected(ptResult.Value, matchLine)) { //mText.Justify = AttachmentPoint.TopCenter; Line x = matchLine.GetOffsetCurves(-3.75)[0] as Line; mText.AlignmentPoint = getMidPoint(x); } else { Line x = matchLine.GetOffsetCurves(3.75)[0] as Line; mText.AlignmentPoint = getMidPoint(x); } //prompt user for sheet number PromptStringOptions strOpt = new PromptStringOptions("Enter Page #") { AllowSpaces = false }; TextStyleTable textStyleTable = trans.GetObject(acCurDb.TextStyleTableId, OpenMode.ForRead) as TextStyleTable; if (textStyleTable.Has("B")) { mText.TextStyleId = trans.GetObject(textStyleTable["B"], OpenMode.ForRead).ObjectId; } PromptResult sheetNum = ed.GetString(strOpt); mText.TextString = "MATCH LINE - SEE SHEET " + sheetNum.StringResult; if (matchLine.Angle > (Math.PI / 2) && matchLine.Angle < ((Math.PI * 3) / 2)) { mText.Rotation = matchLine.Angle + Math.PI; } else { mText.Rotation = matchLine.Angle; } //append to block table blockTableRecord.AppendEntity(mText); trans.AddNewlyCreatedDBObject(mText, true); trans.Commit(); } }
public void SyncProperties() { // User Input: editor equals command line // To talk to the user you use the command line, aka the editor Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; PromptResult pr1 = ed.GetFileNameForOpen("Hello Nadia, Please select the Sheet Set you would like to edit."); PromptStringOptions pso = new PromptStringOptions("\nHello Nadia! \nWhat version # is the drawing at?"); //pso.DefaultValue = @"C:\Users\Robert\Documents\AutoCAD Sheet Sets\Expedia.dst"; //pso.UseDefaultValue = true; pso.AllowSpaces = true; PromptResult pr = ed.GetString(pso); string versionNumber = pr.StringResult; pso = new PromptStringOptions("\nHello Nadia! \nWhat is the version issue date?"); pr = ed.GetString(pso); string versionIssueDate = pr.StringResult; // Get a reference to the Sheet Set Manager object IAcSmSheetSetMgr sheetSetManager = new AcSmSheetSetMgr(); // Create a new sheet set file //AcSmDatabase sheetSetDatabase = sheetSetManager.CreateDatabase("C:\\Datasets\\CP318-4\\CP318-4.dst", "", true); //AcSmDatabase sheetSetDatabase = sheetSetManager.CreateDatabase(@"C:\Users\rhale\Documents\AutoCAD Sheet Sets\Expedia.dst", "", true); // Open a Sheet Set file AcSmDatabase sheetSetDatabase = default(AcSmDatabase); //sheetSetDatabase = sheetSetManager.OpenDatabase("C:\\Program Files\\AutoCAD 2010\\Sample\\Sheet Sets\\Architectural\\IRD Addition.dst", false); //sheetSetDatabase = sheetSetManager.OpenDatabase(@"C:\Users\rhale\Documents\AutoCAD Sheet Sets\Expedia.dst", false); sheetSetDatabase = sheetSetManager.OpenDatabase(pr1.StringResult, false); // Get the sheet set from the database AcSmSheetSet sheetSet = sheetSetDatabase.GetSheetSet(); // Attempt to lock the database if (LockDatabase(ref sheetSetDatabase, true) == true) { // Get the folder the sheet set is stored in string sheetSetFolder = null; sheetSetFolder = sheetSetDatabase.GetFileName().Substring(0, sheetSetDatabase.GetFileName().LastIndexOf("\\")); // Set the default values of the sheet set //SetSheetSetDefaults(sheetSetDatabase, "CP318-4", "AU2009 Sheet Set Object Demo", sheetSetFolder, "C:\\Datasets\\CP318-4\\CP318-4.dwt", "Sheet"); SetSheetSetDefaults(sheetSetDatabase, "Expedia Sheet Set", "ABF Sheet Set Object Demo", sheetSetFolder, @"C:\Users\rhale\Documents\AutoCAD Sheet Sets\ABFStylesSS.dwt", "Sheet"); // Create a sheet set property SetCustomProperty(sheetSet, "Project Approved By", "Erin Tasche", PropertyFlags.CUSTOM_SHEETSET_PROP); // Create sheet properties //SetCustomProperty(sheetSet, "Checked By", "LAA", PropertyFlags.CUSTOM_SHEET_PROP); //SetCustomProperty(sheetSet, "Complete Percentage", "0%", PropertyFlags.CUSTOM_SHEET_PROP); SetCustomProperty(sheetSet, "Version #", versionNumber, PropertyFlags.CUSTOM_SHEET_PROP); SetCustomProperty(sheetSet, "Version Issue Date", versionIssueDate, PropertyFlags.CUSTOM_SHEET_PROP); //AddSheet(sheetSetDatabase, "Title Page", "Project Title Page", "Title Page", "T1"); // Create two new subsets AcSmSubset subset = default(AcSmSubset); //subset = CreateSubset(sheetSetDatabase, "Plans", "Building Plans", "", "C:\\Datasets\\CP318-4\\CP318-4.dwt", "Sheet", false); subset = CreateSubset(sheetSetDatabase, "Submittals", "Project Submittals", "", @"C:\Users\Robert\Documents\AutoCAD Sheet Sets\ABFStylesSS.dwt", "Sheet", false); //subset = CreateSubset(sheetSetDatabase, "Elevations", "Building Elevations", "", "C:\\Datasets\\CP318-4\\CP318-4.dwt", "Sheet", true); subset = CreateSubset(sheetSetDatabase, "As Builts", "Project As Builts", "", @"C:\Users\Robert\Documents\AutoCAD Sheet Sets\ABFStylesSS.dwt", "Sheet", true); // Add a sheet property //SetCustomProperty(sheetSet, "Drafted By", "KMA", PropertyFlags.CUSTOM_SHEET_PROP); // Add a subset property SetCustomProperty(sheetSet, "Count", "0", PropertyFlags.CUSTOM_SHEETSET_PROP); // Sync the properties of the sheet set with the sheets and subsets SyncProperties(sheetSetDatabase); // Unlock the database LockDatabase(ref sheetSetDatabase, false); } else { // Display error message MessageBox.Show("Sheet set could not be opened for write."); } // Close the sheet set sheetSetManager.Close(sheetSetDatabase); }
internal Result(PromptResult promptResult, WorldDraw worldDraw) { rst = promptResult; draw = worldDraw; }
public void CopyAlongPathAtDists() { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; ObjectId[] entIds; //待复制图元Id Curve pathCurve; //复制路劲曲线 Point3d pt1; //复制起点 using (Transaction trans = db.TransactionManager.StartTransaction()) //开始事务处理 { //1.选择要复制的图元 PromptSelectionOptions entsOpt = new PromptSelectionOptions(); entsOpt.MessageForAdding = "\n选择要复制的图元"; PromptSelectionResult entsRes = ed.GetSelection(entsOpt); if (entsRes.Status != PromptStatus.OK) { return; } SelectionSet entSS = entsRes.Value; entIds = entSS.GetObjectIds(); //2.选择路径线 PromptEntityOptions pathOpt = new PromptEntityOptions("\n选择复制路径"); pathOpt.SetRejectMessage("\n请选择多段线、圆弧或直线!"); pathOpt.AddAllowedClass(typeof(Polyline), false); pathOpt.AddAllowedClass(typeof(Arc), false); pathOpt.AddAllowedClass(typeof(Line), false); PromptEntityResult pathRes = ed.GetEntity(pathOpt); ObjectId pathId = pathRes.ObjectId; pathCurve = pathId.GetObject(OpenMode.ForRead) as Curve; //3.选择复制起点 PromptPointOptions pt1Opt = new PromptPointOptions("\n选择起点"); PromptPointResult pt1Res = ed.GetPoint(pt1Opt); if (pt1Res.Status != PromptStatus.OK) { return; } pt1 = pt1Res.Value; pt1 = pathCurve.GetClosestPointTo(pt1, false); //使用GetClosedPointTo函数保证起点严格在曲线上 trans.Commit(); } //4.输入复制距离并进行复制和旋转 double distOfStPt = pathCurve.GetDistAtPoint(pt1); //获取复制起点在曲线上的距离参数 double distCum = distOfStPt; //初始化累计长度 Point3d pt2; //初始化终点 ObjectId newEntId; //初始化复制图元Id Vector3d vct1 = pathCurve.GetFirstDerivative(pt1); //起点切向量 double ang1 = Math.Atan2(vct1.Y, vct1.X); //起点切向量角度 Vector3d vct2; //初始化终点切向量 double ang2; //初始化起点切向量角度 for (;;) { using (Transaction trans = db.TransactionManager.StartTransaction())//开始事务处理 { PromptStringOptions distsOpt = new PromptStringOptions("\n输入分段距离或按ESC退出(各段长度以空格分隔,等间距采用N@d格式)"); distsOpt.AllowSpaces = true; //允许输入空格 PromptResult distsRes = ed.GetString(distsOpt); if (distsRes.Status == PromptStatus.OK) //输入正确 { List <double> dists = new List <double>(); if (ReadSegsInput(ref dists, distsRes.StringResult))//读入距离数据成功 { if (distCum + dists.Sum() > pathCurve.GetDistAtPoint(pathCurve.EndPoint)) { ed.WriteMessage("超出多段线范围,请重新输入!"); trans.Abort(); continue; } foreach (double dist in dists) { distCum += dist; //终点距离累积前进 pt2 = pathCurve.GetPointAtDist(distCum); //重置当前前进起始点 foreach (ObjectId entId in entIds) { newEntId = entId.Copy(pt1, pt2); vct2 = pathCurve.GetFirstDerivative(pt2); //终点切向量 ang2 = Math.Atan2(vct2.Y, vct2.X); //起点切向量角度 newEntId.Rotate(pt2, ang2 - ang1); //旋转图元 } } trans.Commit();//执行事务处理 } else//读入距离数据有误 { ed.WriteMessage("\n输入有误,请重新输入!"); trans.Abort(); continue; } } else { trans.Abort(); break;//输入回车、ESC等则退出 } } } }