/// <summary>ObjectId блока для стрелки</summary> /// <param name="newArrName">Имя блока для стрелки</param> /// <returns>ObjectId нового блока стрелки</returns> public static ObjectId GetArrowObjectId(string newArrName) { ObjectId arrObjId; var doc = AcApp.DocumentManager.MdiActiveDocument; var db = doc.Database; // Получаем текущее значение переменной DIMBLK var oldArrName = AcApp.GetSystemVariable("DIMBLK") as string; // Устанавливаем новое значение DIMBLK // (если такой блок отсутствует в чертеже, то он будет создан) AcApp.SetSystemVariable("DIMBLK", newArrName); // Возвращаем предыдущее значение переменной DIMBLK if (!string.IsNullOrEmpty(oldArrName)) { AcApp.SetSystemVariable("DIMBLK", oldArrName); } // Теперь получаем objectId блока var tr = db.TransactionManager.StartTransaction(); using (tr) { var bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead); arrObjId = bt[newArrName]; tr.Commit(); } return(arrObjId); }
private void AutoCadMessageHandler(object sender, PreTranslateMessageEventArgs e) { if (e.Message.message == (int)WndMsg.WM_KEYDOWN) { if ((int)e.Message.wParam == (int)WndKey.VK_F1) { // F1 pressed if (_currentTooltip != null && _currentTooltip.Length > 8 && _currentTooltip.StartsWith("https://modplus.org/")) { // Another implementation could be to look up the help topic in an index file matching it to URLs. _dropNextHelpCall = true; // Even though we don't forward this F1 keypress, AutoCAD sends a message to itself to open the AutoCAD help file object nomutt = AcApp.GetSystemVariable("NOMUTT"); string cmd = $"._BROWSER {_currentTooltip} _NOMUTT {nomutt} "; AcApp.SetSystemVariable("NOMUTT", 1); AcApp.DocumentManager.MdiActiveDocument.SendStringToExecute(cmd, true, false, false); e.Handled = true; } } } else if (e.Message.message == (int)WndMsg.WM_ACAD_HELP && _dropNextHelpCall) { // Seems this is the message AutoCAD generates itself to open the help file. Drop this if help was called from a ribbon tooltip. _dropNextHelpCall = false; // Reset state of help calls e.Handled = true; // Stop this message from being passed on to AutoCAD } }
public void ReplaceBlockWithFileStart() { Application.SetSystemVariable("FILEDIA", 1); var editorUtility = new EditorHelper(Application.DocumentManager.MdiActiveDocument); PromptEntityResult blockToReplaceResult = editorUtility.PromptForObject("Select the block to replace : ", typeof(BlockReference), false); if (blockToReplaceResult.Status != PromptStatus.OK) { return; } var openFileDialog = new System.Windows.Forms.OpenFileDialog(); if (openFileDialog.ShowDialog() != DialogResult.OK) { return; } if (!File.Exists(openFileDialog.FileName)) { _ed.WriteMessage("File does not exists."); return; } if (!openFileDialog.FileName.EndsWith(".dwg", StringComparison.InvariantCultureIgnoreCase)) { _ed.WriteMessage("File is not a DWG."); return; } Point3d selectedEntityPoint; using (Transaction transaction = _db.TransactionManager.StartTransaction()) { BlockTable blockTable = (BlockTable)transaction.GetObject(_db.BlockTableId, OpenMode.ForWrite); Entity selectedEntity = (Entity)transaction.GetObject(blockToReplaceResult.ObjectId, OpenMode.ForWrite); selectedEntityPoint = ((BlockReference)selectedEntity).Position; selectedEntity.Erase(); blockTable.DowngradeOpen(); blockTable.Dispose(); transaction.Commit(); } ReplaceBlockRefWithDWG(_doc, openFileDialog.FileName, selectedEntityPoint, _ed.CurrentUserCoordinateSystem); _logger.Info(MethodBase.GetCurrentMethod().Name); }
public static int Command(params object[] args) { if (AcadApp.DocumentManager.IsApplicationContext) { return(0); } int stat = 0; int cnt = 0; bool supressOSnap = ShouldSupressRunningOSnap(); bool transform = ShouldTransformCoords(); using (ResultBuffer buffer = new ResultBuffer()) { foreach (object o in args) { if (supressOSnap && (o is Point3d || o is Point2d)) { buffer.Add(new TypedValue(RTSTR, "_non")); } if (transform && (o is Point3d)) { buffer.Add(new TypedValue(RT3DPOINT, WorldToCurrent((Point3d)o))); } else { buffer.Add(TypedValueFromObject(o)); } ++cnt; } if (cnt > 0) { string s = (string)AcadApp.GetSystemVariable("USERS1"); bool debug = string.Compare(s, "DEBUG", true) == 0; int val = debug ? 1 : 0; object cmdecho = AcadApp.GetSystemVariable("CMDECHO"); Int16 c = (Int16)cmdecho; if (c != 0 || debug) { AcadApp.SetSystemVariable("CMDECHO", val); } stat = acedCmd(buffer.UnmanagedObject); if (c != 0 || debug) { AcadApp.SetSystemVariable("CMDECHO", cmdecho); } } } return(stat); }
public void RecoverTest() { Document doc = Application.DocumentManager.MdiActiveDocument; DocumentCollection docs = Application.DocumentManager; Editor ed = doc.Editor; #if !acad2013 ed.WriteMessage("Not supported in ACAD versions lower than 2015."); return; #else var oldValue = Application.GetSystemVariable("PROXYNOTICE"); Application.SetSystemVariable("PROXYNOTICE", 0); var errorsFile = @"errors.csv"; var content = File.ReadAllLines(errorsFile).Select(x => x.Split(new[] { " -> " }, StringSplitOptions.RemoveEmptyEntries)); var forRepair = content.Where(x => x[1].Equals("eDwgNeedsRecovery")).Select(x => x[0]); using (var errorLogger = new StreamWriter("Errors_Recovery.csv", true) { AutoFlush = true }) { foreach (var file in forRepair) { //var path = $@"\\?\{file}"; try { var path = Path.Combine(@"D:\DwgWork", file.Substring(49)); //path = $@"\\?\{path}"; docs.AppContextRecoverDocument(path); Application.DocumentManager.MdiActiveDocument.CloseAndSave(path); } catch (System.Exception e) { errorLogger.WriteLine($"{file} -> {e.Message}"); } } } Application.SetSystemVariable("PROXYNOTICE", oldValue); #endif }
private static void IncludeFolderLocation(string folderLocation) { try { Application.GetSystemVariable("_TOOLPALETTEPATH"); string text = (string)Application.GetSystemVariable("_TOOLPALETTEPATH"); string[] array = text.Split(new char[] { ';' }); bool flag = false; string[] array2 = array; for (int i = 0; i < array2.Length; i++) { string path = array2[i]; if (string.Compare(Path.GetFullPath(path).TrimEnd(new char[] { '\\' }), Path.GetFullPath(folderLocation).TrimEnd(new char[] { '\\' }), StringComparison.InvariantCultureIgnoreCase) == 0) { flag = true; break; } } if (!flag) { text += string.Format(";{0}", folderLocation); Application.SetSystemVariable("_TOOLPALETTEPATH", text); Application.GetSystemVariable("TPSTATE"); } } catch { } }
/// <summary> /// Method to find the object under the mleader arrow /// </summary> /// <param name="mLeader"></param> /// <returns></returns> private static ObjectId GetObjectUnderArrow(this MLeader mLeader) { var leaderInd = mLeader.GetLeaderIndexes(); var objId = ObjectId.Null; var acCurDoc = Application.DocumentManager.MdiActiveDocument; var acCurDb = acCurDoc.Database; var acCurEd = acCurDoc.Editor; try { if (leaderInd.Count != 0) { var leaderLineInd = mLeader.GetLeaderLineIndexes((int)leaderInd[0]); var arrowPt = mLeader.GetFirstVertex((int)leaderLineInd[0]); SelectionSet ss = null; if (LayoutManager.Current.CurrentLayout == "Model") { arrowPt = arrowPt.Trans(acCurEd, CoordSystem.Wcs, CoordSystem.Ucs); var p = arrowPt; var tol = 0.01; var p1 = new Point3d(p.X - tol, p.Y - tol, p.Z - tol); var p2 = new Point3d(p.X + tol, p.Y + tol, p.Z + tol); var res = acCurEd.SelectCrossingWindow(p1, p2); ss = res.Value; } else { var layoutName = LayoutManager.Current.CurrentLayout; using (var acTrans = acCurDb.TransactionManager.StartTransaction()) { var dbDict = (DBDictionary)acTrans.GetObject(acCurDb.LayoutDictionaryId, OpenMode.ForRead); if (dbDict.Contains(layoutName)) { var id = dbDict.GetAt(layoutName); var curLayout = acTrans.GetObject(id, OpenMode.ForRead) as Layout; if (curLayout != null) { var vPorts = new List <Viewport>(); //Get viewports from chosen layout using ( var blkTblRec = acTrans.GetObject(curLayout.BlockTableRecordId, OpenMode.ForRead) as BlockTableRecord) { if (blkTblRec != null) { foreach (var lObjId in blkTblRec) { if (lObjId == acCurDb.PaperSpaceVportId) { continue; } var acVp = acTrans.GetObject(lObjId, OpenMode.ForWrite) as Viewport; if (acVp != null && !acVp.IsErased) { vPorts.Add(acVp); } } } } if (vPorts.Count > 0) { var insideVp = false; var vpLocation = 0; for (var index = 0; index < vPorts.Count; index++) { var acVp = vPorts[index]; if (arrowPt.IsInside(acVp.GeometricExtents)) { insideVp = true; vpLocation = index; break; } } if (insideVp) { var psVpPnts = new Point3dCollection(); // now extract the viewport geometry vPorts[vpLocation].GetGripPoints(psVpPnts, new IntegerCollection(), new IntegerCollection()); // let's assume a rectangular vport for now, make the cross-direction grips square var tmp = psVpPnts[2]; psVpPnts[2] = psVpPnts[1]; psVpPnts[1] = tmp; var xform = vPorts[vpLocation].Dcs2Wcs() * vPorts[vpLocation].Psdcs2Dcs(); arrowPt = arrowPt.TransformBy(xform); // now switch to MS acCurEd.SwitchToModelSpace(); // set the CVPort Application.SetSystemVariable("CVPORT", vPorts[vpLocation].Number); var p = arrowPt; var tol = 0.01; var p1 = new Point3d(p.X - tol, p.Y - tol, p.Z - tol); var p2 = new Point3d(p.X + tol, p.Y + tol, p.Z + tol); var res = acCurEd.SelectCrossingWindow(p1, p2); if (res.Status != PromptStatus.OK) { acCurEd.WriteMessage(res.Status.ToString()); } ss = res.Value; // now switch to MS acCurEd.SwitchToPaperSpace(); } } } } else { acTrans.Abort(); } acTrans.Commit(); } } if (ss == null) { return(objId); } var objIds = new ObjectIdCollection(); foreach (SelectedObject obj in ss) { if (obj.ObjectId != _curLeaderId) { objIds.Add(obj.ObjectId); } } if (objIds.Count > 0) { objId = objIds[objIds.Count - 1]; } } } catch (Exception) { //Ignored } return(objId); }
//[CommandMethod("gi")] public static void GetIntersections() { var db = HostApplicationServices.WorkingDatabase; var doc = Application.DocumentManager.MdiActiveDocument; var ed = doc.Editor; using (var docLock = doc.LockDocument()) { using (var tr = db.TransactionManager.StartTransaction()) { try { var btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite); var peo = new PromptEntityOptions("\nSelect a single polyline >>"); peo.SetRejectMessage("\nSelected object might be of type polyline only >>"); peo.AddAllowedClass(typeof(Polyline), false); PromptEntityResult res; res = ed.GetEntity(peo); if (res.Status != PromptStatus.OK) { return; } var ent = tr.GetObject(res.ObjectId, OpenMode.ForRead); if (ent == null) { return; } //Polyline poly = (Polyline)ent as Polyline; var curv = ent as Curve; var pcurves = new DBObjectCollection(); curv.Explode(pcurves); TypedValue[] values = { new TypedValue(0, "lwpolyline") //might be added layer name to select curve: //, new TypedValue(8, "mylayer") }; var filter = new SelectionFilter(values); var fence = new Point3dCollection(); var leng = curv.GetDistanceAtParameter(curv.EndParam) - curv.GetDistanceAtParameter(curv.StartParam); // number of divisions along polyline to create fence selection var step = leng / 256; // set number of steps to your suit var num = Convert.ToInt32(leng / step); var i = 0; for (i = 0; i < num; i++) { var pp = curv.GetPointAtDist(step * i); fence.Add(curv.GetClosestPointTo(pp, false)); } var selres = ed.SelectFence(fence, filter); if (selres.Status != PromptStatus.OK) { return; } var intpts = new Point3dCollection(); var qcurves = new DBObjectCollection(); foreach (SelectedObject selobj in selres.Value) { var obj = tr.GetObject(selobj.ObjectId, OpenMode.ForRead, false); if (selobj.ObjectId != curv.ObjectId) { var icurves = new DBObjectCollection(); var icurv = obj as Curve; icurv.Explode(icurves); foreach (DBObject dbo in icurves) { if (!qcurves.Contains(dbo)) { qcurves.Add(dbo); } } } } ed.WriteMessage("\n{0}", qcurves.Count); var j = 0; var polypts = new Point3dCollection(); for (i = 0; i < pcurves.Count; ++i) { for (j = 0; j < qcurves.Count; ++j) { var curve1 = pcurves[i] as Curve; var curve2 = qcurves[j] as Curve; var pts = new Point3dCollection(); curve1.IntersectWith(curve2, Intersect.OnBothOperands, pts, IntPtr.Zero, IntPtr.Zero); foreach (Point3d pt in pts) { if (!polypts.Contains(pt)) { polypts.Add(pt); } } } } Application.SetSystemVariable("osmode", 0); // optional // for debug only Application.ShowAlertDialog(string.Format("\nNumber of Intersections: {0}", polypts.Count)); // test for visulization only foreach (Point3d inspt in polypts) { var circ = new Circle(inspt, Vector3d.ZAxis, 10 * db.Dimtxt); circ.ColorIndex = 1; btr.AppendEntity(circ); tr.AddNewlyCreatedDBObject(circ, true); } tr.Commit(); } catch (Exception ex) { ed.WriteMessage("\n{0}\n{1}", ex.Message, ex.StackTrace); } } } }
// [CommandMethod("wblockclone", CommandFlags.Session)] //static public void wblockclone() //{ // Document doc = Application.DocumentManager.MdiActiveDocument; // Database db = doc.Database; // Editor ed = doc.Editor; // //PromptEntityOptions peo = new PromptEntityOptions("\nSelect entity to copy: "); // //PromptEntityResult per = ed.GetEntity(peo); // //if (per.Status != PromptStatus.OK) // // return; // Application. // using (DocumentLock doclock = doc.LockDocument()) // { // ObjectIdCollection ObjectcIds = new ObjectIdCollection(); // ObjectcIds.Add(per.ObjectId); // Database destDb = new Database(false, true); // destDb.ReadDwgFile(@"C:\Users\Daryl Banks\Downloads\doraltest\2014Doral\Doral-Closed-Polygons\Doral06.DWG", System.IO.FileShare.Read, true, ""); // using (Transaction Tx = destDb.TransactionManager.StartTransaction()) // { // BlockTable bt = Tx.GetObject( // destDb.BlockTableId, // OpenMode.ForRead) as BlockTable; // BlockTableRecord btr = Tx.GetObject( // bt[BlockTableRecord.ModelSpace], // OpenMode.ForWrite) as BlockTableRecord; // IdMapping oIdMap = new IdMapping(); // destDb.WblockCloneObjects( // ObjectcIds, // btr.ObjectId, // oIdMap, // DuplicateRecordCloning.Ignore, // false); // Tx.Commit(); // } // destDb.SaveAs(destDb.Filename, DwgVersion.Current); // } //} public static void GetComplexity() { var db = HostApplicationServices.WorkingDatabase; var doc = Application.DocumentManager.MdiActiveDocument; var ed = doc.Editor; using (doc.LockDocument()) { using (var tr = db.TransactionManager.StartTransaction()) { try { var btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite); var peo = new PromptEntityOptions("\nSelect a single polyline >>"); peo.SetRejectMessage("\nSelected object might be of type polyline only >>"); peo.AddAllowedClass(typeof(Polyline), false); PromptEntityResult res; res = ed.GetEntity(peo); if (res.Status != PromptStatus.OK) { return; } var ent = tr.GetObject(res.ObjectId, OpenMode.ForRead); if (ent == null) { return; } //Polyline poly = (Polyline)ent as Polyline; var curv = ent as Curve; var pcurves = new DBObjectCollection(); if (curv != null) { curv.Explode(pcurves); TypedValue[] values = { new TypedValue(0, "lwpolyline") //might be added layer name to select curve: //, new TypedValue(8, "mylayer") }; var filter = new SelectionFilter(values); var fence = new Point3dCollection(); var leng = curv.GetDistanceAtParameter(curv.EndParam) - curv.GetDistanceAtParameter(curv.StartParam); // number of divisions along polyline to create fence selection //double step = leng / 256;// set number of steps to your suit var step = leng / pcurves.Count; Application.SetSystemVariable("osmode", 0); // optional // for debug only Application.ShowAlertDialog(string.Format("\nNumber of Steps: {0}", step)); } tr.Commit(); } catch (Exception ex) { ed.WriteMessage("\n{0}\n{1}", ex.Message, ex.StackTrace); } } } }
// based on article by Wayne Brill // http://adndevblog.typepad.com/autocad/2012/06/use-getclosestpointto-and-onsegat-to-locate-a-polyline-vertex-near-a-point.html //[CommandMethod("oseg")] public static void TEST_PointOnPoly() { var db = Application.DocumentManager.MdiActiveDocument.Database; var ed = Application.DocumentManager.MdiActiveDocument.Editor; var cs = ed.CurrentUserCoordinateSystem.CoordinateSystem3d; var plan = new Plane(Point3d.Origin, cs.Zaxis); Application.SetSystemVariable("osmode", 512); using (var tr = db.TransactionManager.StartTransaction()) { try { Entity ename; Point3d pt; Point3d ptWcs; var peo = new PromptEntityOptions("\nSelect Pline: "); peo.SetRejectMessage("\nYou have to select LWPOLYLINE!"); peo.AddAllowedClass(typeof(Polyline), false); var res = ed.GetEntity(peo); if (res.Status != PromptStatus.OK) { return; } var id = res.ObjectId; // Convert to WCS incase selection was made // while in a UCS. pt = res.PickedPoint; // Transform from UCS to WCS var mat = Matrix3d.AlignCoordinateSystem( Point3d.Origin, Vector3d.XAxis, Vector3d.YAxis, Vector3d.ZAxis, cs.Origin, cs.Xaxis, cs.Yaxis, cs.Zaxis ); ptWcs = pt.TransformBy(mat); ename = tr.GetObject(id, OpenMode.ForRead) as Entity; var pline = ename as Polyline; if (pline == null) { ed.WriteMessage("\nSelected Entity is not a Polyline"); return; } var clickpt = pline.GetClosestPointTo(ptWcs, false); for (var c = 0; c < pline.NumberOfVertices; c++) { var segParam = new double(); // This is the test filter here...it uses the // nifty API OnSegmentAt if (pline.OnSegmentAt(c, clickpt.Convert2d(plan), segParam)) { ed.WriteMessage("\nSelected Segment: {0} \n", c + 1); break; } } } catch (Exception ex) { ed.WriteMessage("\n" + ex.Message + "\n" + ex.StackTrace); } } }
public static void SaveAsPDF(ResultBuffer rbArgs) { var editor = Acad.DocumentManager.MdiActiveDocument.Editor; editor.WriteMessage("Процесс экспорта чертежей в формат PDF начинается..."); // Получение директории и параметров поиска if (rbArgs != null) { string str = ""; bool subDirs = false; foreach (TypedValue rb in rbArgs) { if (rb.TypeCode == (int)Autodesk.AutoCAD.Runtime.LispDataType.Text) { if (rb.Value.ToString() == "true") { subDirs = true; } else if (rb.Value.ToString() == "false") { subDirs = false; } else { str += rb.Value.ToString(); } } } Acad.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Путь к чертежам: " + str); // Получение списка файлов с учетом заданного пути и параметров поиска try { str = str.Replace('/', '\\'); System.IO.DirectoryInfo rootDir = new System.IO.DirectoryInfo(str); System.IO.FileInfo[] dirs = rootDir.GetFiles("*.dwg", subDirs ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly); //Список листов найденных чертежей foreach (FileInfo dir in dirs) { editor.WriteMessage(Environment.NewLine + dir); using (Database dwgDB = new Database(false, true)) { dwgDB.ReadDwgFile(dir.FullName, System.IO.FileShare.ReadWrite, false, ""); Acad.SetSystemVariable("BACKGROUNDPLOT", 1); //Далее манипуляции с базой данных чертежа using (Transaction acTrans = dwgDB.TransactionManager.StartTransaction()) { List <Layout> layouts = new List <Layout>(); DBDictionary layoutDict = (DBDictionary)acTrans.GetObject(dwgDB.LayoutDictionaryId, OpenMode.ForRead); editor.WriteMessage("Листы чертежа " + dir + ":"); foreach (DBDictionaryEntry id in layoutDict) { if (id.Key != "Model") { Layout ltr = (Layout)acTrans.GetObject((ObjectId)id.Value, OpenMode.ForRead); layouts.Add(ltr); editor.WriteMessage(Environment.NewLine + ltr.LayoutName); } } layouts.Sort((l1, l2) => l1.TabOrder.CompareTo(l2.TabOrder)); string filename = Path.ChangeExtension(dwgDB.Filename, "pdf"); MultiSheetsPdf plotter = new MultiSheetsPdf(filename, layouts); plotter.Publish(); editor.WriteMessage(Environment.NewLine + dwgDB.Filename + " успешно экспортирован"); acTrans.Commit(); } } } } catch (Autodesk.AutoCAD.Runtime.Exception e) { editor.WriteMessage("\nError: {0}\n{1}", e.Message, e.StackTrace); } } }
Initialize_Form() { ResultBuffer rb; Document doc = Application.DocumentManager.MdiActiveDocument; using (doc.LockDocument()) { Layer.manageLayers("BRKLINE ERRORS"); Layer.manageLayers("CPNT-BRKLINE"); Layer.manageLayers("CPNT-ON"); Layer.manageLayers("CURB-TEMP"); Layer.manageLayers("FL"); Layer.manageLayers("GB"); Layer.manageLayers("GUTTER"); } Application.SetSystemVariable("PICKFIRST", 1); gintCmdStatus = 1; TARGETDWGNAME = ""; TARGETDWGPATH = ""; using (BaseObjs._acadDoc.LockDocument()) { bool exists = false; //try //{ // Dict.getNamedDictionary(lnkBrks3, out exists); //} //catch //{ //} ObjectId idDict = ObjectId.Null; try { idDict = Dict.getNamedDictionary("LASTBRKLINE", out exists); } catch (System.Exception ex) { BaseObjs.writeDebug(string.Format("{0} ucGrading.xaml.cs: line: 57", ex.Message)); } if (exists) { string sHandle = myUtility.getXrec0("LASTBRKLINE"); if (!string.IsNullOrEmpty(sHandle)) { this.HandleLastBrkLine = Db.stringToHandle(sHandle); } else { this.HandleLastBrkLine = "0000".stringToHandle(); } } else { rb = null; ObjectIdCollection ids = BaseObjs._acadDoc.getBrkLines(); Handle handle; if (ids != null && ids.Count > 0) { try { handle = mySurfaces.cleanUpBreaklines().stringToHandle(); rb = new ResultBuffer(new TypedValue((int)DxfCode.Handle, handle)); Dict.addXRec(idDict, "LASTBRKLINE", rb); this.HandleLastBrkLine = handle; Grading.Cmds.cmdCPXD.checkPntXData(); } catch (System.Exception ex) { BaseObjs.writeDebug(string.Format("{0} ucGrading.xaml.cs: line: 75", ex.Message)); } } } TypedValue[] TVs = new TypedValue[5]; TVs.SetValue(new TypedValue((int)DxfCode.Operator, "<OR"), 0); TVs.SetValue(new TypedValue((int)DxfCode.Start, "LINE"), 1); TVs.SetValue(new TypedValue((int)DxfCode.Start, "POLYLINE"), 2); TVs.SetValue(new TypedValue((int)DxfCode.Operator, "OR>"), 3); TVs.SetValue(new TypedValue((int)DxfCode.LayerName, "CPNT-BRKLINE*"), 4); SelectionSet ss = Select.buildSSet(TVs); if (ss != null) { try { using (Transaction tr = BaseObjs.startTransactionDb()) { ObjectId[] ids = ss.GetObjectIds(); foreach (ObjectId id in ids) { if (id.getType() == "Line") { id.delete(); } else if (id.getType() == "Polyline3d") { Polyline3d poly3d = (Polyline3d)tr.GetObject(id, OpenMode.ForRead); if (poly3d.Length == 0) { id.delete(); } } } tr.Commit(); } } catch (System.Exception ex) { BaseObjs.writeDebug(string.Format("{0} ucGrading.xaml.cs: line: 107", ex.Message)); } } //------------------------------------------------------------------ optFL.IsChecked = true; optPNTS.IsChecked = true; if (System.Environment.UserName.ToUpper() == "JOHN") { cmdPD.IsEnabled = true; } else { cmdPD.IsEnabled = false; } Pub.Slope = Double.Parse(cmdRL_GRADE); } }
public static void SaveAsPDF(ResultBuffer rbArgs)//Основная функция плагина (Требуется корректировка и тестирование) { var editor = Acad.DocumentManager.MdiActiveDocument.Editor; editor.WriteMessage("Процесс экспорта чертежей в формат PDF начинается..."); // Получение директории и параметров поиска if (rbArgs != null) { string str = ""; bool subDirs = false; foreach (TypedValue rb in rbArgs) { if (rb.TypeCode == (int)LispDataType.Text) { if (rb.Value.ToString() == "true") { subDirs = true; } else if (rb.Value.ToString() == "false") { subDirs = false; } else { str += rb.Value.ToString(); } } } Acad.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Путь к чертежам: " + str); // Получение списка файлов с учетом заданного пути и параметров поиска try { str = str.Replace('/', '\\'); DirectoryInfo rootDir = new DirectoryInfo(str); List <FileInfo> files = new List <FileInfo>(); short bgp = (short)Acad.GetSystemVariable("BACKGROUNDPLOT"); Acad.SetSystemVariable("BACKGROUNDPLOT", 0); GetFiles(rootDir, files, subDirs); //Список листов найденных чертежей foreach (FileInfo file in files) { editor.WriteMessage(Environment.NewLine + file); using (Database dwgDB = new Database(false, true)) { dwgDB.ReadDwgFile(file.FullName, FileShare.ReadWrite, false, ""); //Далее манипуляции с базой данных чертежа using (Transaction acTrans = dwgDB.TransactionManager.StartTransaction()) { List <Layout> layouts = new List <Layout>(); DBDictionary layoutDict = (DBDictionary)acTrans.GetObject(dwgDB.LayoutDictionaryId, OpenMode.ForRead); editor.WriteMessage("Листы чертежа " + file + ":"); foreach (DBDictionaryEntry id in layoutDict) { if (id.Key != "Model") { Layout ltr = (Layout)acTrans.GetObject((ObjectId)id.Value, OpenMode.ForRead); PlotConfig config = PlotConfigManager.SetCurrentConfig("AutoCAD PDF (High Quality Print).pc3"); PlotSettingsValidator psv = PlotSettingsValidator.Current; PlotSettings ps = new PlotSettings(ltr.ModelType); psv.SetPlotConfigurationName(ps, "AutoCAD PDF (High Quality Print).pc3", null); psv.RefreshLists(ps); layouts.Add(ltr); editor.WriteMessage(Environment.NewLine + ltr.LayoutName); editor.WriteMessage(Environment.NewLine + ltr.PlotPaperSize.ToString()); editor.WriteMessage(Environment.NewLine + ltr.PlotSettingsName); } } layouts.Sort((l1, l2) => l1.TabOrder.CompareTo(l2.TabOrder)); string filename = Path.ChangeExtension(dwgDB.Filename, "pdf"); MultiSheetsPdf plotter = new MultiSheetsPdf(filename, layouts); plotter.Publish(); editor.WriteMessage(Environment.NewLine + dwgDB.Filename + " успешно экспортирован"); acTrans.Commit(); } } } Acad.SetSystemVariable("BACKGROUNDPLOT", bgp); } catch (Autodesk.AutoCAD.Runtime.Exception e) { editor.WriteMessage("\nError: {0}\n{1}", e.Message, e.StackTrace); } } else { } }
XO() { object objOffset = Application.GetSystemVariable("OFFSETDIST"); Point3d pnt3dBeg = Pub.pnt3dO; Point3d pnt3dEnd = Pub.pnt3dO; Point3d pnt3dCen, pnt3dX; string defPrompt; if (objOffset.ToString() == "-1") { defPrompt = "Through"; } else { defPrompt = objOffset.ToString(); } double disX = 0.0, offset = 0.0, radius = 0.0; bool through = false; string result, prompt = "\nSpecify Offset distance or [Through]: "; UserInput.getUserInput(defPrompt, prompt, out result, false); if (result == string.Empty) { return; } Point3d pnt3dPick = Pub.pnt3dO; string nameLayer = string.Empty; ObjectId idBlkRef = ObjectId.Null; ObjectId idEnt = xRef.getEntity("\nSelect object to offset or <exit>: ", true, out nameLayer, out pnt3dPick, out idBlkRef); if (idEnt == ObjectId.Null) { return; } PromptStatus ps = PromptStatus.Cancel; if (result.ToUpper() == "THROUGH" || result.ToUpper() == "T") { through = true; pnt3dX = UserInput.getPoint("\nSpecify Offset point : ", out ps, osMode: 0); } else { offset = double.Parse(result); Application.SetSystemVariable("OFFSETDIST", offset); if (offset == 0) { idEnt.copy("0"); return; } else { pnt3dX = UserInput.getPoint("\nSpecify point on side to offset: ", out ps, osMode: 0); } } bool rh = true; string typeEnt = idEnt.getType(); switch (typeEnt) { case "Polyline": double bulge = 0.0; try { using (Transaction tr = BaseObjs.startTransactionDb()) { Polyline poly = (Polyline)tr.GetObject(idEnt, OpenMode.ForRead); if (poly.Closed) { idEnt.checkIfClosed(); } int vtx = Geom.getVertexNo(idEnt, pnt3dX); pnt3dBeg = poly.GetPoint3dAt(vtx); pnt3dEnd = poly.GetPoint3dAt(vtx + 1); bulge = poly.GetBulgeAt(vtx); tr.Commit(); } } catch (System.Exception ex) { BaseObjs.writeDebug(ex.Message + " cmdXO.cs: line: 86"); } if (bulge == 0.0) { processLine(pnt3dBeg, pnt3dEnd, pnt3dX, through, disX, ref offset); } else { if (bulge < 0) { rh = false; } pnt3dCen = Geom.getCenter(pnt3dBeg, pnt3dEnd, bulge); if (!processArc(pnt3dBeg, pnt3dEnd, pnt3dCen, pnt3dX, through, radius, rh, idEnt, disX, ref offset)) { return; } } break; case "Line": Line line = (Line)idEnt.getEnt(); pnt3dBeg = line.StartPoint; pnt3dEnd = line.EndPoint; processLine(pnt3dBeg, pnt3dEnd, pnt3dX, through, disX, ref offset); break; case "Arc": Arc arc = (Arc)idEnt.getEnt(); pnt3dBeg = arc.StartPoint; pnt3dEnd = arc.EndPoint; pnt3dCen = arc.Center; radius = arc.Radius; Vector3d v3d = arc.Normal; if (v3d.Z < 0) { rh = false; } if (!processArc(pnt3dBeg, pnt3dEnd, pnt3dCen, pnt3dX, through, radius, rh, idEnt, disX, ref offset)) { return; } break; } idEnt.offset(offset); idEnt.delete(); }
private static void BatchLayout(Document doc, NodeLayout nodeLayout) { Application.SetSystemVariable("CLAYOUT", nodeLayout.Name); Command(doc, batchVm.Options.FileExecute); }