private void btnOk_Click(object sender, EventArgs e) { int num; string str; this.TypeFlag = ( from kvp in this._chkBoxes where kvp.Value.Checked select kvp.Key).Sum(); this.EntityTypeFlag = ( from kvp in this._chkEntTypes where kvp.Value.Checked select kvp.Key).Sum(); this.StartValue = this.txtValue.Text; this.Separator = this.txtSeparator.Text; if (this.TypeFlag == 0) { AcAp.ShowAlertDialog("Tidak ada Block."); return; } if (!this.IsValidString(this.StartValue, this.Separator)) { AcAp.ShowAlertDialog("Invalid Nilai"); this.txtValue.Select(); return; } if (this.TypeFlag == 16 && int.TryParse(this.StartValue, out num)) { this.StartValue = ((Romawi)num).ToString(); } base.DialogResult = DialogResult.OK; //base.Close(); }
public static void OpenSaveDwgFiles() { List <Sheet> dict = new List <Sheet>(); try { var path = @"C:\Users\yusufzhon.marasulov\Desktop\test"; DirectoryInfo d = new DirectoryInfo(path); FileInfo[] Files = d.GetFiles("*.dwg"); foreach (FileInfo file in Files) { var fileName = Path.GetFileName(file.FullName); string dwgFlpath = file.FullName; using (Database db = new Database(false, true)) { db.ReadDwgFile(dwgFlpath, FileOpenMode.OpenForReadAndAllShare, false, null); using (Transaction tr = db.TransactionManager.StartTransaction()) { ObjectId mSpaceId = SymbolUtilityServices.GetBlockModelSpaceId(db); ObjectIdCollection idArray = Utils.SelectDynamicBlockReferences(mSpaceId); GetSheetsFromBlocks(Active.Editor, dict, tr, idArray); tr.Commit(); } db.SaveAs(dwgFlpath, DwgVersion.Current); } } Application.ShowAlertDialog("All files processed"); } catch (System.Exception ex) { Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage(ex.ToString()); } }
public void PlusIndex() { Editor ed = AcadApp.DocumentManager.MdiActiveDocument.Editor; var peo = new PromptEntityOptions("\n选择一个编号"); peo.SetRejectMessage("选择块"); peo.AddAllowedClass(typeof(BlockReference), true); var per = ed.GetEntity(peo); if (per.Status == PromptStatus.OK) { Database db = HostApplicationServices.WorkingDatabase; using (var tr = db.TransactionManager.StartTransaction()) { var indexBlock = (BlockReference)per.ObjectId.GetObject(OpenMode.ForRead); string currIndex = indexBlock.ObjectId.GetAttributeInBlockReference("编号"); try { indexBlock.ObjectId.UpdateAttributesInBlock("编号", (Convert.ToInt32(currIndex) + 1).ToString()); } catch (System.Exception) { AcadApp.ShowAlertDialog("\n当前内容不支持序号加 1"); } tr.Commit(); } } }
private void chkSelBlock_CheckedChanged(object sender, EventArgs e) { bool flag; if (!chkSelBlock.Checked) { ComboBox combobox = this.cbxSelBlk; int num = 0; flag = Convert.ToBoolean(num); this.cbxSelTag.Enabled = Convert.ToBoolean(num); combobox.Enabled = flag; return; } if (this.cbxSelBlk.Items == null || this.cbxSelBlk.Items.Count <= 0) { AcAp.ShowAlertDialog("None block with attributes in this drawing."); this.chkSelBlock.Checked = false; return; } ComboBox combobox1 = this.cbxSelBlk; int num1 = 1; flag = Convert.ToBoolean(num1); this.cbxSelTag.Enabled = Convert.ToBoolean(num1); CheckBox checkbox = this.chkMtext; int num2 = 0; flag = Convert.ToBoolean(num2); this.chkSelText.Checked = Convert.ToBoolean(num2); checkbox.Checked = flag; }
[CommandMethod("GetIntegerOrKeywordFromUser")]//提示用户输入一个非零的正整数或一个关键字 public static void GetIntegerOrKeywordFromUser() { Document acDoc = Application.DocumentManager.MdiActiveDocument; PromptIntegerOptions pIntOpts = new PromptIntegerOptions(""); pIntOpts.Message = "\nEnter the size or "; // 限制输入必须大于0 pIntOpts.AllowZero = false; pIntOpts.AllowNegative = false; // 定义合法关键字并允许直接按Enter键 pIntOpts.Keywords.Add("Big"); pIntOpts.Keywords.Add("Small"); pIntOpts.Keywords.Add("Regular"); pIntOpts.Keywords.Default = "Regular"; pIntOpts.AllowNone = true; // 获取用户键入的值 PromptIntegerResult pIntRes = acDoc.Editor.GetInteger(pIntOpts); if (pIntRes.Status == PromptStatus.Keyword) { Application.ShowAlertDialog("Entered keyword: " + pIntRes.StringResult); } else { Application.ShowAlertDialog("Entered value: " + pIntRes.Value.ToString()); } }
public void ChangeCarType() { Database db = HostApplicationServices.WorkingDatabase; using (var tr = db.TransactionManager.StartTransaction()) { List <BlockReference> cars = db.GetSelectionOfBlockRefs("\n选择车", false, carBlockName); if (cars.Count == 0) { AcadApp.ShowAlertDialog("选中数量为0"); } else { foreach (var car in cars) { var currCarType = car.ObjectId.GetDynBlockValue("类型"); switch (currCarType) { case "微型车位": car.ObjectId.SetDynBlockValue("类型", "普通车位"); break; case "普通车位": car.ObjectId.SetDynBlockValue("类型", "微型车位"); break; } } } tr.Commit(); } }
public static void ShowWCSAndUCS(Point3d p) { Document acDoc = Application.DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { Point3d pPt3dWCS = p; Point3d pPt3dUCS = p; ViewportTableRecord acVportTblRec; acVportTblRec = acTrans.GetObject(acDoc.Editor.ActiveViewportId, OpenMode.ForWrite) as ViewportTableRecord; Matrix3d newMatrix = new Matrix3d(); newMatrix = Matrix3d.AlignCoordinateSystem(Point3d.Origin, Vector3d.XAxis, Vector3d.YAxis, Vector3d.ZAxis, acVportTblRec.Ucs.Origin, acVportTblRec.Ucs.Xaxis, acVportTblRec.Ucs.Yaxis, acVportTblRec.Ucs.Zaxis); pPt3dWCS = pPt3dWCS.TransformBy(newMatrix); Application.ShowAlertDialog("The WCS coordinates are: \n" + pPt3dWCS.ToString() + "\n" + "The UCS coordinates are: \n" + pPt3dUCS.ToString()); acTrans.Commit(); } }
public void PolylineHatch() { Database db = HostApplicationServices.WorkingDatabase; using (var tr = db.TransactionManager.StartTransaction()) { //Polyline pl = new Polyline(); ////pl.CreatePolyline(Point2d.Origin, new Point2d(0, 50), new Point2d(50, 50)); ////pl.Closed = true; ////pl.CreateRectangle(Point2d.Origin, new Point2d(50, 50)); //pl.CreatePolygon(Point2d.Origin, 6, 50); //db.AddToCurrentSpace(pl); var tsId = db.AddTextStyle("test", "sceie.shx", "sceic.shx", 0.7); if (tsId != ObjectId.Null) { DBText text = new DBText() { TextStyleId = tsId, //Position = new Point3d(25, 25, 0), Height = 20, TextString = "文字", HorizontalMode = TextHorizontalMode.TextCenter, VerticalMode = TextVerticalMode.TextVerticalMid, AlignmentPoint = new Point3d(25, 25, 0), }; db.AddToCurrentSpace(text); } else { AcadApp.ShowAlertDialog("字体样式添加失败。"); } tr.Commit(); } }
public void Execute(object parameter) { Application.ShowAlertDialog("실행"); //if (parameter is RibbonButton) //{ // RibbonButton button = parameter as RibbonButton; // CallBack(button.Id); //} }
/// <summary> /// ReadPNote is read Note in general, can be from database, can be from dwg depends on current situation. /// If dwgPNote is opened, is active or not, is modified or not (can't check whether or not it is modied), refer to read from DWG and updateDatabase. /// If dwgPNote is Not open check date, if if equals, read from database. /// Else: read from file + udpate todatabase. /// FK IT, JUST FOUND DOWN THE INTEROPT SHIT /// </summary> /// <param name="connection"></param> /// <returns></returns> public static NODEDWG ReadDataPNode(SQLiteConnection connection) { NODEDWG note = null; string notePath = GoodiesPath.GetNotePathFromADwgPath(Application.DocumentManager.MdiActiveDocument.Name, connection); if (!string.IsNullOrEmpty(notePath)) { if (Goodies.GetListOfDocumentOpening().Contains(notePath)) { Document doc = Goodies.GetDocumentFromDwgpath(notePath); if (doc == null) { Application.ShowAlertDialog("ReadDwgNoteFile -> There is no Document, weird!"); return(null); } AcadDocument acadDoct = (AcadDocument)doc.GetAcadDocument(); if (acadDoct.Saved && GoodiesPath.IsDateTheSame(notePath, connection)) { note = ReadFromDatabase(connection); } else { using (Database db = doc.Database) { note = GetData(db, connection); } } } else { Database db = new Database(); try { if (GoodiesPath.IsDateTheSame(notePath, connection)) { note = ReadFromDatabase(connection); } else { db.ReadDwgFile(notePath, FileOpenMode.OpenForReadAndAllShare, false, ""); note = GetData(db, connection); } }catch (Exception e) { MessageBox.Show(e.Message); } } } return(note); }
private void button1_Click(object sender, EventArgs e) { if (atextBox1.Text.Length > 0 && dtextBox2.Text.Length > 0 && btextBox4.Text.Length > 0 && daDtextBox3.Text.Length > 0 && rtextBox5.Text.Length > 0) { DrawDwg(Convert.ToDouble(atextBox1.Text), Convert.ToDouble(btextBox4.Text), Convert.ToDouble(daDtextBox3.Text), Convert.ToDouble(rtextBox5.Text)); } else { Application.ShowAlertDialog("请输入有效参数"); } }
private void cbxBlock_Validating(object sender, CancelEventArgs e) { string text = this.cbxBlock.Text; if (text == "") { return; } BlockTable obj = this._db.BlockTableId.GetObject <BlockTable>(); if (obj.Has(text)) { BlockTableRecord blockTableRecords = obj[text].GetObject <BlockTableRecord>(); AttributeDefinition[] arrayAttDef = ( from att in blockTableRecords.GetObjects <AttributeDefinition>() where !att.Constant select att).ToArray <AttributeDefinition>(); if (arrayAttDef != null && arrayAttDef.Length != 0) { this.cbxBlock.SelectedItem = blockTableRecords; return; } AcAp.ShowAlertDialog(("Block terpilih tidak terdapat Attribute Reference.")); this.cbxBlock.SelectAll(); return; } ObjectId block = obj.GetBlock(text); if (block == ObjectId.Null) { AcAp.ShowAlertDialog("Block '" + text + "'Tidak ada."); this.cbxBlock.SelectAll(); return; } BlockTableRecord obj1 = block.GetObject <BlockTableRecord>(); AttributeDefinition[] arrayDef = ( from att in obj1.GetObjects <AttributeDefinition>() where !att.Constant select att).ToArray <AttributeDefinition>(); if (arrayDef == null || arrayDef.Length == 0) { AcAp.ShowAlertDialog("Tidak Ada Attribute pada Block yang dipilih."); this.cbxBlock.SelectAll(); return; } if (!this.cbxBlock.Items.Contains(obj1)) { this.cbxBlock.DataSource = this._db.GetBlocksWithAttribute(); } this.cbxBlock.SelectedItem = obj1; }
[CommandMethod("GetKeyword")]//关键字 public static void GetKeywordFromUser2() { Document acDoc = Application.DocumentManager.MdiActiveDocument; PromptKeywordOptions pKeyOpts = new PromptKeywordOptions(""); pKeyOpts.Message = "\nEnter an option "; pKeyOpts.Keywords.Add("Line"); pKeyOpts.Keywords.Add("Circle"); pKeyOpts.Keywords.Add("Arc"); pKeyOpts.Keywords.Default = "Arc"; pKeyOpts.AllowNone = true; PromptResult pKeyRes = acDoc.Editor.GetKeywords(pKeyOpts); Application.ShowAlertDialog("Entered keyword: " + pKeyRes.StringResult); }
public void InsertBlock() { Database db = HostApplicationServices.WorkingDatabase; using (var tr = db.TransactionManager.StartTransaction()) { //块定义 if (!AddIndexBtr()) { AcadApp.ShowAlertDialog($"{indexBlockName} 创建块定义失败。"); return; } Editor ed = AcadApp.DocumentManager.MdiActiveDocument.Editor; //插入点 var ppr = ed.GetPoint(new PromptPointOptions("\n指定点")); if (ppr.Status != PromptStatus.OK) { return; } //序号值 var pir = ed.GetInteger(new PromptIntegerOptions("\n请输入序号")); if (pir.Status != PromptStatus.OK) { return; } //属性 Dictionary <string, string> atts = new Dictionary <string, string> { { "编号", pir.Value.ToString() } }; //添加图层 db.AddLayer(indexLayer, "标注图层"); //插入块 var brefId = db.CurrentSpaceId.InsertBlockReference(indexLayer, indexBlockName, ppr.Value, new Scale3d(1), 0, atts); if (brefId == ObjectId.Null) { AcadApp.ShowAlertDialog($"{indexBlockName} 块插入失败。"); } tr.Commit(); } }
private void SelectPolyline() { Editor acDocEd = Application.DocumentManager.MdiActiveDocument.Editor; PromptSelectionResult acPSR; SelectionSet acSSet; acPSR = acDocEd.GetSelection(); // 선택한 객체를 받음 if (acPSR.Status == PromptStatus.OK) { acSSet = acPSR.Value; Application.ShowAlertDialog("Number of objects selected: " + acSSet.Count.ToString()); } else { Application.ShowAlertDialog("Number of objects selected: 0"); } }
private void btnBrowse_Click(object sender, EventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); ofd.DefaultExt = ".dwg"; ofd.Title = "Pilih File Block"; ofd.RestoreDirectory = true; ofd.Multiselect = false; if (ofd.ShowDialog() != DialogResult.OK) { return; } ObjectId block = this._db.BlockTableId.GetObject <BlockTable>().GetBlock(ofd.FileName); if (block == ObjectId.Null) { AcAp.ShowAlertDialog("Invalid File"); return; } BlockTableRecord obj = block.GetObject <BlockTableRecord>(); AttributeDefinition[] array = ( from att in obj.GetObjects <AttributeDefinition>() where !att.Constant select att).ToArray <AttributeDefinition>(); if (array == null || array.Length == 0) { AcAp.ShowAlertDialog(""); return; } if (!this.cbxBlock.Items.Contains(obj)) { this.cbxBlock.DataSource = this._db.GetBlocksWithAttribute(); } this.cbxBlock.SelectedItem = obj; }
public static List <Curve> SplitFoundation(List <Curve> allLines) { Document acDoc = Application.DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; List <Curve> centreLines = new List <Curve>(); using (Transaction tr = acCurDb.TransactionManager.StartTransaction()) { // Open the Block table for read BlockTable acBlkTbl = tr.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; // Open the Block table record Model space for write BlockTableRecord acBlkTblRec = tr.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; DBObjectCollection remove = new DBObjectCollection(); foreach (Curve c in allLines) { Point3dCollection points = new Point3dCollection(); foreach (Curve target in allLines) { Point3dCollection pointsAppend = new Point3dCollection(); c.IntersectWith(target, Intersect.OnBothOperands, points, IntPtr.Zero, IntPtr.Zero); foreach (Point3d p3d in pointsAppend) { points.Add(p3d); } } if (points.Count > 0) { List <double> splitPoints = new List <double>(); foreach (Point3d p3d in points) { try { splitPoints.Add(c.GetParameterAtPoint(p3d)); } catch (Autodesk.AutoCAD.Runtime.Exception e) { Application.ShowAlertDialog("Something may have gone wron with foundation processing - " + e.Message); } } splitPoints.Sort(); DoubleCollection acadSplitPoints = new DoubleCollection(splitPoints.ToArray()); DBObjectCollection split = c.GetSplitCurves(acadSplitPoints); foreach (Entity e in split) { acBlkTblRec.AppendEntity(e); tr.AddNewlyCreatedDBObject(e, true); centreLines.Add(e as Curve); } remove.Add(c); } } foreach (DBObject obj in remove) { obj.Erase(); } tr.Commit(); } return(centreLines); }
private void btnSelBlk_Click(object sender, EventArgs e) { Editor editor = AcAp.DocumentManager.MdiActiveDocument.Editor; PromptEntityOptions pEnt = new PromptEntityOptions("\nSelect Block: "); pEnt.AllowNone = true; pEnt.SetRejectMessage("Selected Object is not a Block!."); pEnt.AddAllowedClass(typeof(BlockReference), true); PromptEntityResult pEntRes = editor.GetEntity(pEnt); if (pEntRes.Status != PromptStatus.OK) { return; } BlockReference bRef = pEntRes.ObjectId.GetObject <BlockReference>(); Dictionary <string, string> dicTag = new Dictionary <string, string>(); for (int i = 0; i < bRef.AttributeCollection.Count; i++) { string strTag = bRef.AttributeCollection[i].GetObject <AttributeReference>(OpenMode.ForRead).Tag; string strTextString = bRef.AttributeCollection[i].GetObject <AttributeReference>(OpenMode.ForRead).TextString; dicTag.Add(strTag, strTextString); switch (i) { case 0: { lblTag1.Text = strTag; textString1.Text = strTextString; } break; case 1: { lblTag2.Text = strTag; textString2.Text = strTextString; } break; case 2: { lblTag3.Text = strTag; textString3.Text = strTextString; } break; case 3: { lblTag4.Text = strTag; textString4.Text = strTextString; } break; default: break; } } if (objRot.Checked) { this.BlockRotation = bRef.Rotation; txtBlkRot.Text = Converter.AngleToString(bRef.Rotation); } else { this.BlockRotation = Converter.StringToAngle(txtRot.Text); } txtRot.Text = Converter.AngleToString(bRef.Rotation); Autodesk.AutoCAD.DatabaseServices.AttributeCollection attRefColl = bRef.AttributeCollection; if (attRefColl == null || attRefColl.Count == 0) { AcAp.ShowAlertDialog("Selected Block do not have Attributes."); return; } this.cbxBlock.SelectedItem = (bRef.IsDynamicBlock ? bRef.DynamicBlockTableRecord.GetObject <BlockTableRecord>() : bRef.BlockTableRecord.GetObject <BlockTableRecord>()); }
public static void ShowAlertDialog(string str) { AcApp.ShowAlertDialog(str); }
/// <summary> /// 选择钢束按钮 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void buttonTendonSel_Click(object sender, RoutedEventArgs e) { buttonTendonSel.Content = "添加钢束"; Hide(); //启动CAD相关对象 Document doc = AcadApp.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; bool isTdInTbl = false; //初始化判断所选钢束是否已在表中的布尔值 using (Transaction trans = db.TransactionManager.StartTransaction()) //开始事务处理 using (DocumentLock loc = doc.LockDocument()) { SyncData.SyncTdGenParasToDlg(this); //将tdGenParas对象与对话框数据同步 db.SyncDwgToTdGenParas(); //在将图形数据库数据与tdGenParas对象同步 #region 1.选择钢束 List <AcadPolyline> tdLines = new List <AcadPolyline>(); //初始化存储钢束线的List for (;;) //无限循环 { tdLines = new List <AcadPolyline>(); //清空tds PromptSelectionOptions tdsOpt = new PromptSelectionOptions(); tdsOpt.MessageForAdding = "\n选择钢束线,需为无折角的多段线"; PromptSelectionResult tdsRes = ed.GetSelection(tdsOpt); if (tdsRes.Status == PromptStatus.Cancel) { this.Show();//重新显示对话框 return; } bool isPolyline = true;//设置是否选择集中均为多段线的布尔参数 if (tdsRes.Status == PromptStatus.OK) { SelectionSet sSet = tdsRes.Value; foreach (ObjectId tdId in sSet.GetObjectIds()) { AcadPolyline tdLine = tdId.GetObject(OpenMode.ForRead) as AcadPolyline; //获取钢束线 if (tdLine == null) //选择集中有非多段线 { AcadApp.ShowAlertDialog("选择集中含有非多段线,重新选择"); isPolyline = false; break;//退出循环 } tdLines.Add(tdLine); } if (isPolyline == false) { continue; //如果存在非多段线,则重新提示选择 } break; //结束选择 } } #endregion #region 2.扩展字典的读取或添加,并将信息列入表格 for (int i = 0; i < tdLines.Count; i++) { if (idsInTbl.Contains(tdLines[i].ObjectId)) { isTdInTbl = true; break; //钢束已在表中,不继续添加,退出循环 } idsInTbl.Add(tdLines[i].ObjectId); //将新的钢束加入列表中便于后续判断 string tdKey = "TendonHdl_" + tdLines[i].Handle.ToString(); // tdIdsInTable.Add(tdKey, tdLines[i].ObjectId); //加入表中钢束字典列表便于后续操作 } SyncData.SyncTdsToDwg(ref tdsInTbl, idsInTbl); #endregion trans.Commit();//执行事务处理 } dataGridTdInfo.ItemsSource = tdsInTbl; if (isTdInTbl) { MessageBox.Show("选择集中有表中已有钢束,已自动剔除!"); } Show(); }
/// <summary> /// Create a new UCS, make it active, and translate the coordinates of a point into the UCS coordinates /// https://knowledge.autodesk.com/search-result/caas/CloudHelp/cloudhelp/2017/ENU/AutoCAD-NET/files/GUID-096085E3-5AD5-4454-BF10-C9177FDB5979-htm.html /// </summary> public static void NewUCS() { // Get the current document and database, and start a transaction Document acDoc = Application.DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { // Open the UCS table for read UcsTable acUCSTbl; acUCSTbl = acTrans.GetObject(acCurDb.UcsTableId, OpenMode.ForRead) as UcsTable; UcsTableRecord acUCSTblRec; // Check to see if the "New_UCS" UCS table record exists if (acUCSTbl.Has("New_UCS") == false) { acUCSTblRec = new UcsTableRecord(); acUCSTblRec.Name = "New_UCS"; // Open the UCSTable for write acUCSTbl.UpgradeOpen(); // Add the new UCS table record acUCSTbl.Add(acUCSTblRec); acTrans.AddNewlyCreatedDBObject(acUCSTblRec, true); acUCSTblRec.Dispose(); } else { acUCSTblRec = acTrans.GetObject(acUCSTbl["New_UCS"], OpenMode.ForWrite) as UcsTableRecord; } acUCSTblRec.Origin = new Point3d(4, 5, 3); acUCSTblRec.XAxis = new Vector3d(1, 0, 0); acUCSTblRec.YAxis = new Vector3d(0, 1, 0); // Open the active viewport ViewportTableRecord acVportTblRec; acVportTblRec = acTrans.GetObject(acDoc.Editor.ActiveViewportId, OpenMode.ForWrite) as ViewportTableRecord; // Display the UCS Icon at the origin of the current viewport acVportTblRec.IconAtOrigin = true; acVportTblRec.IconEnabled = true; // Set the UCS current acVportTblRec.SetUcs(acUCSTblRec.ObjectId); acDoc.Editor.UpdateTiledViewportsFromDatabase(); // Display the name of the current UCS UcsTableRecord acUCSTblRecActive; acUCSTblRecActive = acTrans.GetObject(acVportTblRec.UcsName, OpenMode.ForRead) as UcsTableRecord; Application.ShowAlertDialog("The current UCS is: " + acUCSTblRecActive.Name); PromptPointResult pPtRes; PromptPointOptions pPtOpts = new PromptPointOptions(""); // Prompt for a point pPtOpts.Message = "\nEnter a point: "; pPtRes = acDoc.Editor.GetPoint(pPtOpts); Point3d pPt3dWCS; Point3d pPt3dUCS; // If a point was entered, then translate it to the current UCS if (pPtRes.Status == PromptStatus.OK) { pPt3dWCS = pPtRes.Value; pPt3dUCS = pPtRes.Value; // Translate the point from the current UCS to the WCS Matrix3d newMatrix = new Matrix3d(); newMatrix = Matrix3d.AlignCoordinateSystem(Point3d.Origin, Vector3d.XAxis, Vector3d.YAxis, Vector3d.ZAxis, acVportTblRec.Ucs.Origin, acVportTblRec.Ucs.Xaxis, acVportTblRec.Ucs.Yaxis, acVportTblRec.Ucs.Zaxis); pPt3dWCS = pPt3dWCS.TransformBy(newMatrix); Application.ShowAlertDialog("The WCS coordinates are: \n" + pPt3dWCS.ToString() + "\n" + "The UCS coordinates are: \n" + pPt3dUCS.ToString()); } // Save the new objects to the database acTrans.Commit(); } }
public static void ShowMsg(string s, params object[] args) { s = string.Format(s, args); AcApp.ShowAlertDialog(s); }
/// <summary> /// Сообщение во всплывающий модальный диалог /// </summary> /// <param name="Message">Данные</param> public static void Alert(object Message) { App.ShowAlertDialog(Message.ToString()); }
internal void M1Q() { _GLOBAL.ClsGlobal clsGlobal = new _GLOBAL.ClsGlobal(); Document acDoc = AcadApp.DocumentManager.MdiActiveDocument; Database acDb = acDoc.Database; Editor acEd = acDoc.Editor; if (acDoc.Name != "Drawing1.dwg") { using (Transaction acTrans = acDb.TransactionManager.StartTransaction()) { using (DocumentLock acLock = acDoc.LockDocument()) { BlockTable acBlkTbl = acTrans.GetObject(acDb.BlockTableId, Autodesk.AutoCAD.DatabaseServices.OpenMode.ForRead) as BlockTable; BlockTableRecord acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], Autodesk.AutoCAD.DatabaseServices.OpenMode.ForWrite) as BlockTableRecord; LayerTable acLyrTbl = acTrans.GetObject(acDb.LayerTableId, Autodesk.AutoCAD.DatabaseServices.OpenMode.ForRead) as LayerTable; Point3d Max = acDb.Extmax; Point3d Min = acDb.Extmin; if (Min.X < 0 || Min.Y < 0) { double Width = Max.X - Min.X; double Height = Max.Y - Min.Y; double OldCenterX = (Max.X + Min.X) / 2; double OldCenterY = (Max.Y + Min.Y) / 2; Point2d OldCenterXY = new Point2d(OldCenterX, OldCenterY); string strOldCenterXY = OldCenterX + "," + OldCenterY; double CenterX = Width / 2; double CenterY = Height / 2; Point2d NewCenterXY = new Point2d(CenterX, CenterY); string strNewCenterXY = CenterX + "," + CenterY; if (OldCenterXY != NewCenterXY) { foreach (ObjectId ObjId in acLyrTbl) { LayerTableRecord acLyrTblRec = acTrans.GetObject(ObjId, Autodesk.AutoCAD.DatabaseServices.OpenMode.ForWrite) as LayerTableRecord; if (acLyrTblRec.IsLocked == true) { acLyrTblRec.IsLocked = false; _GLOBAL.ClsGlobal.LockedLayers.Add(acLyrTblRec.Name); } if (acLyrTblRec.IsFrozen == true) { acLyrTblRec.IsFrozen = false; _GLOBAL.ClsGlobal.FrozenLayer.Add(acLyrTblRec.Name); } } acDoc.SendStringToExecute("._move _all " + strOldCenterXY + " " + strNewCenterXY + " ", true, false, false); acDoc.SendStringToExecute("._Zoom _all ", true, false, false); } else if (OldCenterXY == NewCenterXY) { acEd.WriteMessage("\nDrwaing is in first quadrant"); //_GLOBAL.clsGlobal._ucMain.panel2.Enabled = true; //SetDefaultValues(); } } else { acEd.WriteMessage("\nDrwaing is in first quadrant"); //_GLOBAL.clsGlobal._ucMain.panel2.Enabled = true; //SetDefaultValues(); } } //_GLOBAL.clsGlobal._ucMain.M1Q.Enabled = false; acEd.WriteMessage("\nDrawing moved to first quadrant"); acTrans.Commit(); } } else { AcadApp.ShowAlertDialog("No drawing found"); } }
public static void SaveFileAsTest() { string output = SelectFolder("File name to save as:"); AcAp.ShowAlertDialog($"Filename to save as is: {output}"); }
public static void ShowErr(System.Exception ex) { AppServices.Log.Add(ex); AcApp.ShowAlertDialog(ex.GetExtendedMessage(null, null, false)); }
private void buttonTendonSel_Click(object sender, EventArgs e) { buttonTendonSel.Text = "添加钢束"; this.Visible = false; //启动CAD相关对象 Document doc = AcadApp.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; bool isTdInTbl = false;//初始化判断所选钢束是否已在表中的布尔值 //1.1管道偏差系数 if (!double.TryParse(textBoxKii.Text, out kii)) { MessageBox.Show("管道偏差系数输入有误!"); this.Visible = true; return; } //1.2摩阻系数 if (!double.TryParse(textBoxMiu.Text, out miu)) { MessageBox.Show("摩阻系数输入有误!"); this.Visible = true; return; } //1.3钢束弹模 double Ep = 1.95e5; if (!double.TryParse(textBoxEp.Text, out Ep)) { MessageBox.Show("钢束弹模输入有误!"); this.Visible = true; return; } //1.4张拉控制应力 if (!double.TryParse(textBoxCtrlStress.Text, out ctrlStress)) { MessageBox.Show("张拉控制应力输入有误!"); this.Visible = true; return; } //1.5工作长度 if (!double.TryParse(textBoxWorkLen.Text, out workLen)) { MessageBox.Show("工作长度输入有误!"); this.Visible = true; return; } using (Transaction trans = db.TransactionManager.StartTransaction())//开始事务处理 { #region 1.选择钢束 List <Polyline> tds = new List <Polyline>(); //初始化存储钢束的List for (;;) //无限循环 { tds = new List <Polyline>(); //清空tds PromptSelectionOptions tdsOpt = new PromptSelectionOptions(); tdsOpt.MessageForAdding = "\n选择钢束线,需为无折角的多段线"; PromptSelectionResult tdsRes = ed.GetSelection(tdsOpt); if (tdsRes.Status == PromptStatus.Cancel) { this.Visible = true;//重新显示对话框 return; } bool isPolyline = true;//设置是否选择集中均为多段线的布尔参数 if (tdsRes.Status == PromptStatus.OK) { SelectionSet sSet = tdsRes.Value; foreach (ObjectId tdId in sSet.GetObjectIds()) { Polyline td = tdId.GetObject(OpenMode.ForRead) as Polyline; //获取钢束线 if (td == null) //选择集中有非多段线 { AcadApp.ShowAlertDialog("选择集中含有非多段线,重新选择"); isPolyline = false; break;//退出循环 } tds.Add(td); } if (isPolyline == false) { continue; //如果存在非多段线,则重新提示选择 } break; //结束选择 } } #endregion #region 2.扩展字典的读取或添加,并将信息列入表格 for (int i = 0; i < tds.Count; i++) { if (idsInTbl.Contains(tds[i].ObjectId)) { isTdInTbl = true; break; //钢束已在表中,不继续添加,退出循环 } idsInTbl.Add(tds[i].ObjectId); //将新的钢束加入列表中便于后续判断 int index = (int)(XrecordManipulate.ReadXRecordToRow(this, tds[i], kii, miu, Ep, ctrlStress, workLen)); string tdKey = "TendonHdl_" + tds[i].Handle.ToString(); //钢束键值 dataGridViewTendons.Rows[index].Cells[10].Value = tdKey; //键值加入最后一列 tdIdsInTable.Add(tdKey, tds[i].ObjectId); //加入表中钢束字典列表便于后续操作 } #endregion trans.Commit(); //执行事务处理 } this.Visible = true; //重新显示对话框 if (isTdInTbl) { MessageBox.Show("\n选择集中有表中已有钢束,已自动剔除!"); } }
/// <summary> /// Init JPP command loads all essential elements of the program, including the helper DLL files. /// </summary> public static void InitJPP() { Logger.Log("Loading JPP Core...\n"); //Create the main UI RibbonTab JPPTab = CreateTab(); CreateCoreMenu(JPPTab); //Load the additional DLL files, but only not if running in debug mode #if !DEBUG Update(); #endif LoadModules(); //Create settings window //TODO: move common window creation code to utilities method _settingsWindow = new PaletteSet("JPP", new Guid("9dc86012-b4b2-49dd-81e2-ba3f84fdf7e3")); _settingsWindow.Size = new Size(600, 800); _settingsWindow.Style = (PaletteSetStyles)((int)PaletteSetStyles.ShowAutoHideButton + (int)PaletteSetStyles.ShowCloseButton); _settingsWindow.DockEnabled = (DockSides)((int)DockSides.Left + (int)DockSides.Right); ElementHost settingsWindowHost = new ElementHost(); settingsWindowHost.AutoSize = true; settingsWindowHost.Dock = DockStyle.Fill; settingsWindowHost.Child = new SettingsUserControl(); _settingsWindow.Add("Settings", settingsWindowHost); _settingsWindow.KeepFocus = false; //Load click handler; ClickOverride = ClickOverride.Current; //Check for registry key for autoload if (!RegistryHelper.IsAutoload()) { //No autoload found //TODO: try to condense this into a helper method TaskDialog autoloadPrompt = new TaskDialog(); autoloadPrompt.WindowTitle = Constants.Friendly_Name; autoloadPrompt.MainInstruction = "JPP Library does not currently load automatically. Would you like to enable this?"; autoloadPrompt.MainIcon = TaskDialogIcon.Information; autoloadPrompt.FooterText = "May cause unexpected behaviour on an unsupported version of Autocad"; autoloadPrompt.FooterIcon = TaskDialogIcon.Warning; autoloadPrompt.Buttons.Add(new TaskDialogButton(0, "No, continue without")); autoloadPrompt.Buttons.Add(new TaskDialogButton(1, "Enable autoload")); autoloadPrompt.DefaultButton = 0; autoloadPrompt.Callback = delegate(ActiveTaskDialog atd, TaskDialogCallbackArgs e, object sender) { if (e.Notification == TaskDialogNotification.ButtonClicked) { if (e.ButtonId == 1) { //TODO: Disable when registry is ok //RegistryHelper.CreateAutoload(); Application.ShowAlertDialog("Autload creation currently disabled."); } } return(false); }; autoloadPrompt.Show(Application.MainWindow.Handle); } Logger.Log("JPP Core loaded.\n"); }
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)); } }
checkIfCurrent(string nameFile) { bool isCurrent = false; int compare = 0; bool exists = false; ObjectId idDict = Dict.getNamedDictionary("XRefNames", out exists); ResultBuffer rb = Dict.getXRec(idDict, "XRefNames"); TypedValue[] tvs = rb.AsArray(); DateTime lastWrite = new DateTime(); if (File.Exists(nameFile)) { FileInfo fi = new FileInfo(nameFile); lastWrite = fi.LastWriteTime; string strLastWrite = lastWrite.ToString(); lastWrite = System.Convert.ToDateTime(strLastWrite); } for (int i = 0; i < tvs.Length; i++) { if (tvs[i].Value.ToString() == nameFile) { DateTime savedWrite = System.Convert.ToDateTime(tvs[i + 1].Value.ToString()); compare = lastWrite.CompareTo(savedWrite); if (compare == 0) { isCurrent = true; } if (compare > 0) { isCurrent = false; } break; } } if (!isCurrent) { DimPL_Global.countUpdates = 0; Document workDoc = Application.DocumentManager.MdiActiveDocument; string nameUser = ""; int dwgStatus = Base_Tools45.FileManager.getFileStatus(nameFile, out nameUser); switch (dwgStatus) { case (int)filestatus.isOpenLocal: Document doc = FileManager.getDoc(nameFile, true, false); Application.DocumentManager.MdiActiveDocument = doc; Object dbMod = Application.GetSystemVariable("DBMOD"); if (System.Convert.ToInt16(dbMod) != 0) { doc.Database.SaveAs(doc.Name, true, DwgVersion.Current, doc.Database.SecurityParameters); } Application.DocumentManager.MdiActiveDocument = workDoc; updateDimPL(nameFile); break; case (int)filestatus.isOpenLocalReadOnly: updateDimPL(nameFile); break; case (int)filestatus.isLocked: updateDimPL(nameFile); break; case (int)filestatus.isAvailable: updateDimPL(nameFile); break; } if (DimPL_Global.countUpdates > 0) { Application.ShowAlertDialog(string.Format("{0} DimPL updates were performed.", DimPL_Global.countUpdates)); } } }