private bool GetTextPos() { this.TextPos = TextToPos(Ac.GetValue("OrthoDist.TextPos")); // http://help.autodesk.com/view/ACD/2016/ENU/?guid=GUID-DF40DD82-FD27-43C5-B7D2-E75646B2E47E var opts = new PromptKeywordOptions(AppServices.Strings.EnterTextPosition); opts.Keywords.Add("Left"); opts.Keywords.Add("Right"); //opts.Keywords.Default = this.TextPos.ToString(); opts.AppendKeywordsToMessage = true; //opts.AllowNone = true; //opts.AllowArbitraryInput = true; //var optsStr = opts.Keywords.GetDisplayString(false); var res = Ac.Editor.GetKeywords(opts); if (res.Status != PromptStatus.OK) { return(false); } this.TextPos = TextToPos(res.StringResult); return(true); }
public void ChangeDistanceType() { PromptKeywordOptions pko = new PromptKeywordOptions("\n" + String.Format(CommandStringResources.ResourceManager.GetString("CurrentIs", GLOBAL.CurrentCulture) + " {0}" + ". " + CommandStringResources.ResourceManager.GetString("ChangeTo", GLOBAL.CurrentCulture), this.DistanceType)); pko.Keywords.Add("Horizontal"); pko.Keywords.Add("Vertical"); pko.Keywords.Add("Curve"); pko.Keywords.Default = "Horizontal"; PromptResult pr = GLOBAL.CurrentEditor.GetKeywords(pko); if (pr.Status == PromptStatus.OK) { switch (pr.StringResult) { case "Horizontal": this.DistanceType = Distance.DistanceType.Horizontal; break; case "Vertical": this.DistanceType = Distance.DistanceType.Vertical; break; case "Curve": this.DistanceType = Distance.DistanceType.Curve; break; } } }
/// <summary> /// 输入字符串类型关键字 /// </summary> public static string GetStringKeywordOnScreen(this Editor ed, string message, string str1, string str1display, string str2, string str2display) { PromptKeywordOptions Opts = new PromptKeywordOptions(message); Opts.Keywords.Add(str1, str1, str1display); Opts.Keywords.Add(str2, str2, str2display); Opts.Keywords.Add("Esc", "Esc", "退出(Esc)"); Opts.Keywords.Default = str1; Opts.AllowNone = true; PromptResult Res = ed.GetKeywords(Opts); switch (Res.Status) { case PromptStatus.OK: return(Res.StringResult); case PromptStatus.Cancel: return(null); default: return(null); } }
/// <summary> 从两个选项中选择一个 </summary> /// <param name="docMdf"></param> /// <returns>true 表示按顶点缩放(默认值),false 表示按长度缩放</returns> private static bool?GetKeywordsFromTwoOptions(DocumentModifier docMdf) { var op = new PromptKeywordOptions( messageAndKeywords: "\n删除选择的边坡与平台[仅平台(P) / 仅边坡(S)]:", globalKeywords: "平台 边坡"); // 默认值写在前面 op.AllowArbitraryInput = false; op.AllowNone = true; var res = docMdf.acEditor.GetKeywords(op); if (res.Status == PromptStatus.OK) { // 非默认值 if (res.StringResult == "平台") { return(false); } // 非默认值 if (res.StringResult == "边坡") { return(true); } } return(null); }
public static void XCloseAll() { if (!CheckLicense.Check()) { return; } Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; PromptKeywordOptions kopts = new PromptKeywordOptions("\nTüm dosyalar kaydedilmeden kapatılacak. Devam edilsin mi? [Evet/Hayır] <Hayir>: ", "Yes No"); kopts.AllowNone = true; kopts.Keywords.Default = "No"; PromptResult kres = ed.GetKeywords(kopts); if (kres.Status != PromptStatus.OK || kres.StringResult != "Yes") { return; } foreach (Document doc in Application.DocumentManager) { if (doc.CommandInProgress != "" && doc.CommandInProgress != "XCLOSEALL") { doc.SendStringToExecute("\x03\x03", false, false, false); } DocumentExtension.CloseAndDiscard(doc); } }
public static ObjectId ChosePole() { PromptKeywordOptions keyopt = new PromptKeywordOptions("\n选择杆塔种类 (钢杆0/水泥杆1/铁塔2)" + "[0/1/2]", "0 1 2"); PromptResult keyRes = PublicMethod.Instance.Editor.GetKeywords(keyopt); return(PublicMethod.Instance.GetBlockObjId("201_" + keyRes.StringResult)); }
public void SampleEntry() { Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; PromptKeywordOptions pso = new PromptKeywordOptions("Select the sample for:"); pso.Keywords.Add("override display properties for Material"); pso.Keywords.Add("override display properties for a Wall"); pso.Keywords.Add("display block Attributes"); PromptResult pr = ed.GetKeywords(pso); if (pr.Status == PromptStatus.OK) { if (pr.StringResult == "Material") { DisplayPropertiesMaterialSample(); } if (pr.StringResult == "Wall") { DisplayPropertiesWallSample(); } if (pr.StringResult == "Attributes") { DisplayBlockAttributesSample(); } } }
/// <summary> 从多个选项中选择一个 </summary> /// <param name="docMdf"></param> /// <returns>true 表示按顶点缩放(默认值),false 表示按长度缩放</returns> private static bool GetProtectionDirection(DocumentModifier docMdf, out MergeProtectionDirection dir) { var op = new PromptKeywordOptions( messageAndKeywords: "\n合并后的防护方式选择 <底部>[无(N) / 底部(B) / 顶部(T) / 靠近中线(I) / 远离中线(O)]", globalKeywords: "无 底部 顶部 靠近中线 远离中线"); // 默认值写在前面 op.AllowArbitraryInput = false; op.AllowNone = true; var res = docMdf.acEditor.GetKeywords(op); dir = MergeProtectionDirection.底部; if (res.Status == PromptStatus.OK) { // 非默认值 switch (res.StringResult) { case "顶部": dir = MergeProtectionDirection.顶部; break; case "靠近中线": dir = MergeProtectionDirection.靠近中线; break; case "远离中线": dir = MergeProtectionDirection.远离中线; break; case "无": dir = MergeProtectionDirection.无; break; default: dir = MergeProtectionDirection.底部; break; } return(true); } else if (res.Status == PromptStatus.Cancel) { return(false); } return(true); }
Stream(ArrayList data, PromptKeywordOptions opts) { data.Add(new Snoop.Data.ClassSeparator(typeof(PromptKeywordOptions))); data.Add(new Snoop.Data.Bool("Allow arbitrary input", opts.AllowArbitraryInput)); data.Add(new Snoop.Data.Bool("Allow none", opts.AllowNone)); }
Stream(ArrayList data, PromptEditorOptions opts) { data.Add(new Snoop.Data.ClassSeparator(typeof(PromptEditorOptions))); PromptCornerOptions promptCornerOpts = opts as PromptCornerOptions; if (promptCornerOpts != null) { Stream(data, promptCornerOpts); return; } PromptStringOptions promptStrOpts = opts as PromptStringOptions; if (promptStrOpts != null) { Stream(data, promptStrOpts); return; } PromptKeywordOptions promptKwordOpts = opts as PromptKeywordOptions; if (promptKwordOpts != null) { Stream(data, promptKwordOpts); return; } PromptNumericalOptions promptNumpericalOpts = opts as PromptNumericalOptions; if (promptNumpericalOpts != null) { Stream(data, promptNumpericalOpts); return; } PromptEntityOptions promptEntOpts = opts as PromptEntityOptions; if (promptEntOpts != null) { Stream(data, promptEntOpts); return; } PromptAngleOptions promptAngleOpts = opts as PromptAngleOptions; if (promptAngleOpts != null) { Stream(data, promptAngleOpts); return; } PromptDragOptions promptDragOpts = opts as PromptDragOptions; if (promptDragOpts != null) { Stream(data, promptDragOpts); return; } }
public void KojtoCAD_3D_Reverse_Normals() { PromptKeywordOptions pKeyOpts = new PromptKeywordOptions(""); pKeyOpts.Message = "\nEnter an option "; pKeyOpts.Keywords.Add("All"); pKeyOpts.Keywords.Add("Triangles"); pKeyOpts.Keywords.Add("Bends"); pKeyOpts.Keywords.Add("Nodes"); pKeyOpts.Keywords.Default = "All"; pKeyOpts.AllowNone = true; PromptResult pKeyRes = Application.DocumentManager.MdiActiveDocument.Editor.GetKeywords(pKeyOpts); if (pKeyRes.Status == PromptStatus.OK) { if ((container != null) && (container.Bends.Count > 0) && (container.Nodes.Count > 0) && (container.Triangles.Count > 0)) { switch (pKeyRes.StringResult) { case "All": KojtoCAD_3D_Reverse_All_Normals(); break; case "Triangles": KojtoCAD_3D_Reverse_Triangles_Normals(); break; case "Bends": KojtoCAD_3D_Reverse_Bends_Normals(); break; case "Nodes": KojtoCAD_3D_Reverse_Nodes_Normals(); break; } } else { MessageBox.Show("\nData Base Empty !\n", "Range Error !", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
private static bool GetCreateBorders(Editor ed) { PromptKeywordOptions pko = new PromptKeywordOptions("\nСоздавать границы?"); pko.Keywords.Add("Да"); pko.Keywords.Add("Нет"); pko.Keywords.Default = createBorders ? "Да" : "Нет"; pko.AllowNone = false; PromptResult pr = ed.GetKeywords(pko); if (pr.Status == PromptStatus.OK) { switch (pr.StringResult) { case "Да": createBorders = true; break; case "Нет": createBorders = false; break; } return(true); } return(false); }
private static SearchOption IncludeSubdirs(Editor ed, DirectoryInfo dir) { // Вопрос - включая подпапки? SearchOption recursive = SearchOption.AllDirectories; if (dir.GetDirectories().Length > 0) { var opt = new PromptKeywordOptions("\nВключая подпапки"); opt.Keywords.Add("Да"); opt.Keywords.Add("Нет"); opt.Keywords.Default = "Да"; var res = ed.GetKeywords(opt); if (res.Status == PromptStatus.OK) { if (res.StringResult == "Нет") { recursive = SearchOption.TopDirectoryOnly; } } } ed.WriteMessage("\nПапка для переопределения блока " + dir.FullName); if (recursive == SearchOption.AllDirectories) ed.WriteMessage("\nВключая подпапки"); else ed.WriteMessage("\nТолько в этой папке, без подпапок."); return recursive; }
public void ShowSample() { Editor editor = GetEditor(); editor.WriteMessage("\n====================================================\n"); editor.WriteMessage("Thank you for using StreamSample\n"); PromptKeywordOptions options = new PromptKeywordOptions("Please select a stream type " + "[collect Bodies/collect Clip bodies/collect Materials/cUrves/Explode/eXtent/Intersect/Slice/Vector]", "collectBodies collectClipbodies collectMaterials cUrves Explode eXtent Intersect Slice Vector"); bool stop = false; while (!stop) { PromptResult pr = editor.GetKeywords(options); switch (pr.Status) { case PromptStatus.OK: case PromptStatus.Keyword: DispatchCommand(pr.StringResult); break; default: stop = true; break; } } editor.WriteMessage("\n====================================================\n"); }
/// <summary> /// Sets the keywords. /// </summary> /// <param name="meassageAndKeywords">The meassage and keywords.</param> /// <param name="defaultKeyword">The default keyword.</param> /// <returns></returns> public static PromptKeywordOptions SetKeywords(string meassageAndKeywords, string defaultKeyword) { PromptKeywordOptions pko = SetKeywords(meassageAndKeywords); pko.Keywords.Default = defaultKeyword; return(pko); }
PromptYesNo(string prmpt, bool def, out bool answer) { Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; answer = false; string defStr = (def) ? "Yes" : "No"; PromptKeywordOptions prOpts = new PromptKeywordOptions(prmpt); prOpts.Keywords.Add("Yes"); prOpts.Keywords.Add("No"); prOpts.Keywords.Default = defStr; PromptResult prRes = ed.GetKeywords(prOpts); if (prRes.Status == PromptStatus.OK) { if (prRes.StringResult == "Yes") { answer = true; } } return(prRes.Status); }
public void SetEnglishWhenDrawing() // This method can have any name { var engWhenDrawing = new PromptKeywordOptions( messageAndKeywords: "\n除文字编辑以外均以英文输入法操作? [是(Y) / 否(N) / 禁用(D)]:", globalKeywords: "是 否 禁用"); engWhenDrawing.AllowNone = true; var editor = Application.DocumentManager.MdiActiveDocument.Editor; var res = editor.GetKeywords(engWhenDrawing); if (res.Status == PromptStatus.OK) { switch (res.StringResult) { case "禁用": Enabled = false; break; case "是": Enabled = true; AlwaysInEnglishWhenDrawing = true; break; default: Enabled = true; AlwaysInEnglishWhenDrawing = false; break; } } }
getUserInputYesNo(string prmpt, bool def, out bool answer) { Editor ed = BaseObjs._editor; answer = false; string defStr = (def) ? "Yes" : "No"; PromptKeywordOptions prOpts = new PromptKeywordOptions(prmpt); prOpts.Keywords.Add("Yes"); prOpts.Keywords.Add("No"); prOpts.Keywords.Default = defStr; PromptResult prRes = ed.GetKeywords(prOpts); if (prRes.Status == PromptStatus.OK) { if (prRes.StringResult == "Yes") { answer = true; } } return(prRes.Status); }
/// <summary> 在命令行中获取一个字符 </summary> /// <param name="value">成功获得的数值</param> /// <returns>操作成功,则返回 true,操作失败或手动取消操作,则返回 false</returns> private static bool GetRegexPattern(Editor ed, out bool showtips, out bool ignoreCase, out string value) { value = ""; showtips = false; ignoreCase = false; var op = new PromptKeywordOptions("正则表达式") { AllowArbitraryInput = true, }; op.SetMessageAndKeywords(messageAndKeywords: "\n查询正则表达式[提示(T) / 不区分大小写(C)]:", globalKeywords: "提示 不区分大小写"); // 默认值写在前面 // var res = ed.GetKeywords(op); if (res.Status == PromptStatus.OK) { value = res.StringResult; if (value == "提示") { showtips = true; } else if (value == "不区分大小写") { ignoreCase = true; } else { return(true); } } return(false); }
public void CMD_IncludePos() { if (!CheckLicense.Check()) { return; } PromptSelectionResult selresult = DWGUtility.SelectAllPosUser(); if (selresult.Status != PromptStatus.OK) { return; } PromptKeywordOptions opts = new PromptKeywordOptions("Metraja [Dahil et/metrajdan Cikar]: ", "Add Remove"); opts.AllowNone = false; PromptResult result = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetKeywords(opts); if (result.Status == PromptStatus.OK) { switch (result.StringResult) { case "Add": IcludePosinBOQ(selresult.Value.GetObjectIds(), true); break; case "Remove": IcludePosinBOQ(selresult.Value.GetObjectIds(), false); break; } } }
public void KojtoCAD_3D_SetBendExplicitParametersA(int k) { PromptKeywordOptions pKeyOpts = new PromptKeywordOptions(""); pKeyOpts.Message = "\nEnter an option "; pKeyOpts.Keywords.Add("Start"); pKeyOpts.Keywords.Add("End"); pKeyOpts.Keywords.Default = "Start"; pKeyOpts.AllowNone = true; PromptResult pKeyRes = Application.DocumentManager.MdiActiveDocument.Editor.GetKeywords(pKeyOpts); if (pKeyRes.Status == PromptStatus.OK) { if ((container != null) && (container.Bends.Count > 0) && (container.Nodes.Count > 0) && (container.Triangles.Count > 0)) { switch (pKeyRes.StringResult) { case "Start": KojtoCAD_3D_SetBendExplicitParametersB(k, 0); break; case "End": KojtoCAD_3D_SetBendExplicitParametersB(k, 1); break; } } else { MessageBox.Show("\nData Base Empty !\n", "Range Error !", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
public void CMD_PosLength() { if (!CheckLicense.Check()) { return; } PromptSelectionResult selresult = DWGUtility.SelectAllPosUser(); if (selresult.Status != PromptStatus.OK) { return; } PromptKeywordOptions opts = new PromptKeywordOptions("L boyunu [Göster/giZle]: ", "Show Hide"); opts.AllowNone = false; PromptResult result = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetKeywords(opts); if (result.Status == PromptStatus.OK) { switch (result.StringResult) { case "Show": ShowPosLength(selresult.Value.GetObjectIds(), true); break; case "Hide": ShowPosLength(selresult.Value.GetObjectIds(), false); break; } } }
public void KojtoCAD_3D_Method_Read_Old_From_Dictionary() { Database db = HostApplicationServices.WorkingDatabase; Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; PromptKeywordOptions pKeyOpts = new PromptKeywordOptions(""); pKeyOpts.Message = "\n Base or Second"; pKeyOpts.Keywords.Add("Base"); pKeyOpts.Keywords.Add("Second"); pKeyOpts.Keywords.Default = "Base"; pKeyOpts.AllowNone = false; PromptResult pKeyRes = Application.DocumentManager.MdiActiveDocument.Editor.GetKeywords(pKeyOpts); if (pKeyRes.Status == PromptStatus.OK) { bool addres = pKeyRes.StringResult == "Base"; try { ContextVariablesProvider.Container = new Containers(); container.Read(addres); ed.UpdateScreen(); int notfictive = 0; foreach (Bend b in container.Bends) { if (!b.Fictive) { notfictive++; } } string formatString = "{0,-20}\t{1,-12}\n\n"; string mess = "\n"; mess += string.Format(formatString, "Nodes:", container.Nodes.Count); mess += string.Format(formatString, "All Bends:", container.Bends.Count); mess += string.Format(formatString, "Bends:", notfictive); mess += string.Format(formatString, "Fictive Bends:", container.Bends.Count - notfictive); mess += string.Format(formatString, "Peripheral Bends:", container.peripheralBendsNumers.Count); mess += string.Format(formatString, "Triangles:", container.Triangles.Count); mess += string.Format(formatString, "Polygons:", container.Polygons.Count); MessageBox.Show("\nMesh data was loaded from the Dictionary !\n\n" + mess + "\n\n" + ConstantsAndSettings.GetString(), "Reading from the Dictionary ...", MessageBoxButtons.OK, MessageBoxIcon.Information); ed.WriteMessage("\nMesh data was loaded from the Dictionary !"); } catch { ed.UpdateScreen(); MessageBox.Show("\nMesh data was NOT loaded from the Dictionary !", "ERROR while reading form Dictionary", MessageBoxButtons.OK, MessageBoxIcon.Error); ed.WriteMessage("\nMesh data was NOT loaded from the Dictionary !"); } } }
public void EditPointElevationRandom() { var keywords = new { PositiveOnly = "PositiveOnly", NegativeOnly = "NegativeOnly", Both = "Both" }; List <CogoPoint> points; if (!ObjectCollector.TrySelectObjects(out points, "\nSelect points")) { return; } PromptDoubleOptions valueOption = new PromptDoubleOptions("\nEnter value"); valueOption.AllowNone = false; valueOption.DefaultValue = 0d; valueOption.AllowNegative = false; PromptDoubleResult valueResult = Tools.GetAcadEditor().GetDouble(valueOption); if (valueResult.Status != PromptStatus.OK) { return; } PromptKeywordOptions options = new PromptKeywordOptions("\nEnter method"); options.AppendKeywordsToMessage = true; options.AllowArbitraryInput = true; options.Keywords.Add(keywords.PositiveOnly); options.Keywords.Add(keywords.NegativeOnly); options.Keywords.Add(keywords.Both); options.AppendKeywordsToMessage = true; options.AllowNone = true; options.Keywords.Default = keywords.Both; PromptResult keywordResult = Tools.GetAcadEditor().GetKeywords(options); if (keywordResult.Status != PromptStatus.OK) { return; } double ratio = keywordResult.StringResult == keywords.Both ? -0.5 : 0d; double sign = keywordResult.StringResult == keywords.NegativeOnly ? -1d : 1d; if (keywordResult.StringResult == keywords.Both) { sign = 2d; } Random random = new Random(DateTime.Now.Second); foreach (CogoPoint point in points) { point.Elevation += (random.NextDouble() + ratio) * valueResult.Value * sign; } }
/// <summary> /// Простановка маркировки позиции /// </summary> /// <param name="ent">Примитив</param> /// <param name="type">Тип маркировки. 0 - нужно ставить новую марку, 1 - текст, 2 - выноска, 3 - ничего</param> /// <param name="posTxt">Содержимое маркировки</param> /// <param name="element">Имя изделия для отображения в запросе</param> /// <param name="markType"> </param> private static void AddPositionMarker(Entity ent, int type, string posTxt, string element, out int markType) { markType = 3; if (type != 0) { if (type == 1) { markType = 1; AddTextMark(ent, posTxt); } else if (type == 2) { markType = 2; AddLeaderMark(ent, posTxt); } else if (type == 3) { markType = 3; } } else { var pko = new PromptKeywordOptions( Language.GetItem(LangItem, "h6") + ": " + element + " " + Language.GetItem(LangItem, "h7") + ": " + posTxt + ": [" + Language.GetItem(LangItem, "h8") + "]", "Nothing Text Leader") { AllowArbitraryInput = true, AllowNone = false }; var pr = AcApp.DocumentManager.MdiActiveDocument.Editor.GetKeywords(pko); if (pr.Status != PromptStatus.OK || string.IsNullOrEmpty(pr.StringResult)) { markType = 3; return; } // Далее в зависимости от выбранного условия switch (pr.StringResult) { case "Nothing": markType = 3; break; case "Text": markType = 1; AddTextMark(ent, posTxt); break; case "Leader": markType = 2; AddLeaderMark(ent, posTxt); break; } } }
public void GpIsoline() { Document doc = Application.DocumentManager.MdiActiveDocument; if (doc == null) { return; } Logger.Log.Info("Start Command: GP-Isoline"); Editor ed = doc.Editor; Options = IsolineOptions.Load(); var optKeywords = new PromptKeywordOptions( $"Отрисовка бергштрихов для полилиний {(_overruleIsolineDraw == null ? "Отключена" : "Включена")}"); optKeywords.Keywords.Add($"{(_overruleIsolineDraw == null ? "Включить" : "Отключить")}"); optKeywords.Keywords.Add($"{(_overruleIsolineDraw == null ? "Разморозить" : "Заморозить")}"); optKeywords.Keywords.Add("Настройки"); var resPrompt = ed.GetKeywords(optKeywords); if (resPrompt.Status == PromptStatus.OK) { if (resPrompt.StringResult == "Включить") { IsolinesOn(); } else if (resPrompt.StringResult == "Отключить") { IsolinesOff(); } else if (resPrompt.StringResult == "Разморозить") { // Удалить отдельные штрихи Isoline.UnfreezeAll(); // Включить изолинии IsolinesOn(); } else if (resPrompt.StringResult == "Заморозить") { // Превратить все штрихи в отдельные линии Isoline.FreezeAll(); // выключение изолиний IsolinesOff(); } else if (resPrompt.StringResult == "Настройки") { Options = Options.Show(); } } Application.DocumentManager.MdiActiveDocument.Editor.Regen(); }
public void DrawEOPs() { Document doc = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; using (Transaction tr = db.TransactionManager.StartTransaction()) { PromptKeywordOptions pKeyWord = new PromptKeywordOptions(""); pKeyWord.Message = "Draw EOP lines "; pKeyWord.AllowNone = true; pKeyWord.Keywords.Add("Yes"); pKeyWord.Keywords.Add("No"); pKeyWord.Keywords.Default = "Yes"; PromptResult pKeyRes = doc.Editor.GetKeywords(pKeyWord); if (pKeyRes.Status == PromptStatus.OK) { switch (pKeyRes.StringResult) { case "No": { utils.drawEOP = false; ed.WriteMessage("\nEdge of Pavement lines have been turned off. Use DEOP again to turn them back on."); break; } case "Yes": { utils.drawEOP = true; ed.WriteMessage("\nLeft EOP = " + Math.Abs(utils.leftShoulderWidth).ToString() + " | | Right EOP = " + Math.Abs(utils.rightShoulderWidth).ToString()); break; } default: { if (utils.drawEOP) { ed.WriteMessage("\nLeft EOP = " + Math.Abs(utils.leftShoulderWidth).ToString() + " | | Right EOP = " + Math.Abs(utils.rightShoulderWidth).ToString()); } else { ed.WriteMessage("\nEdge of Pavement lines have been turned off. Use CEOP again to turn them back on."); } break; } } } tr.Commit(); } } // End ChangeEOPWidth()
public PromptResult GetKeywords(string message, string[] keywords) { using (WorkingDocument.LockDocument()) { var options = new PromptKeywordOptions(message); foreach (var k in keywords) { options.Keywords.Add(k); } return(WorkingDocument.Editor.GetKeywords(options)); } }
public void GpIsoline() { Document doc = Application.DocumentManager.MdiActiveDocument; if (doc == null) return; Logger.Log.Info("Start Command: GP-Isoline"); Editor ed = doc.Editor; Options = IsolineOptions.Load(); var optKeywords = new PromptKeywordOptions( $"Отрисовка бергштрихов для полилиний {(_overruleIsolineDraw == null ? "Отключена" : "Включена")}"); optKeywords.Keywords.Add($"{(_overruleIsolineDraw == null ? "Включить" : "Отключить")}"); optKeywords.Keywords.Add($"{(_overruleIsolineDraw == null ? "Разморозить" : "Заморозить")}"); optKeywords.Keywords.Add("Настройки"); var resPrompt = ed.GetKeywords(optKeywords); if (resPrompt.Status == PromptStatus.OK) { if (resPrompt.StringResult == "Включить") { IsolinesOn(); } else if (resPrompt.StringResult == "Отключить") { IsolinesOff(); } else if (resPrompt.StringResult == "Разморозить") { // Удалить отдельные штрихи Isoline.UnfreezeAll(); // Включить изолинии IsolinesOn(); } else if (resPrompt.StringResult == "Заморозить") { // Превратить все штрихи в отдельные линии Isoline.FreezeAll(); // выключение изолиний IsolinesOff(); } else if (resPrompt.StringResult == "Настройки") { Options = Options.Show(); } } Application.DocumentManager.MdiActiveDocument.Editor.Regen(); }
public static void Create() { BaseClass.UseTransaction(trans => { try { // create prompt keyword options PromptKeywordOptions PKO = new PromptKeywordOptions(""); PKO.Message = "\nWhat would you lik to drow?"; PKO.Keywords.Add("Line"); PKO.Keywords.Add("Circle"); PKO.Keywords.Add("MText"); PKO.AllowNone = false; PromptResult PR = BaseClass.Editor.GetKeywords(PKO); string answer = PR.StringResult; if (answer != null) { BlockTable bt = trans.GetObject(BaseClass.Database.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; switch (answer) { case "Line": //Draw Line DrawLines.Create(); break; case "Circle": //Draw Circle DrawCircles.Create(); break; case "MText": //Draw MText DrawMtext.Create(); break; default: BaseClass.Editor.WriteMessage("\nNo option selected"); break; } } } catch (System.Exception ex) { BaseClass.Editor.WriteMessage("Error encountered: " + ex.Message); trans.Abort(); } }); }
public PromptStatus PromptSlopeLineMode(string msg = "\nУкавите метод построения линий откоса") { PromptKeywordOptions pko = new PromptKeywordOptions(msg); pko.Keywords.Add(SlopeModes.OwnPerpendicular.ToString(), "ПРостойПЕРпендикуляр", "ПРостойПЕРпендикуляр", true, true); pko.Keywords.Add(SlopeModes.EqualStep.ToString(), "ЕКВивалентныйШаг", "ЕКВивалентныйШаг", true, true); pko.Keywords.Add(SlopeModes.BothPerpendicular.ToString(), "ПЕРпендикулярОтНиза", "ПЕРпендикулярОтНиза", true, true); pko.Keywords.Add(SlopeModes.RegressBoth.ToString(), "РЕГрессия", "РЕГрессия", true, true); pko.Keywords.Add("Exit", "ВЫХод", "ВЫХод", true, true); PromptResult pr = Tools.GetAcadEditor().GetKeywords(pko); if (pr.Status != PromptStatus.OK) { return(pr.Status); } if (pr.StringResult == "Exit") { return(PromptStatus.Cancel); } else if (pr.StringResult == SlopeModes.OwnPerpendicular.ToString()) { _slopeMode = SlopeModes.OwnPerpendicular; _dataHost.Write("slopeMode", _slopeMode); return(PromptStatus.OK); } else if (pr.StringResult == SlopeModes.EqualStep.ToString()) { _slopeMode = SlopeModes.EqualStep; _dataHost.Write("slopeMode", _slopeMode); return(PromptStatus.OK); } else if (pr.StringResult == SlopeModes.BothPerpendicular.ToString()) { _slopeMode = SlopeModes.BothPerpendicular; _dataHost.Write("slopeMode", _slopeMode); return(PromptStatus.OK); } else if (pr.StringResult == SlopeModes.RegressBoth.ToString()) { _slopeMode = SlopeModes.RegressBoth; _dataHost.Write("slopeMode", _slopeMode); return(PromptStatus.OK); } else { throw new ArgumentException(); } }
public static void Main() { #if !DEBUG Statistic.SendCommandStarting(new ModPlusConnector()); #endif GetSettings(); var repeat = true; var doc = AcApp.DocumentManager.MdiActiveDocument; var ed = doc.Editor; while (repeat) { var preSelection = ed.SelectImplied(); var pko = new PromptKeywordOptions(string.Empty) { Message = $"\n{Language.GetItem(LangItem, "h6")}: ", AllowNone = false, AppendKeywordsToMessage = true }; pko.Keywords.Add("replaceSelected", Language.GetItem(LangItem, "k1")); pko.Keywords.Add("replaceAll", Language.GetItem(LangItem, "k2")); pko.Keywords.Add("seTtings", Language.GetItem(LangItem, "k3")); var pkr = ed.GetKeywords(pko); if (pkr.Status != PromptStatus.OK) { return; } switch (pkr.StringResult) { case "replaceSelected": repeat = false; ReplaceSelected(preSelection); break; case "replaceAll": repeat = false; ReplaceAll(); break; case "seTtings": var win = new Settings(); win.ShowDialog(); GetSettings(); break; } } }
// проверка наличия блока монтажки этого этажа private bool checkBlock(string floorBlockName) { bool skipOrRedefine = false; // true - skip, false - нет такого блока, можно создавать using (var bt = _db.BlockTableId.Open(OpenMode.ForRead) as BlockTable) { if (bt.Has(floorBlockName)) { var prOpt = new PromptKeywordOptions($"Блок плана {floorBlockName} уже определен в чертеже. Что делать?"); prOpt.Keywords.Add("Выход"); prOpt.Keywords.Add("Пропустить"); prOpt.Keywords.Default = "Выход"; var res = _ed.GetKeywords(prOpt); if (res.Status == PromptStatus.OK) { switch (res.StringResult) { case "Выход": throw new Exception("Отменено пользователем."); case "Пропустить": skipOrRedefine = true; break; default: throw new Exception("Отменено пользователем."); } } else { throw new Exception("Отменено пользователем."); } } } return skipOrRedefine; }
static public bool AskForPrintAllXData() { Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; PromptKeywordOptions pKey = new PromptKeywordOptions("\n是否要打印所有的扩展数据 "); pKey.AllowNone = true; pKey.Keywords.Add("Yes"); pKey.Keywords.Add("No"); pKey.Keywords.Default = "Yes"; PromptResult pKeyRes = ed.GetKeywords(pKey); if (pKeyRes.StringResult == "Yes") { return true; } else { return false; } }
public static void AccessSpace() { AcadApp.Document acDoc = AcadApp.Application.DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { BlockTable acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord acBlkTblRec; // Request which table record to open询问打开哪条表记录(空间) PromptKeywordOptions pKeyOpts = new PromptKeywordOptions(""); pKeyOpts.Message = "\nEnter whichspace to create the line in "; pKeyOpts.Keywords.Add("Model"); pKeyOpts.Keywords.Add("Paper"); pKeyOpts.Keywords.Add("Current"); pKeyOpts.AllowNone = false; pKeyOpts.AppendKeywordsToMessage = true; PromptResult pKeyRes = acDoc.Editor.GetKeywords(pKeyOpts); if (pKeyRes.StringResult == "Model") //从Block表获取Model空间的ObjectID { acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; } else if (pKeyRes.StringResult == "Paper") //从Block表获取Paper空间的ObjectID { acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.PaperSpace], OpenMode.ForWrite) as BlockTableRecord; } else { //从数据库获取当前空间的ObjectID acBlkTblRec = acTrans.GetObject(acCurDb.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord; } ////设置图形中所有点对象的样式 acCurDb.Pdmode = 34; acCurDb.Pdsize = 1; //****************************** // Create an in memory circle在内存创建一个圆 using (Circle acCirc = new Circle()) { acCirc.Center = new Point3d(2, 2, 0); acCirc.Radius = 5; // Adds the circle to an object array将圆添加到对象数组 DBObjectCollection acDBObjColl = new DBObjectCollection(); acDBObjColl.Add(acCirc); // Calculate the regions based oneach closed loop //基于每个闭环计算面域 DBObjectCollection myRegionColl = new DBObjectCollection(); myRegionColl = Region.CreateFromCurves(acDBObjColl); Region acRegion = myRegionColl[0] as Region; acBlkTblRec.AppendEntity(acRegion); acTrans.AddNewlyCreatedDBObject(acRegion, true); acCirc.ColorIndex = 1; acBlkTblRec.AppendEntity(acCirc); acTrans.AddNewlyCreatedDBObject(acCirc, true); // Dispose of the in memory circlenot appended to the database //处置内存中的圆,不添加到数据库; } acTrans.Commit(); } }
public void transNest() { #region 事务嵌套 //创建对事务管理器的引用 AcadApp.Document doc = AcadApp.Application.DocumentManager.MdiActiveDocument; Database d = AcadApp.Application.DocumentManager.MdiActiveDocument.Database; TransactionManager acTransMgr = d.TransactionManager; using (Transaction acTrans1 = acTransMgr.StartTransaction()) { //打印当前活动事务的个数 doc.Editor.WriteMessage("\nNumber of transactions active: " + acTransMgr.NumberOfActiveTransactions.ToString()); BlockTable acBlkTbl = acTrans1.GetObject(d.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord acBlkTblRec = acTrans1.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; Circle acCirc = new Circle(); acCirc.Center = new Point3d(5, 5, 0); acCirc.Radius = 3; acBlkTblRec.AppendEntity(acCirc); acTrans1.AddNewlyCreatedDBObject(acCirc, true); //创建第二个事务 using (Transaction acTrans2 = acTransMgr.StartTransaction()) { doc.Editor.WriteMessage("\nNumber of transactions active: " + acTransMgr.NumberOfActiveTransactions.ToString()); acCirc.ColorIndex = 5; // Change the circle's color修改圆的颜色 Line acLine = new Line(new Point3d(2, 5, 0), new Point3d(10, 7, 0)); acLine.ColorIndex = 3; acBlkTblRec.AppendEntity(acLine); acTrans2.AddNewlyCreatedDBObject(acLine, true); //创建第三个事务 using (Transaction acTrans3 = acTransMgr.StartTransaction()) { doc.Editor.WriteMessage("\nNumber of transactions active: " + acTransMgr.NumberOfActiveTransactions.ToString()); acCirc.ColorIndex = 3; // Update the display of the drawing更新图形显示 doc.Editor.WriteMessage("\n"); // doc.Editor.Regen(); //询问保持还是取消第三个事务中的修改 PromptKeywordOptions pKeyOpts = new PromptKeywordOptions(""); pKeyOpts.Message = "\nKeep color change "; pKeyOpts.Keywords.Add("Yes"); pKeyOpts.Keywords.Add("No"); pKeyOpts.Keywords.Default = "No"; pKeyOpts.AllowNone = true; PromptResult pKeyRes = doc.Editor.GetKeywords(pKeyOpts); if (pKeyRes.StringResult == "No") { // t.Abort(); // 如果程序出错,我们可以使用Abort方法回滚事务中所作的修改 acTrans3.Abort(); //取消事务3中的修改 } else { acTrans3.Commit(); //保存事务3中的修改 } } doc.Editor.WriteMessage("\nNumber of transactions active: " + acTransMgr.NumberOfActiveTransactions.ToString()); acTrans2.Commit(); } doc.Editor.WriteMessage("\nNumber of transactions active: " + acTransMgr.NumberOfActiveTransactions.ToString()); acTrans1.Commit(); // Keep the changes to transaction 1保留事务1中的修改 } #endregion }
public static void zhushi() { //1getstsring() AcadApp.Document acDoc = AcadApp.Application.DocumentManager.MdiActiveDocument; //PromptStringOptions pStrOpts = new PromptStringOptions("\nEnter your name: "); //pStrOpts.AllowSpaces = true;//AllowSpaces属性控制提示是否可以输入空格,如果设置为false,按空格键就终止输入。 //PromptResult pStrRes = acDoc.Editor.GetString(pStrOpts); //AcadApp.Application.ShowAlertDialog("The name entered was: " + pStrRes.StringResult); //GetPoint方法提示用户在Command提示时指定一个点。PromptPointOptions对象的UseBasePoint属性和BasePoint属性控制是否从基点绘制一条橡皮带线。PromptPointOptions对象的Keywords属性用来定义除了指定点外还可以在Command提示光标处输入的关键字。 //Database acCurDb = acDoc.Database; //PromptPointResult pPtRes; //PromptPointOptions pPtOpts = new PromptPointOptions("1"); //// Prompt for the start point //pPtOpts.Message = "\nEnter the start point of the line: "; //pPtRes = acDoc.Editor.GetPoint(pPtOpts); //Point3d ptStart = pPtRes.Value; //// Exit if the user presses ESC or cancels the command //if (pPtRes.Status == PromptStatus.Cancel) return; //// Prompt for the end point //pPtOpts.Message = "\nEnter the end point of the line: "; //pPtOpts.UseBasePoint = true; //pPtOpts.BasePoint = ptStart; //pPtRes = acDoc.Editor.GetPoint(pPtOpts); //Point3d ptEnd = pPtRes.Value; //if (pPtRes.Status == PromptStatus.Cancel) return; //// Start a transaction //using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) //{ // BlockTable acBlkTbl; // BlockTableRecord acBlkTblRec; // // Open Model space for write // acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; // acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; // // Define the new line // Line acLine = new Line(ptStart, ptEnd); // // Add the line to the drawing // acBlkTblRec.AppendEntity(acLine); // acTrans.AddNewlyCreatedDBObject(acLine, true); // // Zoom to the extents or limits of the drawing // acDoc.SendStringToExecute("._zoom _all ", true, false, false); // acTrans.Commit(); //} //GetKeywords方法提示用户在Command提示光标处输入一个关键字。PromptKeywordOptions对象用来控制键入及提示信息呈现方式。PromptKeywordOptions对象的Keywords属性用来定义可在Command提示光标处键入的关键字。 //从AutoCAD命令行获取用户输入的关键字 //下例将PromptKeywordOptions对象的AllowNone属性设置为false(不允许直接回车),这样使用户必须输入一个关键字。Keywords属性用来添加允许的合法关键字。 PromptKeywordOptions pKeyOpts = new PromptKeywordOptions(""); pKeyOpts.Message = "\nEnter an option "; pKeyOpts.Keywords.Add("Line"); pKeyOpts.Keywords.Add("Circle"); pKeyOpts.Keywords.Add("Arc"); //pKeyOpts.AllowNone = false; pKeyOpts.Keywords.Default = "Arc"; pKeyOpts.AllowNone = true; PromptResult pKeyRes = acDoc.Editor.GetKeywords(pKeyOpts); AcadApp.Application.ShowAlertDialog("Entered keyword: " + pKeyRes.StringResult); ////更用户友好的关键字提示方式是如果用户按Enter键(没有输入)时提供一个缺省值。注意下面的这个小小改动 //4 //PromptIntegerOptions pIntOpts = new PromptIntegerOptions(""); //pIntOpts.Message = "\nEnter the size or "; //// Restrict input to positive and non-negative values ////限制输入必须大于0; //pIntOpts.AllowZero = false; //pIntOpts.AllowNegative = false; //// Define the valid keywords and allow Enter ////定义合法关键字并允许直接按Enter键; //pIntOpts.Keywords.Add("Big"); //pIntOpts.Keywords.Add("Small"); //pIntOpts.Keywords.Add("Regular"); //pIntOpts.Keywords.Default = "Regular"; //pIntOpts.AllowNone = true; //// Get the value entered by the user ////获取用户键入的值 //PromptIntegerResult pIntRes = acDoc.Editor.GetInteger(pIntOpts); //if (pIntRes.Status == PromptStatus.Keyword) //{ // AcadApp. Application.ShowAlertDialog("Entered keyword: " + pIntRes.StringResult); //} //else //{ // AcadApp.Application.ShowAlertDialog("Entered value: " + pIntRes.Value.ToString()); //} ////PromptKeywordOptions opts=new PromptKeywordOptions("Offset Project"); //用户选择的是椭圆,则加入关键字让用户在命令行中进行选择来对椭圆进行投影或平移 ////opts.Keywords.Add("Project"); //加入关键字"Project",它表示对椭圆进行投影 ////opts.Keywords.Add("Offset"); //加入关键字"Offset",它表示对椭圆进行平移 ////opts.Keywords.Default="Project"; //设置缺省的关键字为"Project",当用户直接按空格或回车的话,相当于在命令行中键入了"Project" ////PromptResult resKey=ed.GetKeywords(opts); //获取用户输入的关键字 }
public ObjectIdCollection AddLineandcirclr() { ObjectIdCollection objcoll = new ObjectIdCollection(); //过程都是先得到数据库,然后依次打开块表、块表记录,接着添加实体,最后关闭块表、块表记录。 // Database db = HostApplicationServices.WorkingDatabase;//获得当前工作空间的数据库 AcadApp.Document doc = AcadApp.Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; // 开始事务处理,也就是往CAD中加入东西 Circle circle; ObjectId objcid, objlid; using (Transaction tran = db.TransactionManager.StartTransaction()) { BlockTable bt = (BlockTable)tran.GetObject(db.BlockTableId, OpenMode.ForRead);// 得到块表 // // 获得AutoCAD块表,AutoCAD将加入到图形中的对象的信息都放在这个表中 BlockTableRecord btr = (BlockTableRecord)tran.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);//得到模型空间的块表纪录 //*** // 使用当前的空间Id来获取块表记录——注意我们是打开它用来写入 // *** BlockTableRecord btr = (BlockTableRecord)tran.GetObject(db.CurrentSpaceId, OpenMode.ForWrite); Line l = new Line(new Point3d(0, 0, 0), new Point3d(200, 200, 0)); // 定义一个Circle对象来表示你要生成的圆,传入的第二个参数为圆的法向,就是把圆生成在什么面上,因为AutoCAD程序一般都是平面问题,因此你一般都把这个法向量定义成//z轴方向。 circle = new Circle(new Point3d(200, 200, 0), new Vector3d(0.0, 0.0, 1.0), 50); // Vector3d.ZAxis objlid = btr.AppendEntity(l);//将直线加入到模型空间中 // 向块表记录加入圆的相关信息 tran.AddNewlyCreatedDBObject(l, true); objcoll.Add(objlid); objcid = btr.AppendEntity(circle); objcoll.Add(objcid); tran.AddNewlyCreatedDBObject(circle, true); tran.Commit(); //一旦完成以上操作,我们就提交事务处理,这样以上所做的改变就被保存了…… //然后销毁事务处理,因为我们已经完成了相关的操作(事务处理不是数据库驻留对象,可以销毁) } System.Diagnostics.Trace.WriteLine(objcid.ToString()); //面的代码是根据用户在命令行中的选择来改变圆的颜色。 Editor ed = doc.Editor; //Editor ed = Entities.Editor; // PromptKeywordOptions定义一个关键字列表选项 PromptKeywordOptions opt = new PromptKeywordOptions("选择颜色[绿色(G)/蓝色(B)]<红色(R)>"); //加入关键字列表 opt.Keywords.Add("R"); opt.Keywords.Add("G"); opt.Keywords.Add("B"); //获取用户输入的关键字 PromptResult result = ed.GetKeywords(opt); //判断是否输入了定义的关键字 if (result.Status == PromptStatus.OK) { //根据用户选择的关键字,来改变圆的颜色 switch (result.StringResult) { case "R": // PutColorIndex是ZHFARX库中改变对象颜色的函数 ChangeColorIndex(objcoll, 1); break; case "G": ChangeColorIndex(objcoll, 3); break; case "B": ChangeColorIndex(objcoll, 5); break; } } return objcoll; }
//Get selected AEC Objects (Only works for Conduit as of V1.0) public void GetAECObjects(Double distRes) { Document doc = Application.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; try { PromptSelectionResult psr = ed.SelectImplied(); //Get user selection. if (psr.Status == PromptStatus.OK) { ed.SetImpliedSelection(new ObjectId[0]); } else { PromptSelectionOptions selOpts = new PromptSelectionOptions(); selOpts.MessageForAdding = "\nSelect objects: "; psr = ed.GetSelection(selOpts); } // Get the selected objects one by one. Transaction tr = doc.TransactionManager.StartTransaction(); using (tr) { try { double[] partSizes = new double[50]; // accept 50 selected objects string[] partCndtType = new string[50]; double[] pSizeMult = new double[50]; // accept 50 selected objects int total = 0; ObjectId[] objIds = psr.Value.GetObjectIds(); //Ask for weight Table type String weightTable = ""; PromptKeywordOptions pko = new PromptKeywordOptions(""); pko.Message = "\nEnter table to use calculations from "; pko.Keywords.Add("Water"); pko.Keywords.Add("Conductor"); pko.Keywords.Default = "Water"; pko.AllowNone = true; PromptResult pr = ed.GetKeywords(pko); weightTable = pr.StringResult; //Loop through Selected Conduits. foreach (ObjectId objId in objIds) { Entity ent = (Entity)tr.GetObject(objId, OpenMode.ForRead); //use entity as object type to find. Member mem = tr.GetObject(objId, OpenMode.ForRead) as Member; //set as member (needed to process AEC) partSizes[total] = GetPartSize(mem); partCndtType[total] = GetPartCndtType(mem); pSizeMult[total] = CalcWeightPerFoot(partSizes[total].ToString(), partCndtType[total], weightTable); //now call the calculation loop for each size. ed.WriteMessage("\n[" + total.ToString() + "] " + partSizes[total].ToString() + " x " + pSizeMult[total].ToString()); //write out to command line for verification. total += 1; //increase increment for loop. } Double multSum = pSizeMult.Sum(); //sum up the multipliers for use later. ed.WriteMessage("\n\nThe Sum of the multipliers= " + multSum.ToString()); /*Finally Calculate the Point Load weight.*/ // Convert the distance to feet. distRes = distRes / 12; ed.WriteMessage("\n\nFormula: (" + multSum.ToString() + " * " + distRes.ToString() + ") / 2"); // Multiply the sum of the multipliers by the distance, then divide by 2 to get the individual point load. Double finalCalc = (multSum * distRes) / 2; finalCalc = Math.Round(finalCalc, 1); //Round the calculation to 1 decimal point ex. 3.4 ed.WriteMessage("\n\nThe point load= " + finalCalc.ToString() + " x2"); // Place point load tag on drawing. Class2.Commands.ImportBlocks(); //Imports the dynamic block from external dwg. Class2.Commands.BlockJigCmd(finalCalc); //Jigs the block with the correct values and places in drawing at user point. } catch (SystemException ex) { ed.WriteMessage("Error" + ex.ToString()); } tr.Commit(); } } catch (SystemException ex) { ed.WriteMessage("Error " + ex.ToString()); } }
public void KWandStringTest() { Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; PromptStringOptions stropts = new PromptStringOptions("Enter a string you want to use as keyword"); PromptKeywordOptions kwopts = new PromptKeywordOptions("Enter a string you want to use as keyword"); stropts.AllowSpaces = false; PromptResult str = ed.GetString(stropts); kwopts.Keywords.Add(str.StringResult); kwopts.Keywords.Add("onemore"); kwopts.Message = "Enter the word that u just enterd to test if its a valid keyword or not"; PromptResult kw = ed.GetKeywords(kwopts); if(kw.Status == PromptStatus.OK) { ed.WriteMessage("You entered a valid keyword"); } else { ed.WriteMessage("You didn't enter a valid keyword: "+kw.Status.ToString()); } }
public void CMD_PosLicense() { LicenseInformation(); Autodesk.AutoCAD.ApplicationServices.Application.DisplayTextScreen = true; PromptKeywordOptions opts = new PromptKeywordOptions("Lisansınızı değiştirmek istiyor musunuz? [Evet/Hayır]: ", "Yes No"); opts.AllowNone = false; PromptResult result = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetKeywords(opts); if (result.Status == PromptStatus.OK) { switch (result.StringResult) { case "Yes": RequestLicense(); break; } } }
public void CMD_PosLength() { if (!CheckLicense()) return; PromptSelectionResult selresult = DWGUtility.SelectAllPosUser(); if (selresult.Status != PromptStatus.OK) return; PromptKeywordOptions opts = new PromptKeywordOptions("L boyunu [Göster/giZle]: ", "Show Hide"); opts.AllowNone = false; PromptResult result = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetKeywords(opts); if (result.Status == PromptStatus.OK) { switch (result.StringResult) { case "Show": ShowPosLength(selresult.Value.GetObjectIds(), true); break; case "Hide": ShowPosLength(selresult.Value.GetObjectIds(), false); break; } } }
public void CMD_IncludePos() { if (!CheckLicense()) return; PromptSelectionResult selresult = DWGUtility.SelectAllPosUser(); if (selresult.Status != PromptStatus.OK) return; PromptKeywordOptions opts = new PromptKeywordOptions("Metraja [Dahil et/metrajdan Cikar]: ", "Add Remove"); opts.AllowNone = false; PromptResult result = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetKeywords(opts); if (result.Status == PromptStatus.OK) { switch (result.StringResult) { case "Add": IcludePosinBOQ(selresult.Value.GetObjectIds(), true); break; case "Remove": IcludePosinBOQ(selresult.Value.GetObjectIds(), false); break; } } }
public void DeleteAllGroupInformation() { Editor ed = dwg.Editor; PromptKeywordOptions pkOpts = new PromptKeywordOptions( "\nВы собираетесь удалить всю информацию о группах с чертежа. Точно? [Yes/No]", "Yes No"); pkOpts.AllowArbitraryInput = false; pkOpts.AllowNone = false; PromptResult res = ed.GetKeywords(pkOpts); switch (res.StringResult) { case "Yes": ed.WriteMessage("\nВперёд!!!"); using (Transaction tr = CurrentDatabase.TransactionManager.StartTransaction()) { GroupsInformation groupEntities = new GroupsInformation(tr, CurrentDatabase); foreach (string group in groupEntities.GroupList) { foreach (ObjectId id in groupEntities.GetObjectsOfGroup(group)) { groupEntities.DeleteGroupFromObject(id, group); } } tr.Commit(); } break; case "No": ed.WriteMessage("\nФфух!"); break; } }
private bool? TryGetAdditionalStirrups(string promptMessage) { PromptKeywordOptions options = new PromptKeywordOptions(promptMessage, "TAK NIE"); options.Keywords.Default = "NIE"; options.AllowNone = false; PromptResult result = editor.GetKeywords(options); if (result.Status == PromptStatus.OK) { return (result.StringResult == "TAK") ? true : false; } else { acMark.RemoveMarks(); return null; } }
public static void PromptAndPlot(Document doc) { Editor ed = doc.Editor; PlotOptions plotOpt = new PlotOptions(); bool repeat = false; do { var optPrompt = new PromptKeywordOptions($"\nПечать листов в PDF из текущего чертежа, выбранных файлов или из всех чертежей в папке."); optPrompt.Keywords.Add("Текущего"); optPrompt.Keywords.Add("Папки"); optPrompt.Keywords.Add("Настройки"); optPrompt.Keywords.Default = "Папки"; var resPrompt = ed.GetKeywords(optPrompt); if (resPrompt.Status == PromptStatus.OK) { if (resPrompt.StringResult == "Текущего") { repeat = false; Logger.Log.Info("Текущего"); if (!File.Exists(doc.Name)) { throw new Exception("Нужно сохранить текущий чертеж."); } string filePdfName = Path.Combine(Path.GetDirectoryName(doc.Name), Path.GetFileNameWithoutExtension(doc.Name) + ".pdf"); PlotDirToPdf plotter = new PlotDirToPdf(new string[] { doc.Name }, filePdfName); plotter.Options = plotOpt; plotter.Plot(); } else if (resPrompt.StringResult == "Папки") { repeat = false; Logger.Log.Info("Папки"); var dialog = new UI.FileFolderDialog(); dialog.Dialog.Multiselect = true; dialog.IsFolderDialog = true; dialog.Dialog.Title = "Выбор папки или файлов для печати чертежей в PDF."; dialog.Dialog.Filter = "Чертежи|*.dwg"; dialog.Dialog.InitialDirectory = Path.GetDirectoryName(doc.Name); if (dialog.ShowDialog() == DialogResult.OK) { PlotDirToPdf plotter; string firstFileNameWoExt = Path.GetFileNameWithoutExtension(dialog.Dialog.FileNames.First()); if (dialog.Dialog.FileNames.Count() > 1) { plotter = new PlotDirToPdf(dialog.Dialog.FileNames, Path.GetFileName(dialog.SelectedPath)); } else if (firstFileNameWoExt.Equals("п", StringComparison.OrdinalIgnoreCase)) { plotter = new PlotDirToPdf(dialog.SelectedPath); } else { plotter = new PlotDirToPdf(dialog.Dialog.FileNames, firstFileNameWoExt); } plotter.Options = plotOpt; plotter.Plot(); } } else if (resPrompt.StringResult == "Настройки") { // Сортировка; Все файлы в один пдф или для каждого файла отдельная пдф plotOpt.Show(); repeat = true; } } else { ed.WriteMessage("\nОтменено пользователем."); return; } } while (repeat); }
private PromptResult GetElementTypeToSign() { PromptKeywordOptions elementOptions = new PromptKeywordOptions("Co podpisać? [Wall/Column] : ", "Wall Column"); elementOptions.Keywords.Default = "Column"; PromptResult element = editor.GetKeywords(elementOptions); return element; }
/// <summary> /// Creates a new Topology from users input of the name, description, type /// and selected entities in the drawing file /// </summary> public void CreateMapTopology() { string name = ""; string description = ""; string typeName = ""; //Get the name, description, type string. PromptResult promptResult = Utility.AcadEditor.GetString("\nEnter the Topology name:"); if (promptResult.Status == PromptStatus.Cancel) return; name = promptResult.StringResult; promptResult = Utility.AcadEditor.GetString("\nEnter the new Topology Description:"); if (promptResult.Status == PromptStatus.Cancel) return; description = promptResult.StringResult; PromptKeywordOptions options = new PromptKeywordOptions("\nEnter the new Topology Type: "); options.Keywords.Add("Node"); options.Keywords.Add("netWork"); options.Keywords.Add("Polygon"); options.Keywords.Default = "Polygon"; promptResult = Utility.AcadEditor.GetKeywords(options); if (promptResult.Status == PromptStatus.Cancel) return; typeName = promptResult.StringResult; TopologyTypes topoType; //Parse the type if (string.Compare(typeName, "Polygon", true) == 0) { topoType = TopologyTypes.Polygon; } else if (string.Compare(typeName, "Node", true) == 0) { topoType = TopologyTypes.Point; } else if (string.Compare(typeName, "Network", true) == 0) { topoType = TopologyTypes.Linear; } else { Utility.AcadEditor.WriteMessage("\nInvalid Topology type."); return; } // Get the selection set according to the type ObjectIdCollection polygonCentroidCollection = new ObjectIdCollection(); ObjectIdCollection linkCollection = new ObjectIdCollection(); ObjectIdCollection nodeCollection = new ObjectIdCollection(); try { switch (topoType) { case TopologyTypes.Polygon: Utility.AcadEditor.WriteMessage("\nSelect centroids to add to the new topology: "); HelperFunctions.SelectIds(polygonCentroidCollection); Utility.AcadEditor.WriteMessage("\nSelect links to add to the new topology: "); HelperFunctions.SelectIds(linkCollection); Utility.AcadEditor.WriteMessage("\nSelect nodes to add to the new topology: "); HelperFunctions.SelectIds(nodeCollection); break; case TopologyTypes.Linear: Utility.AcadEditor.WriteMessage("\nSelect links to add to the new topology: "); HelperFunctions.SelectIds(linkCollection); Utility.AcadEditor.WriteMessage("\nSelect nodes to add to the new topology: "); HelperFunctions.SelectIds(nodeCollection); break; case TopologyTypes.Point: Utility.AcadEditor.WriteMessage("\nSelect nodes to add to the new topology: "); HelperFunctions.SelectIds(nodeCollection); break; } } catch (Autodesk.AutoCAD.Runtime.Exception expt) { Utility.AcadEditor.WriteMessage(string.Format("\nAutodesl.AutoCAD.Runtime.Exception throwed out containing the error status: {0}", expt.ErrorStatus)); return; } CreateMapTopology(name, description, topoType, polygonCentroidCollection, linkCollection, nodeCollection); }
private void btnAlign_Click(object sender, EventArgs e) { Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; using (EditorUserInteraction UI = ed.StartUserInteraction(this)) { PromptEntityOptions opts = new PromptEntityOptions("\nSelect entity: "); opts.AllowNone = false; opts.SetRejectMessage("\nSelect a LINE, ARC or POLYLINE entity."); opts.AddAllowedClass(typeof(Curve), false); PromptEntityResult per = ed.GetEntity(opts); if (per.Status == PromptStatus.OK) { Point3d pt = per.PickedPoint; ObjectId id = per.ObjectId; bool posUp = false; Vector3d dir = new Vector3d(), up = new Vector3d(), normal = new Vector3d(); Database db = HostApplicationServices.WorkingDatabase; using (Transaction tr = db.TransactionManager.StartTransaction()) { try { RebarPos pos = (RebarPos)tr.GetObject(m_Pos, OpenMode.ForRead); Curve curve = (Curve)tr.GetObject(id, OpenMode.ForRead); pt = curve.GetClosestPointTo(pt, curve.GetPlane().Normal, false); dir = curve.GetFirstDerivative(pt); dir = dir * pos.DirectionVector.Length / dir.Length; normal = pos.NormalVector; normal = normal * pos.DirectionVector.Length / normal.Length; up = dir.CrossProduct(normal); up = up * pos.DirectionVector.Length / up.Length; posUp = (dir.DotProduct(pos.UpVector) > 0); } catch (System.Exception ex) { System.Windows.Forms.MessageBox.Show("Error: " + ex.Message, "RebarPos", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); } } double offset = 0.0; double offset1 = -0.75, offset2 = 1.75; if (posUp) { AlignPos(pt + offset1 * up, dir, up, normal); offset = offset2; } else { AlignPos(pt + offset2 * up, dir, up, normal); offset = offset1; } PromptKeywordOptions kopts = new PromptKeywordOptions("\nDiğer tarafa yerleştirilsin mi? [Evet/Hayır] <Hayir>: ", "Yes No"); kopts.AllowNone = true; PromptResult kres = ed.GetKeywords(kopts); if (kres.Status == PromptStatus.None || kres.StringResult == "Yes") { AlignPos(pt + offset * up, dir, up, normal); ed.UpdateScreen(); } } } }