Example #1
0
        //--------------------------------------------------------------------------
        //
        // ���ܣ�����ע��
        //
        //  ���ߣ�
        //
        //  ���ڣ�200708
        //
        //   ��ʷ��
        //--------------------------------------------------------------------------
        private void btnInsertAnnotation_Click(System.Object sender, System.EventArgs e)
        {
            try
            {
                int curSel = listbTemplates.SelectedIndex;
                if (LB_ERR == curSel)
                {
                    MessageBox.Show("����ѡ��ע��ģ��");
                    return;
                }

                m_selectedTemplateName = listbTemplates.SelectedItem.ToString();
                m_idTemplate = m_annotations[m_selectedTemplateName].BlockDefinitionId;
                m_templateName = m_selectedTemplateName;

                using (Transaction trans = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.TransactionManager.StartTransaction())
                {
                    BlockTableRecord blkTblRcd = (BlockTableRecord)trans.GetObject(m_idTemplate, Autodesk.AutoCAD.DatabaseServices.OpenMode.ForRead);

                    //
                    string templateName = null;
                    if (!m_annotations.IsAnnotationTemplate(ref templateName, blkTblRcd))
                    {
                        MessageBox.Show("���ע��ģ��ʧ��");
                        return;
                    }

                    // ���ñ���ַ�
                    try
                    {
                        m_annotations.SetExpressionString(blkTblRcd,      //��ע�����ݽ�����ת
                            AnnotationExpressionFields.BlockRotation,
                            ".ANGLE");
                        trans.Commit();
                    }
                    catch (Autodesk.AutoCAD.Runtime.Exception err)
                    {
                        MessageBox.Show(string.Format("��ע�����ݽ�����תʧ��\n{0}", err.Message));
                    }
                } // end of using transaction

                // ѡ��ʵ�壬����ע��
                try
                {
                    m_selSetResult = Utility.AcadEditor.GetSelection();
                    if ((m_selSetResult.Status == PromptStatus.OK) && (m_selSetResult.Value.Count > 0))
                    {
                        foreach (Autodesk.AutoCAD.EditorInput.SelectedObject selectedObject in m_selSetResult.Value)
                        {
                            m_annotations[m_selectedTemplateName].InsertReference(selectedObject.ObjectId);������������������//sunj-���ע�ǵIJ���
                        }
                        Regen();
                        //
                        DialogResult = DialogResult.OK;
                    }
                    else
                    {
                        MessageBox.Show("û��ѡ��ʵ�壬����ȡ��.");
                    }
                }
                catch (Autodesk.AutoCAD.Runtime.Exception err)
                {
                    MessageBox.Show(string.Format("����ע��ʧ��\n{0}", err.Message));
                }
            }
            catch (System.Exception err)
            {
                MessageBox.Show(err.Message);
            }
        }
Example #2
0
        public void ScreenShotCommand() // This method can have any name
        {
            DocumentCollection acDocMgr = cadApplication.DocumentManager;
            Document           document = cadApplication.DocumentManager.MdiActiveDocument;


            string fileName = string.Empty;

            if (acDocMgr.Count > 1)
            {
                MessageBox.Show("已经有编辑的源文件在编辑,请手动关闭当前编辑的文件!");
                return;
            }
            else if (acDocMgr.Count == 1)
            {
                string[] args = Environment.GetCommandLineArgs();

                if (args.Length < 5)
                {
                    cadApplication.ShowAlertDialog("参数传递错误!");
                    return;
                }

                fileName = args[1];
                Environment.SetEnvironmentVariable("fileName", fileName);


                /// 如果是只有一个文档的话,且为源文件的话
                string curDocName = document.Name;

                if (curDocName.Contains(fileName))
                {
                    if (File.Exists(curDocName) &&
                        curDocName.IndexOf(orgDwgextesion) > -1)
                    {
                        string fName = curDocName.Replace(orgDwgextesion, dwgExtesion);
                        if (File.Exists(fName))
                        {
                            File.Delete(fName);
                        }
                    }
                    else if (File.Exists(curDocName) &&
                             curDocName.IndexOf(orgDwgextesion) < 0)
                    {
                        string fName = curDocName.Replace(dwgExtesion, orgDwgextesion);
                        if (File.Exists(fName))
                        {
                            File.Delete(fName);
                        }
                    }
                }
            }
            string newFileName = fileName.Replace(dwgExtesion, orgDwgextesion);

            Database db = HostApplicationServices.WorkingDatabase;
            Editor   ed = cadApplication.DocumentManager.MdiActiveDocument.Editor;


            /// 当前最新位置的Polyline
            ObjectId objId = new ObjectId();
            Polyline pl    = (Polyline)AutoCADHelper.GetObjFromDic(ref objId, "redId", db, ed);

            if (pl == null)
            {
                return;
            }

            ///保留剪切前的文件
            if (!File.Exists(fileName))
            {
                db.SaveAs(fileName, DwgVersion.Current);
            }
            else
            {
                db.SaveAs(newFileName, DwgVersion.Current);
            }
            //MessageBox.Show(newFileName);
            ///实行剪切操作
            AutoCADHelper.TrimMap(pl);

            /// 矩形右上角的点
            Point2d pThird = pl.GetPoint2dAt(2);
            /// 矩形左下角的点
            Point2d pFirst = pl.GetPoint2dAt(0);



            PromptSelectionResult result = ed.SelectCrossingWindow(
                new Point3d(pFirst.X + 10, pFirst.Y + 10, 0),
                new Point3d(pThird.X - 10, pThird.Y - 10, 0));


            if (result.Status == PromptStatus.Error)
            {
                cadApplication.ShowAlertDialog("没有选中坐标点!");
            }
            else if (result.Status == PromptStatus.OK)
            {
                ///剪切一些没有剪切干净的图形
                ///选中所有的实体对象
                PromptSelectionResult resultAll = ed.SelectAll();

                using (Transaction trans = document.TransactionManager.StartTransaction())
                {
                    ObjectId[]      sIds = result.Value.GetObjectIds();
                    List <ObjectId> oIds = sIds.ToList <ObjectId>();
                    foreach (ObjectId pid in resultAll.Value.GetObjectIds())
                    {
                        if (!oIds.Contains(pid))
                        {
                            Entity ent = trans.GetObject(pid, OpenMode.ForWrite) as Entity;
                            if (ent == null)
                            {
                                continue;
                            }
                            ent.Erase();
                        }
                    }
                    trans.Commit();
                }
                //if (!File.Exists(fileName))
                //{
                //    db.SaveAs(fileName, DwgVersion.Current);
                //}
                //else
                //{
                //    CADTools.RunCommand(true, "_qsave", "");
                //}
            }
        }
Example #3
0
        public static void Breakatpoint()
        {
            Document acDoc = acApp.DocumentManager.MdiActiveDocument;
            Database acDb  = acDoc.Database;
            Editor   acEd  = acDoc.Editor;


            PromptSelectionResult psr = acEd.GetSelection();

            if (psr.Status != PromptStatus.OK)
            {
                return;
            }

            foreach (ObjectId id in psr.Value.GetObjectIds())
            {
                using (Transaction acTrans = acDb.TransactionManager.StartTransaction())
                {
                    BlockTable acBlkTbl;
                    acBlkTbl = acTrans.GetObject(acDb.BlockTableId,
                                                 OpenMode.ForRead) as BlockTable;
                    BlockTableRecord acBlkTblRec;
                    acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
                                                    OpenMode.ForWrite) as BlockTableRecord;

                    Line line            = (Line)acTrans.GetObject(id, OpenMode.ForRead);
                    PromptPointResult pr = acEd.GetPoint("Select break point");
                    if (pr.Status != PromptStatus.Cancel)
                    {
                        ObjectId objId;
                        Point3d  pointPr = pr.Value;
                        //Test to ensure that point selected actually lies on the line
                        if (IsPointOnCurve(line, pointPr))
                        {
                            //create new line from selected line start point to point chosen

                            var  lineseg   = new LineSegment3d(line.StartPoint, pointPr);
                            var  vec       = lineseg.Direction.MultiplyBy(2).Negate();
                            Line line_seg1 = new Line(line.StartPoint, pointPr.Add(vec));
                            line_seg1.Layer = line.Layer;
                            objId           = acBlkTblRec.AppendEntity(line_seg1);
                            acTrans.AddNewlyCreatedDBObject(line_seg1, true);

                            //create new line from point chosen to end point on selected line
                            lineseg = new LineSegment3d(pointPr, line.EndPoint);
                            vec     = lineseg.Direction.MultiplyBy(2).Negate();
                            Line line_seg2 = new Line(pointPr.Subtract(vec), line.EndPoint);
                            line_seg2.Layer = line.Layer;
                            objId           = acBlkTblRec.AppendEntity(line_seg2);
                            acTrans.AddNewlyCreatedDBObject(line_seg2, true);

                            //remove origionally selected line
                            Entity acEnt = acTrans.GetObject(id, OpenMode.ForWrite) as Entity;
                            acEnt.Erase();
                            acEnt.Dispose();
                        }
                        else
                        {
                            MessageBox.Show("Point chosen does not lie on the line selected");
                        }
                    }
                    else
                    {
                        return;
                    }
                    acTrans.Commit();
                }
            }
        }
Example #4
0
        public void ColumnsToExcel()
        {
            Document adoc = Application.DocumentManager.MdiActiveDocument;

            if (adoc == null)
            {
                return;
            }

            Database db = adoc.Database;

            Editor ed = adoc.Editor;

            try
            {
                //Выбор текстов и линий
                TypedValue[]           tv  = new TypedValue[] { new TypedValue(0, "LWPOLYLINE,LINE,TEXT,MTEXT") };
                SelectionFilter        flt = new SelectionFilter(tv);
                PromptSelectionOptions pso = new PromptSelectionOptions();
                pso.MessageForAdding = "\nВыберите содержимое таблицы (LWPOLYLINE,LINE,TEXT,MTEXT). Нужно выбрать все тексты, а так же все горизонтальные линии, разделяющие строки таблицы";

                PromptSelectionResult acSSPrompt = adoc.Editor.GetSelection(pso, flt);
                if (acSSPrompt.Status == PromptStatus.OK)
                {
                    //SortedSet<LineSegment2d> horizontalLines = new SortedSet<LineSegment2d>(new HorizontalComparer());
                    List <LineSegment2d> horizontalLines = new List <LineSegment2d>();
                    SortedSet <SLEvent>  eventQueue      = new SortedSet <SLEvent>();
                    using (Transaction tr = db.TransactionManager.StartTransaction())
                    {
                        //Среди линий отобрать все горизонтальные линии в отдельную коллекцию
                        //Для всех текстов определить прямоугольник расположения
                        //Построить очередь событий начала и конца текстов, рассматривая их как горизонтальные отрезки
                        SelectionSet acSSet = acSSPrompt.Value;
                        foreach (ObjectId id in acSSet.GetObjectIds())
                        {
                            Entity ent = (Entity)tr.GetObject(id, OpenMode.ForRead);

                            if (ent is MText || ent is DBText)
                            {
                                string contents = GetTextContents(ent);
                                if (!String.IsNullOrEmpty(contents))
                                {
                                    Extents3d?ext = ent.Bounds;
                                    if (ext != null)
                                    {
                                        new TextInfo(contents, new Point2d(ext.Value.MaxPoint.X, ext.Value.MaxPoint.Y),
                                                     new Point2d(ext.Value.MinPoint.X, ext.Value.MinPoint.Y), eventQueue);
                                    }
                                }
                            }
                            else if (ent is Polyline)
                            {
                                Polyline polyline = ent as Polyline;
                                if (!polyline.HasBulges && !polyline.Closed)//не рассматривать замкнутые и полилинии с дугами
                                {
                                    for (int i = 0; i < polyline.NumberOfVertices - 1; i++)
                                    {
                                        Point2d segPt1 = polyline.GetPoint2dAt(i);
                                        Point2d segPt2 = polyline.GetPoint2dAt(i + 1);
                                        SelectHorizontalLines(segPt1, segPt2, horizontalLines);
                                    }
                                }
                            }
                            else if (ent is Line)
                            {
                                Line    line   = ent as Line;
                                Point2d segPt1 = new Point2d(line.StartPoint.X, line.StartPoint.Y);
                                Point2d segPt2 = new Point2d(line.EndPoint.X, line.EndPoint.Y);
                                SelectHorizontalLines(segPt1, segPt2, horizontalLines);
                            }
                        }

                        //TEST//TEST//TEST//TEST//TEST//TEST//TEST//TEST//TEST//TEST//TEST//TEST
                        //BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForWrite) as BlockTable;
                        //BlockTableRecord ms = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);

                        //foreach (LineSegment2d hor in horizontalLines)
                        //{
                        //    using (Line line = new Line(
                        //        new Point3d(hor.StartPoint.X, hor.StartPoint.Y, 0),
                        //        new Point3d(hor.EndPoint.X, hor.EndPoint.Y, 0)))
                        //    {
                        //        line.ColorIndex = 1;

                        //        ms.AppendEntity(line);
                        //        tr.AddNewlyCreatedDBObject(line, true);
                        //    }
                        //}
                        //TEST//TEST//TEST//TEST//TEST//TEST//TEST//TEST//TEST//TEST//TEST//TEST
                        tr.Commit();
                    }

                    //Используя логику сканирующей линии распределить все тексты по столбцам, отсортировав сверху вниз
                    SweepLine sweepLine = new SweepLine(eventQueue);

                    List <SortedSet <TextInfo> > columns = sweepLine.Columns;



                    //Для каждого столбца определить границы ячеек по следующим правилам:
                    // - Если прямоугольники расположения текстов перекрываются, то считать что тексты находятся в разных ячейках
                    // - Иначе проверить есть ли между центральными точками прямоугольников горизонтальные линии. Если нет, то тексты находятся в одной ячейке

                    //for (int i = 0; i < columns.Count; i++)
                    //{
                    //    SortedSet<TextInfo> col = columns.ElementAt(i);

                    List <List <string> > columnsToExcel = new List <List <string> >();

                    foreach (SortedSet <TextInfo> col in columns)
                    {
                        List <string> colToExcel = new List <string>();
                        columnsToExcel.Add(colToExcel);
                        TextInfo prevTi = null;
                        foreach (TextInfo ti in col)
                        {
                            bool concat = false;
                            if (prevTi != null)
                            {
                                if (!Utils.BoxesAreSuperimposed(prevTi.MaxPt, prevTi.MinPt, ti.MaxPt, ti.MinPt) &&
                                    !AreDivided(prevTi, ti, horizontalLines))   //Проверить есть ли между текстами горизонтальная линия
                                {
                                    concat = true;
                                }
                            }

                            if (concat)
                            {
                                colToExcel[colToExcel.Count - 1] = colToExcel[colToExcel.Count - 1] + " " + ti.Contents;
                            }
                            else
                            {
                                colToExcel.Add(ti.Contents);
                            }


                            prevTi = ti;
                            //colToExcel[colToExcel.Count] = colToExcel[colToExcel.Count] + " " + ti.Contents;

                            //colToExcel.Add(ti.Contents);
                        }
                    }


                    //Excel
                    Excel.Application instance = null;
                    try
                    {
                        instance = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
                    }
                    catch (System.Runtime.InteropServices.COMException)
                    {
                        instance = new Excel.Application();
                    }


                    try
                    {
                        instance.ScreenUpdating = false;
                        //Создать новую книгу Excel и записать в нее таблицу
                        Excel._Workbook workbook = instance.Workbooks.Add(Type.Missing);
                        Excel.Worksheet wSheet   = workbook.Sheets.Item[1];

                        int colNum = 1;
                        foreach (List <string> col in columnsToExcel)
                        {
                            int rowNum = 1;
                            foreach (string val in col)
                            {
                                wSheet.Cells[rowNum, colNum] = val;
                                rowNum++;
                            }

                            colNum++;
                        }
                    }
                    finally
                    {
                        instance.ScreenUpdating = true;
                        instance.Visible        = true;
                    }
                }
            }
            catch (System.Exception ex)
            {
                CommonException(ex, "Ошибка при переносе столбцов текста из AutoCAD в Excel");
            }
        }
Example #5
0
        public static System.Data.DataTable GetAllPolylineNums()
        {
            System.Data.DataTable table = new System.Data.DataTable("编码");
            table.Columns.Add(new System.Data.DataColumn(("多段线id"), typeof(string)));
            table.Columns.Add(new System.Data.DataColumn(("个体编码"), typeof(string)));
            table.Columns.Add(new System.Data.DataColumn(("个体要素"), typeof(string)));
            table.Columns.Add(new System.Data.DataColumn(("个体名称"), typeof(string)));
            table.Columns.Add(new System.Data.DataColumn(("数量"), typeof(string)));
            table.Columns.Add(new System.Data.DataColumn(("个体阶段"), typeof(string)));

            System.Data.DataColumn column;
            System.Data.DataRow    row;

            Document     doc            = Application.DocumentManager.MdiActiveDocument;
            Editor       ed             = doc.Editor;
            Database     db             = doc.Database;
            DocumentLock m_DocumentLock = Application.DocumentManager.MdiActiveDocument.LockDocument();

            try
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    foreach (ObjectId layerId in LayersToList(db))
                    {
                        LayerTableRecord layer = tr.GetObject(layerId, OpenMode.ForRead) as LayerTableRecord;

                        TypedValue[] filList = new TypedValue[1] {
                            new TypedValue((int)DxfCode.LayerName, layer.Name)
                        };
                        SelectionFilter sfilter = new SelectionFilter(filList);

                        PromptSelectionResult result = ed.SelectAll(sfilter);
                        if (result.Status == PromptStatus.OK)
                        {
                            SelectionSet acSSet = result.Value;
                            foreach (ObjectId id in acSSet.GetObjectIds())
                            {
                                DBObject obj = id.GetObject(OpenMode.ForRead); //以读的方式打开对象

                                ObjectId dictId = obj.ExtensionDictionary;     //获取对象的扩展字典的id

                                Entity ent1 = tr.GetObject(id, OpenMode.ForRead) as Entity;
                                if (ent1 is Polyline && !dictId.IsNull)
                                {
                                    DBDictionary dict = dictId.GetObject(OpenMode.ForRead) as DBDictionary;//获取对象的扩展字典
                                    if (!dict.Contains("polylineNumber"))
                                    {
                                        continue;//如果扩展字典中没有包含指定关键 字的扩展记录,则返回null;
                                    }
                                    //先要获取对象的扩展字典或图形中的有名对象字典,然后才能在字典中获取要查询的扩展记录
                                    ObjectId     xrecordId = dict.GetAt("polylineNumber");                     //获取扩展记录对象的id
                                    Xrecord      xrecord   = xrecordId.GetObject(OpenMode.ForRead) as Xrecord; //根据id获取扩展记录对象
                                    ResultBuffer resBuf    = xrecord.Data;

                                    ResultBufferEnumerator rator = resBuf.GetEnumerator();
                                    int i = 0;

                                    List <string> values = new List <string>();
                                    while (rator.MoveNext())
                                    {
                                        TypedValue re = rator.Current;
                                        values.Add((string)re.Value);
                                    }

                                    bool hasData = false;
                                    foreach (System.Data.DataRow item in table.Rows)
                                    {
                                        if ((string)item["个体编码"] == values[0] && (string)item["个体要素"] == values[1] && (string)item["个体名称"] == values[2] && (string)item["个体阶段"] == values[3])
                                        {
                                            item["多段线id"] += id.Handle.Value.ToString() + ",";
                                            int count = 0;
                                            int.TryParse((string)item["数量"], out count);
                                            item["数量"] = count + 1;
                                            hasData    = true;
                                            break;
                                        }
                                    }
                                    if (!hasData)
                                    {
                                        row          = table.NewRow();
                                        row["多段线id"] = id.Handle.Value.ToString() + ",";
                                        row["数量"]    = 1;
                                        while (rator.MoveNext())
                                        {
                                            TypedValue re = rator.Current;
                                            if (i == 0)
                                            {
                                                row["个体编码"] = re.Value;
                                            }
                                            if (i == 1)
                                            {
                                                row["个体要素"] = re.Value;
                                            }
                                            if (i == 2)
                                            {
                                                row["个体名称"] = re.Value;
                                            }
                                            if (i == 3)
                                            {
                                                row["个体阶段"] = re.Value;
                                            }
                                            i++;
                                        }
                                        table.Rows.Add(row);
                                    }
                                    resBuf.Dispose();
                                    xrecord.Dispose();
                                    dict.Dispose();
                                }
                                ent1.Dispose();
                                obj.Dispose();
                            }
                        }

                        layer.Dispose();
                    }
                    tr.Commit();
                }
            }
            catch (Exception e)
            {
                System.Windows.Forms.MessageBox.Show(e.ToString());
            }
            finally
            {
                m_DocumentLock.Dispose();
            }
            return(table);
        }
Example #6
0
        public void ShowPick()
        {
            Document doc    = Application.DocumentManager.MdiActiveDocument;
            Database db     = doc.Database;
            Editor   editor = doc.Editor;

            try
            {
                using (Transaction trans = db.TransactionManager.StartTransaction())
                {
                    // 获取PickFirst选择集
                    PromptSelectionResult psr = editor.SelectImplied();

                    // 如果提示状态OK,说明启动命令前选择了对象;
                    if (psr.Status != PromptStatus.OK)
                    {
                        editor.WriteMessage("没有选中对象\n");
                        return;
                    }
                    SelectionSet sset = psr.Value;
                    editor.WriteMessage("选中{0:d}对象,第一个类型为{1:s}\n", sset.Count, sset[0].ObjectId.ObjectClass.DxfName);
                    StringBuilder sb = new StringBuilder();
                    foreach (SelectedObject so in sset)
                    {
                        if (so.ObjectId.ObjectClass.DxfName == "TEXT")
                        {
                            DBText text = (DBText)so.ObjectId.GetObject(OpenMode.ForRead);
                            sb.AppendLine(text.TextString);
                            string s = string.Format("( {0:f1}, {1:f1} ) ( {2:f1}, {3:f1} )",
                                                     text.GeometricExtents.MinPoint.X,
                                                     text.GeometricExtents.MinPoint.Y,
                                                     text.GeometricExtents.MaxPoint.X,
                                                     text.GeometricExtents.MaxPoint.Y
                                                     );
                            sb.AppendLine(s);
                            //sb.Append(text.Position.ToString());
                        }
                        else if (so.ObjectId.ObjectClass.DxfName == "MTEXT")
                        {
                            MText text = (MText)so.ObjectId.GetObject(OpenMode.ForRead);
                            sb.AppendLine(text.Contents);
                            sb.AppendLine(text.Text);
                            string s = string.Format("( {0:f1}, {1:f1} ) ( {2:f1}, {3:f1} )",
                                                     text.GeometricExtents.MinPoint.X,
                                                     text.GeometricExtents.MinPoint.Y,
                                                     text.GeometricExtents.MaxPoint.X,
                                                     text.GeometricExtents.MaxPoint.Y
                                                     );
                            sb.AppendLine(s);
                            //sb.Append(text.Location.ToString());
                        }
                        else if (so.ObjectId.ObjectClass.DxfName == "LINE")
                        {
                            Line line = (Line)so.ObjectId.GetObject(OpenMode.ForRead);
                            sb.Append(line.StartPoint.ToString());
                            sb.Append(line.EndPoint.ToString());
                        }
                        else if (so.ObjectId.ObjectClass.DxfName == "LWPOLYLINE")
                        {
                            Polyline pLine = (Polyline)so.ObjectId.GetObject(OpenMode.ForRead);
                            for (int i = 0; i < pLine.NumberOfVertices; i++)
                            {
                                sb.Append(pLine.GetPoint2dAt(i).ToString());
                            }
                        }
                        else if (so.ObjectId.ObjectClass.DxfName == "INSERT")
                        {
                            Entity entity = (Entity)so.ObjectId.GetObject(OpenMode.ForWrite);
                            if (entity is BlockReference)
                            {
                                BlockReference br = entity as BlockReference;
                                sb.Append(br.Name);
                            }
                        }
                    }
                    editor.WriteMessage(sb.ToString());
                    trans.Commit();
                }
            }
            catch (System.Exception e)
            {
                editor.WriteMessage(e.ToString());
            }
        }
Example #7
0
        private bool SelectZuRaumIdEntities(bool ignoreFirstCancel)
        {
            _HKBlocks.Clear();
            _VermPunkte.Clear();
            _RaumPolygons.Clear();

            //LayerOnAndThaw(new List<string> { _HoePrOptions.PolygonLayer, "X_FH_SYMB", "X_SPKT_SYMB", "X_GH_SYMB", "X_DR_SYMB", FEHLER_LINE_LAYER });
            LayerOnAndThawRegex(new List <string> {
                "^" + _HoePrOptions.PolygonLayer + "$", "^X", "^" + FEHLER_LINE_LAYER + "$"
            });

            var             ed     = _AcAp.Application.DocumentManager.MdiActiveDocument.Editor;
            SelectionFilter filter = new SelectionFilter(new TypedValue[] {
                new TypedValue((int)DxfCode.Operator, "<OR"),

                new TypedValue((int)DxfCode.Operator, "<AND"),
                new TypedValue((int)DxfCode.Start, "INSERT"),
                new TypedValue((int)DxfCode.BlockName, _HoePrOptions.HKBlockname),
                new TypedValue((int)DxfCode.Operator, "AND>"),

                // zusätzlicher höhenkotenblock
                new TypedValue((int)DxfCode.Operator, "<AND"),
                new TypedValue((int)DxfCode.Start, "INSERT"),
                new TypedValue((int)DxfCode.BlockName, HOEHENKOTEN_BLOCK_2),
                new TypedValue((int)DxfCode.Operator, "AND>"),

                new TypedValue((int)DxfCode.Operator, "<AND"),
                new TypedValue((int)DxfCode.Start, "INSERT"),
                new TypedValue((int)DxfCode.BlockName, "GEOINOVA"),
                new TypedValue((int)DxfCode.Operator, "<OR"),
                new TypedValue((int)DxfCode.LayerName, "X_FH_SYMB"),
                new TypedValue((int)DxfCode.LayerName, "X_SPKT_SYMB"),
                new TypedValue((int)DxfCode.LayerName, "X_GH_SYMB"),
                new TypedValue((int)DxfCode.LayerName, "X_DR_SYMB"),
                new TypedValue((int)DxfCode.Operator, "OR>"),
                new TypedValue((int)DxfCode.Operator, "AND>"),

                new TypedValue((int)DxfCode.Operator, "<AND"),
                new TypedValue((int)DxfCode.Start, "*POLYLINE"),
                new TypedValue((int)DxfCode.LayerName, _HoePrOptions.PolygonLayer),
                new TypedValue((int)DxfCode.Operator, "AND>"),
                new TypedValue((int)DxfCode.Operator, "OR>"),
            });

            PromptSelectionResult res = ed.GetSelection(filter);

            if (res.Status == PromptStatus.Cancel && ignoreFirstCancel)
            {
                res = ed.GetSelection(filter);
            }
            if (res.Status != PromptStatus.OK)
            {
                return(false);
            }

            List <ObjectId> allEntities = null;

#if BRX_APP
            SelectionSet ss = res.Value;
#else
            using (SelectionSet ss = res.Value)
#endif
            {
                allEntities = ss.GetObjectIds().ToList();
            }

            if (allEntities == null || allEntities.Count == 0)
            {
                return(false);
            }

            bool someMarkedAsOk = false;

            using (Transaction myT = _TransMan.StartTransaction())
            {
                foreach (var oid in allEntities)
                {
                    Entity ent = _TransMan.GetObject(oid, OpenMode.ForRead) as Entity;
                    if (ent == null)
                    {
                        continue;
                    }
                    BlockReference blockRef = ent as BlockReference;
                    if (blockRef != null)
                    {
                        var bd = (BlockTableRecord)_TransMan.GetObject(blockRef.BlockTableRecord, OpenMode.ForRead);

                        if (
                            (string.Compare(_HoePrOptions.HKBlockname, blockRef.Name, StringComparison.OrdinalIgnoreCase) == 0) ||
                            (string.Compare(HOEHENKOTEN_BLOCK_2, blockRef.Name, StringComparison.OrdinalIgnoreCase) == 0)
                            )
                        {
                            //HKBlocks
                            if (!MarkedAsOk(oid))
                            {
                                _HKBlocks.Add(oid);
                            }
                            else
                            {
                                Plan2Ext.Globs.Stern(blockRef.Position, 1.0, 32, color: 3, highLighted: false);
                                someMarkedAsOk = true;
                            }
                        }
                        else
                        {
                            _VermPunkte.Add(oid);
                        }
                    }
                    else
                    {
                        //Polylines
                        if (string.Compare(_HoePrOptions.PolygonLayer, ent.Layer, StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            _RaumPolygons.Add(oid);
                        }
                    }
                }
                myT.Commit();
            }

            if (someMarkedAsOk)
            {
                log.Warn("Einige Blöcke wurden ignoriert, da sie als OK markiert wurden.");
            }

            if (_HKBlocks.Count == 0)
            {
                log.Warn("Es wurden keine Höhenkoten gefunden!");
            }
            else
            {
                log.InfoFormat(CultureInfo.CurrentCulture, "Anzahl der Höhenkoten: {0}", _HKBlocks.Count);
            }

            if (_VermPunkte.Count == 0)
            {
                log.Warn("Es wurden keine passenden Vermessungspunkte gefunden!");
            }
            else
            {
                log.InfoFormat(CultureInfo.CurrentCulture, "Anzahl der Vermessungspunkte: {0}", _VermPunkte.Count);
            }

            if (_RaumPolygons.Count == 0)
            {
                string msg = "Es wurden keine Raumpolylinien gewählt!";
                log.Warn(msg);
                _AcAp.Application.ShowAlertDialog(msg);
            }
            else
            {
                log.InfoFormat(CultureInfo.CurrentCulture, "Anzahl der Raumpolylinien: {0}", _RaumPolygons.Count);
            }

            if (_HKBlocks.Count > 0 && _VermPunkte.Count > 0 && _RaumPolygons.Count > 0)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Example #8
0
        public void TcLiangZhuLaJin()
        {
            int    num;
            int    num4;
            object obj;

            try
            {
IL_01:
                ProjectData.ClearProjectError();
                num = -2;
IL_09:
                int num2 = 2;
                Document mdiActiveDocument = Application.DocumentManager.MdiActiveDocument;
IL_16:
                num2 = 3;
                Database database = mdiActiveDocument.Database;
IL_1F:
                num2 = 4;
                using (Transaction transaction = database.TransactionManager.StartTransaction())
                {
                    TypedValue[] array  = new TypedValue[1];
                    Array        array2 = array;
                    TypedValue   typedValue;
                    typedValue..ctor(0, "LWPOLYLINE");
                    array2.SetValue(typedValue, 0);
                    SelectionFilter       selectionFilter = new SelectionFilter(array);
                    PromptSelectionResult selection       = mdiActiveDocument.Editor.GetSelection(selectionFilter);
                    if (selection.Status == 5100)
                    {
                        SelectionSet value    = selection.Value;
                        Entity       e        = (Entity)transaction.GetObject(value[0].ObjectId, 0);
                        Entity       e2       = (Entity)transaction.GetObject(value[checked (value.Count - 1)].ObjectId, 0);
                        Point3d      point3d  = CAD.GetEntCenter(e);
                        Point3d      point3d2 = CAD.GetEntCenter(e2);
                        if (point3d.X > point3d2.X)
                        {
                            Point3d point3d3 = point3d;
                            point3d  = point3d2;
                            point3d2 = point3d3;
                        }
                        else if (point3d.X == point3d2.X & point3d.Y > point3d2.Y)
                        {
                            Point3d point3d4 = point3d;
                            point3d  = point3d2;
                            point3d2 = point3d4;
                        }
                        if (Class36.double_0 == 0.0)
                        {
                            Class36.double_0 = 5.0;
                        }
                        Class36.smethod_8(point3d, point3d2, Class36.double_0);
                    }
                    transaction.Commit();
                }
IL_177:
                num2 = 6;
                if (Information.Err().Number <= 0)
                {
                    goto IL_19C;
                }
IL_188:
                num2 = 7;
                Interaction.MsgBox(Information.Err().Description, MsgBoxStyle.OkOnly, null);
IL_19C:
                goto IL_218;
IL_19E:
                int num3 = num4 + 1;
                num4     = 0;
                @switch(ICSharpCode.Decompiler.ILAst.ILLabel[], num3);
IL_1D2:
                goto IL_20D;
IL_1D4:
                num4 = num2;
                if (num <= -2)
                {
                    goto IL_19E;
                }
                @switch(ICSharpCode.Decompiler.ILAst.ILLabel[], num);
                IL_1EA :;
            }
            catch when(endfilter(obj is Exception & num != 0 & num4 == 0))
            {
                Exception ex = (Exception)obj2;

                goto IL_1D4;
            }
IL_20D:
            throw ProjectData.CreateProjectError(-2146828237);
IL_218:
            if (num4 != 0)
            {
                ProjectData.ClearProjectError();
            }
        }
Example #9
0
        public void TcZLJ_YJK()
        {
            int    num;
            int    num4;
            object obj;

            try
            {
IL_01:
                ProjectData.ClearProjectError();
                num = -2;
IL_09:
                int num2 = 2;
                Document mdiActiveDocument = Application.DocumentManager.MdiActiveDocument;
IL_16:
                num2 = 3;
                Database database = mdiActiveDocument.Database;
IL_1F:
                num2 = 4;
                using (Transaction transaction = database.TransactionManager.StartTransaction())
                {
                    TypedValue[] array  = new TypedValue[1];
                    Array        array2 = array;
                    TypedValue   typedValue;
                    typedValue..ctor(0, "LWPOLYLINE");
                    array2.SetValue(typedValue, 0);
                    SelectionFilter       selectionFilter = new SelectionFilter(array);
                    PromptSelectionResult selection       = mdiActiveDocument.Editor.GetSelection(selectionFilter);
                    if (selection.Status == 5100)
                    {
                        SelectionSet value      = selection.Value;
                        Entity       e          = (Entity)transaction.GetObject(value[0].ObjectId, 0);
                        Entity       e2         = (Entity)transaction.GetObject(value[checked (value.Count - 1)].ObjectId, 0);
                        Point3d      entCenter  = CAD.GetEntCenter(e);
                        Point3d      entCenter2 = CAD.GetEntCenter(e2);
                        if (Class36.double_0 == 0.0)
                        {
                            Class36.double_0 = 2.0;
                        }
                        this.DrawLaJinYJK(entCenter, entCenter2, Class36.double_0);
                    }
                    transaction.Commit();
                }
IL_129:
                num2 = 6;
                if (Information.Err().Number <= 0)
                {
                    goto IL_14E;
                }
IL_13A:
                num2 = 7;
                Interaction.MsgBox(Information.Err().Description, MsgBoxStyle.OkOnly, null);
IL_14E:
                goto IL_1CA;
IL_150:
                int num3 = num4 + 1;
                num4     = 0;
                @switch(ICSharpCode.Decompiler.ILAst.ILLabel[], num3);
IL_184:
                goto IL_1BF;
IL_186:
                num4 = num2;
                if (num <= -2)
                {
                    goto IL_150;
                }
                @switch(ICSharpCode.Decompiler.ILAst.ILLabel[], num);
                IL_19C :;
            }
            catch when(endfilter(obj is Exception & num != 0 & num4 == 0))
            {
                Exception ex = (Exception)obj2;

                goto IL_186;
            }
IL_1BF:
            throw ProjectData.CreateProjectError(-2146828237);
IL_1CA:
            if (num4 != 0)
            {
                ProjectData.ClearProjectError();
            }
        }
Example #10
0
        /// <summary>
        /// Загружает в объект свойства всех слоев проекта с привязанными
        /// к ним фигурами типа: точка, отрезок и окружность.
        /// </summary>
        private void Load()
        {
            // Обнуляем коллекцию слоев.
            Layers = new ObservableCollection <Layer>();

            // Получаем текущий документ, доступ к командной строке и БД.
            Document doc = AcadAS.Application.DocumentManager.MdiActiveDocument;
            Editor   ed  = doc.Editor;
            Database db  = doc.Database;

            // Начинаем транзакцию.
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                // Получаем таблицу слоев документа.
                LayerTable lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead);
                // Добавляем в нашу коллекцию все слои с требуемыми параметрами.
                foreach (ObjectId ltrId in lt)
                {
                    LayerTableRecord ltr = (LayerTableRecord)tr.GetObject(ltrId, OpenMode.ForRead);
                    Layers.Add(new Layer(ltr));
                }
                // Получаем список фигур (точка, отрезок и окружность) каждого слоя,
                // и сохраняем требуемыме параметры фигур в коллекции каждого слоя.
                foreach (var layer in Layers)
                {
                    // Обновляем предствление пользователя.
                    if (Layers[0] == layer)
                    {
                        _selectedLayer = layer;
                        OnPropertyChanged("SelectedLayer");
                    }

                    // Задание параметров фильтра.
                    TypedValue[] filterlist = new TypedValue[8];
                    filterlist[0] = new TypedValue((int)DxfCode.Operator, "<AND");
                    filterlist[1] = new TypedValue((int)DxfCode.LayerName, layer.Name);
                    filterlist[2] = new TypedValue((int)DxfCode.Operator, "<OR");
                    filterlist[3] = new TypedValue((int)DxfCode.Start, "POINT");
                    filterlist[4] = new TypedValue((int)DxfCode.Start, "LINE");
                    filterlist[5] = new TypedValue((int)DxfCode.Start, "CIRCLE");
                    filterlist[6] = new TypedValue((int)DxfCode.Operator, "OR>");
                    filterlist[7] = new TypedValue((int)DxfCode.Operator, "AND>");

                    // Создаем фильтр.
                    SelectionFilter filter = new SelectionFilter(filterlist);
                    // пытаемся получить ссылки на объекты с учетом фильтра
                    PromptSelectionResult selRes = ed.SelectAll(filter);

                    // Получаем массив ID объектов.
                    if (selRes.Value != null)
                    {
                        ObjectId[] ids = selRes.Value.GetObjectIds();

                        foreach (ObjectId id in ids)
                        {
                            // Приводим каждый из них к типу Entity.
                            Entity entity = (Entity)tr.GetObject(id, OpenMode.ForRead);
                            // Классифицируем по группам.
                            if (entity.GetType() == typeof(AcadDS.DBPoint))
                            {
                                layer.Points.Add(new Model.Point(entity as AcadDS.DBPoint));
                            }
                            else if (entity.GetType() == typeof(AcadDS.Line))
                            {
                                layer.Lines.Add(new Model.Line(entity as AcadDS.Line));
                            }
                            else if (entity.GetType() == typeof(AcadDS.Circle))
                            {
                                layer.Circles.Add(new Model.Circle(entity as AcadDS.Circle));
                            }
                        }
                    }
                }
                tr.Commit();
            }
        }
Example #11
0
        public object GetGuJinPoint(ref Point3d P1, ref Point3d P2)
        {
            int    num;
            object obj2;
            int    num8;
            object obj3;

            try
            {
IL_01:
                ProjectData.ClearProjectError();
                num = -2;
IL_09:
                int num2 = 2;
                Document mdiActiveDocument = Application.DocumentManager.MdiActiveDocument;
IL_16:
                num2 = 3;
                Database database = mdiActiveDocument.Database;
IL_1F:
                num2 = 4;
                using (Transaction transaction = database.TransactionManager.StartTransaction())
                {
                    TypedValue[] array  = new TypedValue[1];
                    Array        array2 = array;
                    TypedValue   typedValue;
                    typedValue..ctor(0, "LWPOLYLINE");
                    array2.SetValue(typedValue, 0);
                    SelectionFilter       selectionFilter = new SelectionFilter(array);
                    PromptSelectionResult selection       = mdiActiveDocument.Editor.GetSelection(selectionFilter);
                    if (selection.Status == 5100)
                    {
                        SelectionSet value      = selection.Value;
                        Entity       e          = (Entity)transaction.GetObject(value[0].ObjectId, 0);
                        Point3d      entCenter  = CAD.GetEntCenter(e);
                        double       num3       = entCenter.X;
                        double       num4       = entCenter.Y;
                        double       num5       = entCenter.X;
                        double       num6       = entCenter.Y;
                        IEnumerator  enumerator = value.GetEnumerator();
                        while (enumerator.MoveNext())
                        {
                            object         obj            = enumerator.Current;
                            SelectedObject selectedObject = (SelectedObject)obj;
                            e         = (Entity)transaction.GetObject(selectedObject.ObjectId, 0);
                            entCenter = CAD.GetEntCenter(e);
                            num3      = Math.Min(entCenter.X, num3);
                            num4      = Math.Min(entCenter.Y, num4);
                            num5      = Math.Max(entCenter.X, num5);
                            num6      = Math.Max(entCenter.Y, num6);
                        }
                        if (enumerator is IDisposable)
                        {
                            (enumerator as IDisposable).Dispose();
                        }
                        P1..ctor(num3, num4, 0.0);
                        P2..ctor(num5, num6, 0.0);
                    }
                    transaction.Commit();
                }
IL_1AC:
                num2 = 6;
                if (Information.Err().Number <= 0)
                {
                    goto IL_1D1;
                }
IL_1BD:
                num2 = 7;
                Interaction.MsgBox(Information.Err().Description, MsgBoxStyle.OkOnly, null);
IL_1D1:
                num2 = 9;
                obj2 = true;
IL_1E1:
                goto IL_261;
IL_1E3:
                int num7 = num8 + 1;
                num8     = 0;
                @switch(ICSharpCode.Decompiler.ILAst.ILLabel[], num7);
IL_21B:
                goto IL_256;
IL_21D:
                num8 = num2;
                if (num <= -2)
                {
                    goto IL_1E3;
                }
                @switch(ICSharpCode.Decompiler.ILAst.ILLabel[], num);
                IL_233 :;
            }
            catch when(endfilter(obj3 is Exception & num != 0 & num8 == 0))
            {
                Exception ex = (Exception)obj4;

                goto IL_21D;
            }
IL_256:
            throw ProjectData.CreateProjectError(-2146828237);
IL_261:
            object result = obj2;

            if (num8 != 0)
            {
                ProjectData.ClearProjectError();
            }
            return(result);
        }
Example #12
0
        transferTableData(Document docSrc, Document docTar, Database dbSrc, Database dbTar)
        {
            TypedValue[] tvs = new TypedValue[2] {
                new TypedValue((int)DxfCode.Start, RXClass.GetClass(typeof(Table)).DxfName),
                new TypedValue((int)DxfCode.LayerName, "ZZ_ZZ-TABLE")
            };

            SelectionFilter filter = new SelectionFilter(tvs);

            using (var tr = dbTar.TransactionManager.StartOpenCloseTransaction()) {
                PromptSelectionResult psr = BaseObjs._editor.SelectAll(filter);
                SelectionSet          ss  = psr.Value;
                if (ss == null)
                {
                    return;
                }
                ObjectId[] ids        = ss.GetObjectIds();
                ObjectId   idTableSrc = ids[0];
                Table      tblSrc     = (Table)tr.GetObject(idTableSrc, OpenMode.ForRead);

                Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument = docTar;
                psr = BaseObjs._editor.SelectAll(filter);
                ss  = psr.Value;
                ids = ss.GetObjectIds();
                ObjectId idTableTar = ids[0];
                Table    tblTar     = (Table)tr.GetObject(idTableTar, OpenMode.ForWrite);

                for (int i = 3; i < 14; i++)
                {
                    for (int j = 0; j < 2; j++)
                    {
                        string val = tblSrc.Cells[i, j].Value.ToString();
                        if (val != string.Empty)
                        {
                            tblTar.Cells[i, j].Value = val;
                        }
                    }
                }
                for (int i = 3; i < 14; i++)
                {
                    for (int j = 3; j < tblSrc.Columns.Count; j++)
                    {
                        string val = tblSrc.Cells[i, j].Value.ToString();
                        if (val != string.Empty)
                        {
                            tblTar.Cells[i, j].Value = val;
                        }
                    }
                }

                for (int i = 15; i < 23; i++)
                {
                    string val = tblSrc.Cells[i, 1].Value.ToString();
                    if (val != string.Empty)
                    {
                        tblTar.Cells[i, 1].Value = val;
                    }
                }
                tr.Commit();
            }
        }
Example #13
0
        public void ExportToCSVFile()
        {
            var acDoc = AcAp.DocumentManager.MdiActiveDocument;
            var acDb  = acDoc.Database;
            var ed    = acDoc.Editor;


            var filter = new SelectionFilter(new[]
            {
                new TypedValue(-4, "OR"),
                new TypedValue(0, "ARC,CIRCLE,ELLIPSE,LINE,LWPOLYLINE,SPLINE"),
                new TypedValue(-4, "AND"),
                new TypedValue(0, "POLYLINE"),
                new TypedValue(-4, "NOT"),
                new TypedValue(-4, "&"),
                new TypedValue(70, 112),
                new TypedValue(-4, "NOT>"),
                new TypedValue(-4, "AND>"),
                new TypedValue(-4, "OR>"),
            });

            PromptSelectionResult selection = ed.GetSelection(filter);

            if (selection.Status == PromptStatus.OK)
            {
                return;
            }

            sw.Forms.SaveFileDialog sfd = new sw.Forms.SaveFileDialog();
            sfd.Filter = "*.csv Files|*.csv";

            try
            {
                using (Transaction acTrans = acDb.TransactionManager.StartTransaction())
                {
                    sfd.ShowDialog();
                    string filename = sfd.FileName;

                    if (filename != "")
                    {
                        StreamWriter sWriter;
                        sWriter = GetWriterForFile(filename);

                        var lengths = selection.Value
                                      .Cast <SelectedObject>()
                                      .Select(selObj => (Curve)acTrans.GetObject(selObj.ObjectId, OpenMode.ForRead))
                                      .ToLookup(curve => curve.GetType().Name,                         // <- key selector
                                                curve => curve.GetDistanceAtParameter(curve.EndParam)) // <- element selector
                                      .ToDictionary(group => group.Key,                                // <- key selector
                                                    group => group.Sum());                             // <- element selector

                        // print results
                        foreach (var entry in lengths)
                        {
                            sWriter.WriteLine($"\n{entry.Key,-12} , {entry.Value,9:0.00}");
                        }
                    }
                    else
                    {
                        ed.WriteMessage("\nHa, you're joking, right?");
                    }
                }
            }
            catch
            {
                ed.WriteMessage("\nI don't know how to write....");
            }
        }
Example #14
0
        public void Play()
        {
            //Doc = Application.DocumentManager.MdiActiveDocument;
            //Db = Doc.Database;
            //DL = Doc.LockDocument(DocumentLockMode.ProtectedAutoWrite, null, null, true);

            //Editor Editor = Application.DocumentManager.MdiActiveDocument.Editor;

            PromptSelectionResult acPSR = AC.Editor.GetSelection();

            // 선택한 객체를 받음
            if (acPSR.Status == PromptStatus.OK)
            {
                var edgePtrs  = new Curve2dCollection();
                var edgeTypes = new IntegerCollection();

                using (Transaction T = AC.DB.TransactionManager.StartTransaction())
                {
                    BlockTable       BT  = T.GetObject(AC.DB.BlockTableId, OpenMode.ForWrite) as BlockTable;
                    BlockTableRecord BTR = T.GetObject(BT[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

                    SelectionSet acSSet = acPSR.Value;

                    foreach (var objID in acSSet.GetObjectIds())
                    {
                        var acEnt = T.GetObject(objID, OpenMode.ForWrite) as Entity;

                        if (acEnt is Polyline)
                        {
                            Polyline acPL = acEnt as Polyline;

                            GetEdgeInformation(acPL, ref edgePtrs, ref edgeTypes);
                        }
                    }
                }

                var acPolylines = from a in edgePtrs.Cast <Curve2d>()
                                  orderby a.StartPoint.GetDistanceTo(a.EndPoint) descending
                                  select a;

                //var usedCurve = new List<Curve2d>();
                var usedCurve = new List <Point2d>();

                acPolylines.Cast <Curve2d>().ToList().ForEach(c =>
                {
                    var CenterP = CADUtil.GetCenterPoint2d(c.StartPoint, c.EndPoint);

                    var curves = from a in edgePtrs.Cast <Curve2d>().ToList()
                                 where a != c
                                 select a;

                    // c와 평행한 선을 받음
                    var MatchedCurves                 = from a in curves
                                                let d = a.GetDistanceTo(c)
                                                        where CADUtil.GetVector(a).GetNormal().IsEqualTo(-CADUtil.GetVector(c).GetNormal())
                                                        where d > Min && d < Max
                                                        let cp1                     = CADUtil.GetCenterPoint2d(c)
                                                                            let cp2 = CADUtil.GetCenterPoint2d(a)
                                                                                      orderby cp1.GetDistanceTo(cp2) ascending
                                                                                      select a;

                    if (MatchedCurves.Any())
                    {
                        //CAD.CreateLine(c.StartPoint, c.EndPoint);

                        bool B = true;

                        MatchedCurves.ToList().ForEach(c1 =>
                        {
                            var cp1 = CADUtil.GetCenterPoint2d(c1);

                            usedCurve.ForEach(cp2 =>
                            {
                                if (cp1.IsEqualTo(cp2))
                                {
                                    B = false;
                                }
                            });
                        });

                        if (B)
                        {
                            CreateRectangle(c, MatchedCurves.ToList());

                            usedCurve.Add(CADUtil.GetCenterPoint2d(c));
                        }
                    }
                });
            }
            else
            {
                Application.ShowAlertDialog("Number of objects selected: 0");
            }
        }
Example #15
0
        public void fOPEN()
        {
            Editor ed = acApp.DocumentManager.MdiActiveDocument.Editor;

            try
            {
                Utils.Utils.Init();

                Document acDoc   = acApp.DocumentManager.MdiActiveDocument;
                Database acCurDb = acDoc.Database;

                while (true)
                {
                    PromptSelectionOptions options = new PromptSelectionOptions();
                    options.SingleOnly        = true;
                    options.SinglePickInSpace = true;

                    // Request for objects to be selected in the drawing area
                    PromptSelectionResult acSSPrompt = acDoc.Editor.GetSelection(options);

                    // If the prompt status is OK, objects were selected
                    if (acSSPrompt.Status != PromptStatus.OK || acSSPrompt.Status == PromptStatus.Cancel)
                    {
                        Utils.Utils.End(); return;
                    }
                    if (acSSPrompt.Status == PromptStatus.OK)
                    {
                        SelectionSet acSSet = acSSPrompt.Value;

                        // Step through the objects in the selection set
                        SelectedObject acSSObj = acSSet[0];

                        string    layer = "";
                        Extents3d ext;

                        // Check to make sure a valid SelectedObject object was returned
                        if (acSSObj != null)
                        {
                            // Open the selected object for write
                            Entity acEnt = null;
                            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
                            {
                                acEnt = acTrans.GetObject(acSSObj.ObjectId, OpenMode.ForRead) as Entity;
                                acEnt.Unhighlight();
                                acEnt.Highlight();
                                layer = acEnt.Layer;
                                ext   = acEnt.GeometricExtents;
                            }
                            if (layer.Contains("!FDS_MESH"))
                            {
                                PromptKeywordOptions axisOptions = new PromptKeywordOptions("\nChoose opening axis");
                                axisOptions.Keywords.Add("X-axis");
                                axisOptions.Keywords.Add("Y-axis");
                                axisOptions.Keywords.Add("Z-axis");
                                axisOptions.Keywords.Add("All");
                                axisOptions.AllowNone = false;
                                PromptResult axis = ed.GetKeywords(axisOptions);

                                if (axis.Status != PromptStatus.OK || axis.Status == PromptStatus.Cancel)
                                {
                                    Utils.Utils.End(); return;
                                }
                                ;
                                if (axis.Status == PromptStatus.OK)
                                {
                                    if (axis.StringResult == "X-axis")
                                    {
                                        PromptKeywordOptions directionOptions = new PromptKeywordOptions("\nChoose direction");
                                        directionOptions.Keywords.Add("mIn");
                                        directionOptions.Keywords.Add("mAx");
                                        directionOptions.Keywords.Add("Both");
                                        directionOptions.AllowNone = false;
                                        PromptResult direction = ed.GetKeywords(directionOptions);
                                        if (direction.Status != PromptStatus.OK || direction.Status == PromptStatus.Cancel)
                                        {
                                            Utils.Utils.End(); return;
                                        }
                                        ;
                                        if (direction.Status == PromptStatus.OK)
                                        {
                                            if (direction.StringResult == "mIn")
                                            {
                                                Utils.Utils.CreateExtrudedSurface(ext.MinPoint, new Point3d(ext.MinPoint.X, ext.MaxPoint.Y, ext.MaxPoint.Z), "!FDS_MESH[open]", 1, 1);
                                            }
                                            else if (direction.StringResult == "mAx")
                                            {
                                                Utils.Utils.CreateExtrudedSurface(new Point3d(ext.MaxPoint.X, ext.MinPoint.Y, ext.MinPoint.Z), ext.MaxPoint, "!FDS_MESH[open]", 1, 1);
                                            }
                                            else if (direction.StringResult == "Both")
                                            {
                                                Utils.Utils.CreateExtrudedSurface(ext.MinPoint, new Point3d(ext.MinPoint.X, ext.MaxPoint.Y, ext.MaxPoint.Z), "!FDS_MESH[open]", 1, 1);
                                                Utils.Utils.CreateExtrudedSurface(new Point3d(ext.MaxPoint.X, ext.MinPoint.Y, ext.MinPoint.Z), ext.MaxPoint, "!FDS_MESH[open]", 1, 1);
                                            }
                                        }
                                    }
                                    else if (axis.StringResult == "Y-axis")
                                    {
                                        PromptKeywordOptions directionOptions = new PromptKeywordOptions("\nChoose direction");
                                        directionOptions.Keywords.Add("mIn");
                                        directionOptions.Keywords.Add("mAx");
                                        directionOptions.Keywords.Add("Both");
                                        directionOptions.AllowNone = false;
                                        PromptResult direction = ed.GetKeywords(directionOptions);
                                        if (direction.Status != PromptStatus.OK || direction.Status == PromptStatus.Cancel)
                                        {
                                            Utils.Utils.End(); return;
                                        }
                                        ;
                                        if (direction.Status == PromptStatus.OK)
                                        {
                                            if (direction.StringResult == "mIn")
                                            {
                                                Utils.Utils.CreateExtrudedSurface(ext.MinPoint, new Point3d(ext.MaxPoint.X, ext.MinPoint.Y, ext.MaxPoint.Z), "!FDS_MESH[open]", 1, 1);
                                            }
                                            else if (direction.StringResult == "mAx")
                                            {
                                                Utils.Utils.CreateExtrudedSurface(new Point3d(ext.MinPoint.X, ext.MaxPoint.Y, ext.MinPoint.Z), ext.MaxPoint, "!FDS_MESH[open]", 1, 1);
                                            }
                                            else if (direction.StringResult == "Both")
                                            {
                                                Utils.Utils.CreateExtrudedSurface(ext.MinPoint, new Point3d(ext.MaxPoint.X, ext.MinPoint.Y, ext.MaxPoint.Z), "!FDS_MESH[open]", 1, 1);
                                                Utils.Utils.CreateExtrudedSurface(new Point3d(ext.MinPoint.X, ext.MaxPoint.Y, ext.MinPoint.Z), ext.MaxPoint, "!FDS_MESH[open]", 1, 1);
                                            }
                                        }
                                    }
                                    else if (axis.StringResult == "Z-axis")
                                    {
                                        PromptKeywordOptions directionOptions = new PromptKeywordOptions("\nChoose direction");
                                        directionOptions.Keywords.Add("mIn");
                                        directionOptions.Keywords.Add("mAx");
                                        directionOptions.Keywords.Add("Both");
                                        directionOptions.AllowNone = false;
                                        PromptResult direction = ed.GetKeywords(directionOptions);
                                        if (direction.Status != PromptStatus.OK || direction.Status == PromptStatus.Cancel)
                                        {
                                            Utils.Utils.End(); return;
                                        }
                                        ;
                                        if (direction.Status == PromptStatus.OK)
                                        {
                                            if (direction.StringResult == "mIn")
                                            {
                                                Utils.Utils.CreateExtrudedSurface(ext.MinPoint, new Point3d(ext.MaxPoint.X, ext.MaxPoint.Y, ext.MinPoint.Z), "!FDS_MESH[open]", 1, 1);
                                            }
                                            else if (direction.StringResult == "mAx")
                                            {
                                                Utils.Utils.CreateExtrudedSurface(new Point3d(ext.MinPoint.X, ext.MinPoint.Y, ext.MaxPoint.Z), ext.MaxPoint, "!FDS_MESH[open]", 1, 1);
                                            }
                                            else if (direction.StringResult == "Both")
                                            {
                                                Utils.Utils.CreateExtrudedSurface(ext.MinPoint, new Point3d(ext.MaxPoint.X, ext.MaxPoint.Y, ext.MinPoint.Z), "!FDS_MESH[open]", 1, 1);
                                                Utils.Utils.CreateExtrudedSurface(new Point3d(ext.MinPoint.X, ext.MinPoint.Y, ext.MaxPoint.Z), ext.MaxPoint, "!FDS_MESH[open]", 1, 1);
                                            }
                                        }
                                    }
                                    else if (axis.StringResult == "All")
                                    {
                                        Utils.Utils.CreateExtrudedSurface(ext.MinPoint, new Point3d(ext.MinPoint.X, ext.MaxPoint.Y, ext.MaxPoint.Z), "!FDS_MESH[open]", 1, 1);
                                        Utils.Utils.CreateExtrudedSurface(new Point3d(ext.MaxPoint.X, ext.MinPoint.Y, ext.MinPoint.Z), ext.MaxPoint, "!FDS_MESH[open]", 1, 1);

                                        Utils.Utils.CreateExtrudedSurface(ext.MinPoint, new Point3d(ext.MaxPoint.X, ext.MinPoint.Y, ext.MaxPoint.Z), "!FDS_MESH[open]", 1, 1);
                                        Utils.Utils.CreateExtrudedSurface(new Point3d(ext.MinPoint.X, ext.MaxPoint.Y, ext.MinPoint.Z), ext.MaxPoint, "!FDS_MESH[open]", 1, 1);

                                        Utils.Utils.CreateExtrudedSurface(ext.MinPoint, new Point3d(ext.MaxPoint.X, ext.MaxPoint.Y, ext.MinPoint.Z), "!FDS_MESH[open]", 1, 1);
                                        Utils.Utils.CreateExtrudedSurface(new Point3d(ext.MinPoint.X, ext.MinPoint.Y, ext.MaxPoint.Z), ext.MaxPoint, "!FDS_MESH[open]", 1, 1);
                                    }

                                    using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
                                    {
                                        acEnt = acTrans.GetObject(acSSObj.ObjectId, OpenMode.ForRead) as Entity;
                                        acEnt.Unhighlight();
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (System.Exception e)
            {
                ed.WriteMessage("Program error: " + e.ToString());
                Utils.Utils.End();
                return;
            }
        }
Example #16
0
        public void GetBlockData(PurgeAttributeForm form)
        {
            form.Close();
            form.Dispose();

            Document acDoc     = Application.DocumentManager.MdiActiveDocument;
            Database acCurDb   = acDoc.Database;
            var      blockData = new BlockData()
            {
                AttNameAndvalue = new List <AttName_Value>()
            };

            // Start a transaction
            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                // Request for objects to be selected in the drawing area

                var opt = new PromptSelectionOptions()
                {
                    SingleOnly = true
                };
                PromptSelectionResult acSSPrompt = acDoc.Editor.GetSelection(opt);

                // If the prompt status is OK, objects were selected
                if (acSSPrompt.Status == PromptStatus.OK)
                {
                    SelectionSet acSSet = acSSPrompt.Value;

                    // Step through the objects in the selection set
                    foreach (SelectedObject acSSObj in acSSet)
                    {
                        Entity ent = acTrans.GetObject(acSSObj.ObjectId, OpenMode.ForRead) as Entity;
                        if (ent is BlockReference br)
                        {
                            blockData.BlockName = br.Name;

                            foreach (ObjectId attribute in br.AttributeCollection)
                            {
                                DBObject obj = acTrans.GetObject(attribute, OpenMode.ForRead);
                                if (obj is AttributeReference ar)
                                {
                                    blockData.AttNameAndvalue.Add(new AttName_Value {
                                        attName = ar.Tag, attValue = ar.TextString
                                    });
                                }
                            }
                        }

                        // Save the new object to the database
                        acTrans.Dispose();
                    }

                    // Dispose of the transaction
                }
            }

            using (var _form = new PurgeAttributeForm())
            {
                var drawingList = new List <string>();

                _form.SetTabIndex(1);
                _form.BlockData = blockData;
                _form.SetValueFromInput();

                var result = _form.ShowDialog();

                if (result == System.Windows.Forms.DialogResult.OK)
                {
                    drawingList = _form.AttributeDrawingList;
                }
                if (result == System.Windows.Forms.DialogResult.None)
                {
                    return;
                }

                ReplaceStringValue(drawingList, _form.AttBlockname, _form.LinkattAttributeName, _form.LinkAttValue, _form.ChangeattAttributeName, _form.ChangeAttValue);
            }
        }
Example #17
0
        public void PrintTT()
        {
            Document      acDoc     = Application.DocumentManager.MdiActiveDocument;
            Database      acCurDb   = acDoc.Database;
            Editor        ed        = Application.DocumentManager.MdiActiveDocument.Editor;
            List <String> imagelist = new List <String>();

            string directory = @"D:\";//磁盘路径
            string MediaName = comboBoxMedia.SelectedItem.ToString().Replace(" ", "_").Replace("毫米", "MM").Replace("英寸", "Inches").Replace("像素", "Pixels");

            try
            {
                if (PlotFactory.ProcessPlotState == ProcessPlotState.NotPlotting)
                {
                    using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
                    {
                        int flag = 0;
                        //获取当前布局管理器变量
                        LayoutManager acLayoutMgr = LayoutManager.Current;
                        //获取当前布局变量
                        Layout acLayout = (Layout)acTrans.GetObject(acLayoutMgr.GetLayoutId(acLayoutMgr.CurrentLayout), OpenMode.ForRead);
                        //Layout acLayout = (Layout)acTrans.GetObject(acLayoutMgr.GetLayoutId(acLayoutMgr.CurrentLayout), OpenMode.ForWrite);
                        //获取当前布局的打印信息
                        PlotInfo acPlInfo = new PlotInfo()
                        {
                            Layout = acLayout.ObjectId
                        };



                        //提示用户输入打印窗口的两个角点
                        PromptPointResult resultp = ed.GetPoint("\n指定第一个角点");
                        if (resultp.Status != PromptStatus.OK)
                        {
                            return;
                        }
                        Point3d basePt = resultp.Value;
                        resultp = ed.GetCorner("指定对角点", basePt);
                        if (resultp.Status != PromptStatus.OK)
                        {
                            return;
                        }
                        Point3d cornerPt = resultp.Value;

                        //选择实体对象
                        // PromptSelectionOptions result1 = new PromptSelectionOptions();

                        SelectionFilter frameFilter = new SelectionFilter(
                            new TypedValue[]
                            { new TypedValue(0, "LWPOLYLINE"),
                              new TypedValue(90, 4),
                              new TypedValue(70, 1) });


                        PromptSelectionResult selectedFrameResult = ed.SelectWindow(basePt, cornerPt, frameFilter);
                        // PromptSelectionResult selectedFrameResult = ed.GetSelection(result1, frameFilter);
                        PromptSelectionResult selectedFrameResult1 = ed.SelectAll(frameFilter);
                        if (selectedFrameResult.Status == PromptStatus.OK)
                        {
                            List <ObjectId> selectedObjectIds = new List <ObjectId>(selectedFrameResult.Value.GetObjectIds());
                            List <ObjectId> resultObjectIds   = new List <ObjectId>(selectedFrameResult.Value.GetObjectIds());
                            RemoveInnerPLine(acTrans, ref selectedObjectIds, ref resultObjectIds);
                            foreach (ObjectId frameId in resultObjectIds)
                            {
                                Polyline framePline = acTrans.GetObject(frameId, OpenMode.ForRead) as Polyline;
                                framePline.Highlight();
                            }


                            PlotSettings acPlSet = new PlotSettings(acLayout.ModelType);
                            acPlSet.CopyFrom(acLayout);
                            //着色打印选项,设置按线框进行打印
                            acPlSet.ShadePlot = PlotSettingsShadePlotType.Wireframe;
                            PlotSettingsValidator acPlSetVdr = PlotSettingsValidator.Current;
                            //打印比例
                            //用户标准打印
                            acPlSetVdr.SetUseStandardScale(acPlSet, true);
                            acPlSetVdr.SetStdScaleType(acPlSet, StdScaleType.ScaleToFit);

                            //居中打印
                            acPlSetVdr.SetPlotCentered(acPlSet, true);
                            //调用GetPlotStyleSheetList之后才可以使用SetCurrentStyleSheet
                            System.Collections.Specialized.StringCollection sc = acPlSetVdr.GetPlotStyleSheetList();
                            //设置打印样式表
                            if (comboBoxStyleSheet.SelectedItem.ToString() == "无")
                            {
                                acPlSetVdr.SetCurrentStyleSheet(acPlSet, "acad.ctb");
                            }

                            else
                            {
                                acPlSetVdr.SetCurrentStyleSheet(acPlSet, comboBoxStyleSheet.SelectedItem.ToString());
                            }

                            //选择方向
                            if (radioButtonHorizontal.Checked)
                            {
                                //横向
                                acPlSetVdr.SetPlotConfigurationName(acPlSet, "DWG To PDF.pc3", MediaName);
                                acPlSetVdr.SetPlotRotation(acPlSet, PlotRotation.Degrees090);
                            }

                            //竖向
                            if (radioButtonVertical.Checked)
                            {
                                acPlSetVdr.SetPlotConfigurationName(acPlSet, "DWG To PDF.pc3", MediaName);//获取打印图纸尺寸ComboxMedia
                                acPlSetVdr.SetPlotRotation(acPlSet, PlotRotation.Degrees000);
                            }
                            PlotProgressDialog acPlProgDlg = new PlotProgressDialog(false, resultObjectIds.Count, true);
                            string             imagename   = "";
                            string[]           files       = new string[] { };
                            List <string>      listfile    = new List <string>();
                            foreach (var frame in resultObjectIds)
                            {
                                if (!Directory.Exists(directory))
                                {
                                    Directory.CreateDirectory(directory);
                                }
                                flag++;

                                Entity ent = acTrans.GetObject(frame, OpenMode.ForRead) as Entity;

                                imagename = string.Format("{0}-{1}.pdf", frame, flag);
                                //imagelist.Add(directory + imagename);
                                listfile.Add(directory + imagename);


                                //设置是否使用打印样式
                                acPlSet.ShowPlotStyles = true;
                                //设置打印区域
                                Extents3d extents3d = ent.GeometricExtents;

                                Extents2d E2d = new Extents2d(extents3d.MinPoint.X, extents3d.MinPoint.Y, extents3d.MaxPoint.X, extents3d.MaxPoint.Y);
                                acPlSetVdr.SetPlotWindowArea(acPlSet, E2d);
                                acPlSetVdr.SetPlotType(acPlSet, Autodesk.AutoCAD.DatabaseServices.PlotType.Window);
                                //重载和保存打印信息
                                acPlInfo.OverrideSettings = acPlSet;
                                //验证打印信息设置,看是否有误
                                PlotInfoValidator acPlInfoVdr = new PlotInfoValidator();
                                acPlInfoVdr.MediaMatchingPolicy = MatchingPolicy.MatchEnabled;
                                acPlInfoVdr.Validate(acPlInfo);

                                while (PlotFactory.ProcessPlotState != ProcessPlotState.NotPlotting)
                                {
                                    continue;
                                }
                                #region BackUpCode

                                //保存App的原参数
                                short bgPlot = (short)Application.GetSystemVariable("BACKGROUNDPLOT");
                                //设定为前台打印,加快打印速度
                                Application.SetSystemVariable("BACKGROUNDPLOT", 0);
                                PlotEngine acPlEng1 = PlotFactory.CreatePublishEngine();
                                // acPlProgDlg.set_PlotMsgString(PlotMessageIndex.DialogTitle, "图片输出");
                                // acPlProgDlg.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "取消输出");
                                //acPlProgDlg.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "输出进度");
                                acPlProgDlg.LowerPlotProgressRange = 0;
                                acPlProgDlg.UpperPlotProgressRange = 100;
                                acPlProgDlg.PlotProgressPos        = 0;
                                acPlProgDlg.OnBeginPlot();
                                acPlProgDlg.IsVisible = true;
                                acPlEng1.BeginPlot(acPlProgDlg, null);
                                acPlEng1.BeginDocument(acPlInfo, "", null, 1, true, directory + imagename);
                                //  acPlProgDlg.set_PlotMsgString(PlotMessageIndex.Status, string.Format("正在输出文件"));
                                acPlProgDlg.OnBeginSheet();
                                acPlProgDlg.LowerSheetProgressRange = 0;
                                acPlProgDlg.UpperSheetProgressRange = 100;
                                acPlProgDlg.SheetProgressPos        = 0;
                                PlotPageInfo acPlPageInfo = new PlotPageInfo();
                                acPlEng1.BeginPage(acPlPageInfo, acPlInfo, true, null);
                                acPlEng1.BeginGenerateGraphics(null);
                                acPlEng1.EndGenerateGraphics(null);
                                acPlEng1.EndPage(null);
                                acPlProgDlg.SheetProgressPos = 100;
                                acPlProgDlg.OnEndSheet();
                                acPlEng1.EndDocument(null);
                                acPlProgDlg.PlotProgressPos = 100;
                                acPlProgDlg.OnEndPlot();
                                acPlEng1.EndPlot(null);
                                acPlEng1.Dispose();
                                acPlEng1.Destroy();
                                Application.SetSystemVariable("BACKGROUNDPLOT", bgPlot);

                                #endregion
                            }


                            files = listfile.ToArray();
                            PlotConfig config = PlotConfigManager.CurrentConfig;
                            //获取去除扩展名后的文件名(不含路径)
                            string fileName = SymbolUtilityServices.GetSymbolNameFromPathName(acDoc.Name, "dwg");
                            //定义保存文件对话框
                            PromptSaveFileOptions opt = new PromptSaveFileOptions("文件名")
                            {
                                //保存文件对话框的文件扩展名列表
                                Filter           = "*" + config.DefaultFileExtension + "|*" + config.DefaultFileExtension,
                                DialogCaption    = "浏览打印文件",                            //保存文件对话框的标题
                                InitialDirectory = @"D:\",                              //缺省保存目录
                                InitialFileName  = fileName + "-" + acLayout.LayoutName //缺省保存文件名
                            };
                            //根据保存对话框中用户的选择,获取保存文件名
                            PromptFileNameResult result = ed.GetFileNameForSave(opt);
                            if (result.Status != PromptStatus.OK)
                            {
                                return;
                            }
                            fileName = result.StringResult;

                            //string fileName = @"D:\输出.pdf";
                            PdfDocumentBase docx = PdfDocument.MergeFiles(files);
                            docx.Save(fileName, FileFormat.PDF);
                            System.Diagnostics.Process.Start(fileName);



                            //保存App的原参数
                            short bgPlot1 = (short)Application.GetSystemVariable("BACKGROUNDPLOT");
                            //设定为前台打印,加快打印速度
                            Application.SetSystemVariable("BACKGROUNDPLOT", 0);
                            PlotEngine acPlEng = PlotFactory.CreatePublishEngine();
                            acPlProgDlg.set_PlotMsgString(PlotMessageIndex.DialogTitle, "图片输出");
                            acPlProgDlg.set_PlotMsgString(PlotMessageIndex.CancelSheetButtonMessage, "取消输出");
                            acPlProgDlg.set_PlotMsgString(PlotMessageIndex.SheetProgressCaption, "输出进度");
                            acPlProgDlg.LowerPlotProgressRange = 0;
                            acPlProgDlg.UpperPlotProgressRange = 100;
                            acPlProgDlg.PlotProgressPos        = 0;
                            acPlProgDlg.OnBeginPlot();
                            acPlProgDlg.IsVisible = true;
                            acPlEng.BeginPlot(acPlProgDlg, null);
                            acPlEng.BeginDocument(acPlInfo, "", null, 1, true, directory + imagename);
                            acPlProgDlg.set_PlotMsgString(PlotMessageIndex.Status, string.Format("正在输出文件"));
                            acPlProgDlg.OnBeginSheet();
                            acPlProgDlg.LowerSheetProgressRange = 0;
                            acPlProgDlg.UpperSheetProgressRange = 100;
                            acPlProgDlg.SheetProgressPos        = 0;
                            PlotPageInfo acPlPageInfo1 = new PlotPageInfo();
                            acPlEng.BeginPage(acPlPageInfo1, acPlInfo, true, null);
                            acPlEng.BeginGenerateGraphics(null);
                            acPlEng.EndGenerateGraphics(null);
                            acPlEng.EndPage(null);
                            acPlProgDlg.SheetProgressPos = 100;
                            acPlProgDlg.OnEndSheet();
                            acPlEng.EndDocument(null);
                            acPlProgDlg.PlotProgressPos = 100;
                            acPlProgDlg.OnEndPlot();
                            acPlEng.EndPlot(null);
                            acPlEng.Dispose();
                            acPlEng.Destroy();
                            Application.SetSystemVariable("BACKGROUNDPLOT", bgPlot1);

                            acPlProgDlg.Dispose();
                            acPlProgDlg.Destroy();

                            for (int i = 0; i < files.Length; i++)
                            {
                                File.Delete(files[i]);
                            }
                        }
                        while (PlotFactory.ProcessPlotState != ProcessPlotState.NotPlotting)
                        {
                            continue;
                        }
                        //MessageBox.Show("打印完成!");
                    }
                }
                else
                {
                    ed.WriteMessage("\n另一个打印进程正在进行中.");
                }
            }



            catch (System.Exception)
            {
                throw;
            }
        }
Example #18
0
        public static void testForUnionPlines()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Editor   ed  = doc.Editor;
            Database db  = doc.Database;
            // get argument to choose boolean operation mode
            PromptKeywordOptions pko = new PromptKeywordOptions("\nChoose boolean operation mode " + "[Union/Subtract]: ", "Union Subtract");

            // The default depends on our current settings
            pko.Keywords.Default = "Union";
            PromptResult pkr = ed.GetKeywords(pko);

            if (pkr.Status != PromptStatus.OK)
            {
                return;
            }
            string choice = pkr.StringResult;

            bool            doUnion  = choice == "Union" ? true : false;
            List <Region>   regLst   = new List <Region>();
            List <Polyline> delPline = new List <Polyline>();

            using (DocumentLock doclock = doc.LockDocument())
            {
                //start a transaction
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    TypedValue[] tvs = new TypedValue[3]
                    {
                        new TypedValue(0, "lwpolyline"),
                        new TypedValue(-4, "&"),
                        new TypedValue(70, 1)
                    };
                    SelectionFilter        filter = new SelectionFilter(tvs);
                    PromptSelectionOptions pso    = new PromptSelectionOptions();
                    pso.MessageForRemoval = "\nSelect closed polylines only: ";
                    pso.MessageForAdding  = "\nSelect closed polylines: ";
                    PromptSelectionResult result = ed.GetSelection(filter);
                    if (result.Status != PromptStatus.OK)
                    {
                        return;
                    }

                    try
                    {
                        SelectionSet     sset    = result.Value;
                        ObjectId[]       ids     = sset.GetObjectIds();
                        BlockTableRecord btr     = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite, false);
                        Region           objreg1 = new Region();

                        for (int n = 0; n < ids.Count(); n++)
                        {
                            DBObject obj    = tr.GetObject(ids[n], OpenMode.ForRead) as DBObject;
                            Polyline pline1 = obj as Polyline;
                            if (pline1 == null)
                            {
                                return;
                            }
                            // Add the polyline to the List to rerase them all at the end of execution
                            delPline.Add(pline1);
                            // Add the polyline to the array
                            DBObjectCollection objArray1 = new DBObjectCollection();
                            objArray1.Add(pline1);
                            // create the 1 st region
                            DBObjectCollection objRegions1 = new DBObjectCollection();
                            objRegions1 = Region.CreateFromCurves(objArray1);
                            objreg1     = objRegions1[0] as Region;
                            btr.AppendEntity(objreg1);

                            tr.AddNewlyCreatedDBObject(objreg1, true);

                            objreg1.ColorIndex = 1;//optional
                            // add the region to the List<Region> for the future work
                            regLst.Add(objreg1);
                        }
                        //ed.WriteMessage("\nCount regions:\t{0}\n", regLst.Count);//just for the debug

                        // sort regions by areas
                        Region[] items = regLst.ToArray();
                        Array.Sort(items, (Region x, Region y) => y.Area.CompareTo(x.Area));
                        // get the biggest region first
                        Region mainReg = items[0];
                        // ed.WriteMessage("\nMain region area:\t{0:f3}\n", items[0].Area);//just for the debug
                        if (!mainReg.IsWriteEnabled)
                        {
                            mainReg.UpgradeOpen();
                        }
                        if (items.Length == 2)
                        {
                            if (!doUnion)
                            {
                                mainReg.BooleanOperation(BooleanOperationType.BoolSubtract, (Region)items[1]);
                            }
                            else
                            {
                                mainReg.BooleanOperation(BooleanOperationType.BoolUnite, (Region)items[1]);
                            }
                        }
                        else
                        {
                            // starting iteration from the second region
                            int i = 1;
                            do
                            {
                                Region reg1 = items[i]; Region reg2 = items[i + 1];

                                if ((reg1 == null) || (reg2 == null))
                                {
                                    break;
                                }

                                else
                                {
                                    // subtract region 1 from region 2
                                    if (reg1.Area > reg2.Area)
                                    {
                                        // subtract the smaller region from the larger one
                                        //
                                        reg1.BooleanOperation(BooleanOperationType.BoolUnite, reg2);
                                        if (!doUnion)
                                        {
                                            mainReg.BooleanOperation(BooleanOperationType.BoolSubtract, reg1);
                                        }
                                        else
                                        {
                                            mainReg.BooleanOperation(BooleanOperationType.BoolUnite, reg1);
                                        }
                                    }

                                    else
                                    {
                                        // subtract the smaller region from the larger one

                                        reg2.BooleanOperation(BooleanOperationType.BoolUnite, reg1);
                                        if (!doUnion)
                                        {
                                            mainReg.BooleanOperation(BooleanOperationType.BoolSubtract, reg2);
                                        }
                                        else
                                        {
                                            mainReg.BooleanOperation(BooleanOperationType.BoolUnite, reg2);
                                        }
                                    }
                                }
                                // increase counter
                                i++;
                            } while (i < items.Length - 1);
                        }
                        mainReg.ColorIndex = 1;// put dummy color for region

                        // erase polylines
                        foreach (Polyline poly in delPline)
                        {
                            if (poly != null)
                            {
                                if (!poly.IsWriteEnabled)
                                {
                                    poly.UpgradeOpen();
                                }
                                poly.Erase();
                                if (!poly.IsDisposed)
                                {
                                    poly.Dispose();
                                }
                            }
                        }

                        //  ---    explode region and create polyline from exploded entities   ---   //

                        DBObjectCollection regexpl = new DBObjectCollection();
                        mainReg.Explode(regexpl);

                        List <ObjectId> exids = new List <ObjectId>();

                        // gather selected object into the List<ObjectId>
                        if (regexpl.Count > 0)
                        {
                            foreach (DBObject obj in regexpl)
                            {
                                Entity ent = obj as Entity;
                                if (ent != null)
                                {
                                    ObjectId eid = btr.AppendEntity(ent);
                                    tr.AddNewlyCreatedDBObject(ent, true);

                                    exids.Add(eid);
                                }
                            }
                        }
                        // define AcadDocument as object
                        object     ActiveDocument = doc.GetAcadDocument();
                        ObjectId[] entids         = new ObjectId[] { };
                        Array.Resize(ref entids, exids.Count);
                        // convert List<ObjectId> to array of ObjectID
                        exids.CopyTo(entids, 0);

                        ed.Regen();
                        // create a new selection set and exploded items
                        SelectionSet newset = SelectionSet.FromObjectIds(entids);

                        ed.SetImpliedSelection(newset.GetObjectIds());

                        PromptSelectionResult pfres = ed.SelectImplied();
                        // execute Sendcommand synchronously
                        ActiveDocument.GetType().InvokeMember(
                            "SendCommand", System.Reflection.BindingFlags.InvokeMethod, null, ActiveDocument,
                            new object[] { "select\n" });
                        // execute Sendcommand synchronously
                        string cmd = "_pedit _M _P" + " " + "" + " " + "_J" + " " + "" + " " + "" + "\n";
                        ActiveDocument.GetType().InvokeMember(
                            "SendCommand", System.Reflection.BindingFlags.InvokeMethod, null, ActiveDocument,
                            new object[] { cmd });
                        // rerase region if this is do not erased (relative to current DELOBJ variable value)
                        if (mainReg != null)
                        {
                            if (!mainReg.IsWriteEnabled)
                            {
                                mainReg.UpgradeOpen();
                            }
                        }
                        mainReg.Erase();

                        tr.Commit();
                    }

                    catch (Autodesk.AutoCAD.Runtime.Exception ex)
                    {
                        ed.WriteMessage("\nAutoCAD exception:\n" + ex.Message + "\n" + ex.StackTrace);
                    }
                    finally
                    {
                        ed.WriteMessage("\n{0}", new Autodesk.AutoCAD.Runtime.ErrorStatus().ToString());//optional, might be removed
                    }
                }
            }
        }
Example #19
0
        internal void AutoDeleteLayer(string file)
        {
            try
            {
                // 获取当前文档和数据库
                Document         acDoc   = Application.DocumentManager.Open(file, false);
                Database         acCurDb = acDoc.Database;
                Editor           ed      = acDoc.Editor;
                List <ObjectId>  layers  = new List <ObjectId>();
                LayerTableRecord layer;

                using (DocumentLock acLckDoc = acDoc.LockDocument())
                {
                    using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
                    {
                        foreach (ObjectId layerId in MethodCommand.LayersToList(acCurDb))
                        {
                            try
                            {
                                layer = acTrans.GetObject(layerId, OpenMode.ForWrite) as LayerTableRecord;

                                TypedValue[] filList = new TypedValue[1] {
                                    new TypedValue((int)DxfCode.LayerName, layer.Name)
                                };
                                SelectionFilter sfilter = new SelectionFilter(filList);

                                PromptSelectionResult result = acDoc.Editor.SelectAll(sfilter);
                                if (result.Status == PromptStatus.OK)
                                {
                                    SelectionSet acSSet = result.Value;
                                    foreach (ObjectId id in acSSet.GetObjectIds())
                                    {
                                        try
                                        {
                                            Entity hatchobj = acTrans.GetObject(id, OpenMode.ForWrite) as Entity;
                                            hatchobj.Erase(true);//删除
                                        }
                                        catch (Exception e)
                                        {
                                            System.Windows.Forms.MessageBox.Show(e.Message);
                                        }
                                    }
                                }
                                // 删除图层
                                if (layer.Name != "0")
                                {
                                    layer.Erase();
                                }
                            }
                            catch (Exception e)
                            {
                                System.Windows.Forms.MessageBox.Show(e.Message);
                            }
                        }

                        acTrans.Commit();
                    }
                }
            }
            catch (Exception e)
            {
                System.Windows.Forms.MessageBox.Show(e.Message);
            }
        }
        public void GetIntersections()
        {
            Database db = HostApplicationServices.WorkingDatabase;

            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Editor ed = doc.Editor;

            Transaction tr = db.TransactionManager.StartTransaction();

            using (tr)
            {
                try
                {
                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);

                    PromptEntityOptions 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;
                    }

                    DBObject ent = (DBObject)tr.GetObject(res.ObjectId, OpenMode.ForRead);

                    if (ent == null)
                    {
                        return;
                    }

                    //Polyline poly = (Polyline)ent as Polyline;
                    Curve curv = ent as Curve;

                    DBObjectCollection pcurves = new DBObjectCollection();

                    curv.Explode(pcurves);
                    TypedValue[] values = new TypedValue[]
                    {
                        new TypedValue(0, "lwpolyline")
                        //might be added layer name to select curve:
                        //, new TypedValue(8, "mylayer")
                    };
                    SelectionFilter filter = new SelectionFilter(values);

                    Point3dCollection fence = new Point3dCollection();

                    double leng = curv.GetDistanceAtParameter(curv.EndParam) - curv.GetDistanceAtParameter(curv.StartParam);
                    // number of divisions along polyline to create fence selection
                    double step = leng / 256;// set number of steps to your suit

                    int num = Convert.ToInt32(leng / step);

                    int i = 0;

                    for (i = 0; i < num; i++)
                    {
                        Point3d pp = curv.GetPointAtDist(step * i);

                        fence.Add(curv.GetClosestPointTo(pp, false));
                    }

                    PromptSelectionResult selres = ed.SelectFence(fence, filter);

                    if (selres.Status != PromptStatus.OK)
                    {
                        return;
                    }
                    Point3dCollection intpts = new Point3dCollection();

                    DBObjectCollection qcurves = new DBObjectCollection();

                    foreach (SelectedObject selobj in selres.Value)
                    {
                        DBObject obj = tr.GetObject(selobj.ObjectId, OpenMode.ForRead, false) as DBObject;
                        if (selobj.ObjectId != curv.ObjectId)
                        {
                            DBObjectCollection icurves = new DBObjectCollection();
                            Curve icurv = obj as Curve;
                            icurv.Explode(icurves);
                            foreach (DBObject dbo in icurves)
                            {
                                if (!qcurves.Contains(dbo))
                                {
                                    qcurves.Add(dbo);
                                }
                            }
                        }
                    }
                    ed.WriteMessage("\n{0}", qcurves.Count);



                    int j = 0;
                    Point3dCollection polypts = new Point3dCollection();

                    for (i = 0; i < pcurves.Count; ++i)
                    {
                        for (j = 0; j < qcurves.Count; ++j)
                        {
                            Curve curve1 = pcurves[i] as Curve;

                            Curve curve2 = qcurves[j] as Curve;

                            Point3dCollection pts = new Point3dCollection();

                            curve1.IntersectWith(curve2, Intersect.OnBothOperands, pts, IntPtr.Zero, IntPtr.Zero);

                            foreach (Point3d pt in pts)
                            {
                                if (!polypts.Contains(pt))
                                {
                                    polypts.Add(pt);
                                }
                            }
                        }
                    }

                    Autodesk.AutoCAD.ApplicationServices.Core.Application.SetSystemVariable("osmode", 0);// optional
                    // for debug only
                    Autodesk.AutoCAD.ApplicationServices.Core.Application.ShowAlertDialog(string.Format("\nNumber of Intersections: {0}", polypts.Count));
                    // test for visulization only
                    foreach (Point3d inspt in polypts)
                    {
                        Circle circ = new Circle(inspt, Vector3d.ZAxis, 10 * db.Dimtxt)
                        {
                            ColorIndex = 1
                        };
                        btr.AppendEntity(circ);
                        tr.AddNewlyCreatedDBObject(circ, true);
                    }
                    tr.Commit();
                }
                catch (System.Exception ex)
                {
                    ed.WriteMessage("\n{0}\n{1}", ex.Message, ex.StackTrace);
                }
            }
        }
Example #21
0
        public static void ImportAsXref()
        {
            Document       acDoc   = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            bool           Aborted = false;
            SaveFileDialog sfd;
            ObjectId       SurveyTextStyle;

            //Make all the drawing changes
            using (DocumentLock dl = acDoc.LockDocument())
            {
                using (Transaction tr = acDoc.Database.TransactionManager.StartTransaction())
                {
                    //Remove all sheets
                    ObjectId newLayout = LayoutManager.Current.CreateLayout("Paper");
                    LayoutManager.Current.SetCurrentLayoutId(newLayout);
                    DBDictionary lays = tr.GetObject(acDoc.Database.LayoutDictionaryId, OpenMode.ForWrite) as DBDictionary;
                    foreach (DBDictionaryEntry item in lays)
                    {
                        string layoutName = item.Key;
                        if (layoutName != "Model" && layoutName != "Paper")
                        {
                            LayoutManager.Current.DeleteLayout(layoutName); // Delete layout.
                        }
                    }

                    //Get or create the survey text style
                    TextStyleTable tst = tr.GetObject(acDoc.Database.TextStyleTableId, OpenMode.ForRead) as TextStyleTable;
                    if (!tst.Has("JPP_Survey"))
                    {
                        tst.UpgradeOpen();
                        TextStyleTableRecord tstr = new TextStyleTableRecord();
                        tstr.FileName = "romans.shx";
                        tstr.Name     = "JPP_Survey";
                        tst.Add(tstr);
                        tr.AddNewlyCreatedDBObject(tstr, true);
                    }

                    SurveyTextStyle = tst["JPP_Survey"];

                    //Get all model space drawing objects
                    TypedValue[] tv = new TypedValue[1];
                    tv.SetValue(new TypedValue(67, 0), 0);
                    SelectionFilter       sf  = new SelectionFilter(tv);
                    PromptSelectionResult psr = acDoc.Editor.SelectAll(sf);

                    //Lengthy operations so show progress bar
                    ProgressMeter pm = new ProgressMeter();

                    Byte         alpha = (Byte)(255 * (1));
                    Transparency trans = new Transparency(alpha);

                    //Iterate over all layer and set them to color 8, 0 transparency and continuous linetype
                    // Open the Layer table for read
                    LayerTable acLyrTbl   = tr.GetObject(acDoc.Database.LayerTableId, OpenMode.ForRead) as LayerTable;
                    int        layerCount = 0;
                    foreach (ObjectId id in acLyrTbl)
                    {
                        layerCount++;
                    }

                    pm = new ProgressMeter();
                    pm.Start("Updating layers...");
                    pm.SetLimit(layerCount);
                    foreach (ObjectId id in acLyrTbl)
                    {
                        LayerTableRecord ltr = tr.GetObject(id, OpenMode.ForWrite) as LayerTableRecord;
                        ltr.IsLocked         = false;
                        ltr.Color            = Autodesk.AutoCAD.Colors.Color.FromColorIndex(Autodesk.AutoCAD.Colors.ColorMethod.ByColor, 8);
                        ltr.LinetypeObjectId = acDoc.Database.ContinuousLinetype;
                        ltr.LineWeight       = acDoc.Database.Celweight;
                        ltr.Transparency     = trans;

                        pm.MeterProgress();
                        System.Windows.Forms.Application.DoEvents();
                    }
                    pm.Stop();

                    pm.Start("Updating objects...");
                    pm.SetLimit(psr.Value.Count);

                    foreach (SelectedObject so in psr.Value)
                    {
                        //For each object set its color, transparency, lineweight and linetype to ByLayer
                        Entity obj = tr.GetObject(so.ObjectId, OpenMode.ForWrite) as Entity;
                        obj.ColorIndex = 256;
                        obj.LinetypeId = acDoc.Database.Celtype;
                        obj.LineWeight = acDoc.Database.Celweight;

                        pm.MeterProgress();
                        System.Windows.Forms.Application.DoEvents();

                        if (obj is Polyline)
                        {
                            Polyline pl = obj as Polyline;
                            pl.Elevation = 0;
                        }
                        if (obj is Polyline2d)
                        {
                            Polyline2d pl = obj as Polyline2d;
                            pl.Elevation = 0;
                        }
                        if (obj is Polyline3d)
                        {
                            Polyline3d pl3d = obj as Polyline3d;
                            foreach (ObjectId id in pl3d)
                            {
                                PolylineVertex3d plv3d = tr.GetObject(id, OpenMode.ForWrite) as PolylineVertex3d;
                                Point3d          p3d   = plv3d.Position;
                                plv3d.Position = new Point3d(p3d.X, p3d.Y, 0);
                            }
                        }

                        //Change all text to Romans
                        if (obj is DBText)
                        {
                            DBText text = obj as DBText;
                            text.Position    = new Point3d(text.Position.X, text.Position.Y, 0);
                            text.Height      = 0.4;
                            text.TextStyleId = SurveyTextStyle;
                        }
                        if (obj is MText)
                        {
                            MText text = obj as MText;
                            text.Location    = new Point3d(text.Location.X, text.Location.Y, 0);
                            text.Height      = 0.4;
                            text.TextStyleId = SurveyTextStyle;
                        }
                    }
                    pm.Stop();

                    //Operate over all blocks
                    BlockTable blkTable   = (BlockTable)tr.GetObject(acDoc.Database.BlockTableId, OpenMode.ForRead);
                    int        blockCount = 0;
                    foreach (ObjectId id in blkTable)
                    {
                        blockCount++;
                    }

                    pm = new ProgressMeter();
                    pm.Start("Updating blocks...");
                    pm.SetLimit(blockCount);
                    foreach (ObjectId id in blkTable)
                    {
                        BlockTableRecord btRecord = (BlockTableRecord)tr.GetObject(id, OpenMode.ForRead);
                        if (!btRecord.IsLayout)
                        {
                            foreach (ObjectId childId in btRecord)
                            {
                                //For each object set its color, transparency, lineweight and linetype to ByLayer
                                Entity obj = tr.GetObject(childId, OpenMode.ForWrite) as Entity;
                                obj.ColorIndex = 256;
                                obj.LinetypeId = acDoc.Database.Celtype;
                                obj.LineWeight = acDoc.Database.Celweight;


                                //Adjust Z values
                            }
                        }
                        pm.MeterProgress();
                        System.Windows.Forms.Application.DoEvents();
                    }

                    pm.Stop();

                    //Run the cleanup commands
                    Core.Utilities.Purge();

                    acDoc.Database.Audit(true, false);

                    //Prompt for the save location
                    sfd        = new SaveFileDialog();
                    sfd.Filter = "Drawing File|*.dwg";
                    sfd.Title  = "Save drawing as";
                    sfd.ShowDialog();
                    if (sfd.FileName != "")
                    {
                        tr.Commit();
                        Aborted = false;
                    }
                    else
                    {
                        tr.Abort();
                        Aborted = true;
                    }
                }
            }

            if (!Aborted)
            {
                acDoc.Database.SaveAs(sfd.FileName, Autodesk.AutoCAD.DatabaseServices.DwgVersion.Current);

                //Close the original file as its no longer needed
                acDoc.CloseAndDiscard();
            }
        }
Example #22
0
        public void CreateBoundaries()
        {
            n = 0;

            Document adoc = Application.DocumentManager.MdiActiveDocument;

            if (adoc == null)
            {
                return;
            }

            Database db = adoc.Database;

            ed = adoc.Editor;

            Database dbTarget = null;

            Document adocTarget = null;

            SelectionSet ssToProcess = null;

            try
            {
                //TODO: Запуск только в пространстве модели

                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    //Запрос у пользователя выбора слоев, объекты в которых нужно подвергнуть обработке
                    //Подсветка объектов, подлежащих обработке (линии с глобальной шириной и штриховки)


                    SortedSet <string> selectedLayers = new SortedSet <string>();

                    while (true)
                    {
                        if (selectedLayers.Count > 0)
                        {
                            ed.WriteMessage("\nВыбраны слои " + String.Join(", ", selectedLayers));
                        }

                        PromptEntityOptions peo
                            = new PromptEntityOptions("\nУкажите объект для добавления слоя");
                        PromptEntityResult res = ed.GetEntity(peo);



                        //PromptSelectionOptions options = new PromptSelectionOptions();
                        //options.SingleOnly = true;
                        //options.MessageForAdding = "\nУкажите объекты для выбора слоев разметки";
                        //PromptSelectionResult res = ed.GetSelection(options);
                        if (res.Status == PromptStatus.OK)
                        {
                            ObjectId pickedId = res.ObjectId;
                            if (pickedId != null && pickedId != ObjectId.Null)
                            {
                                //Подсветить все объекты, которые подлежат обработке

                                //Добавить выбранный слой
                                Entity ent = tr.GetObject(pickedId, OpenMode.ForRead) as Entity;
                                selectedLayers.Add(ent.Layer);



                                //Фильтр для набора выбора
                                TypedValue[] tv = new TypedValue[] //{ new TypedValue(0, "POLYLINE,HATCH") };
                                {
                                    //new TypedValue(-4, "<AND"),

                                    new TypedValue(-4, "<OR"),
                                    new TypedValue(0, "HATCH"),    //Либо штриховка

                                    new TypedValue(-4, "<AND"),    //Либо полилиния, у которой есть глобальная ширина
                                    new TypedValue(0, "LWPOLYLINE,POLYLINE"),
                                    new TypedValue(-4, "!="),
                                    new TypedValue(40, 0),
                                    new TypedValue(-4, "AND>"),

                                    new TypedValue(-4, "OR>"),

                                    new TypedValue(8, String.Join(",", selectedLayers)),//В любом из выбранных слоев!

                                    //new TypedValue(-4, "AND>"),
                                };
                                SelectionFilter flt = new SelectionFilter(tv);

                                PromptSelectionResult res1 = ed.SelectAll(flt);
                                if (res1.Status == PromptStatus.OK)
                                {
                                    ssToProcess = res1.Value;
                                    //подсветить

                                    foreach (SelectedObject acSSObj in ssToProcess)
                                    {
                                        Entity entToHighlight = tr.GetObject(acSSObj.ObjectId, OpenMode.ForRead) as Entity;
                                        entToHighlight.Highlight();
                                    }
                                }

                                continue;
                            }
                        }
                        break;
                    }


                    if (ssToProcess != null && ssToProcess.Count > 0)
                    {
                        ObjectIdCollection idToExtract = new ObjectIdCollection();//выбранные объекты
                        foreach (SelectedObject acSSObj in ssToProcess)
                        {
                            idToExtract.Add(acSSObj.ObjectId);
                        }



                        //Создание новой базы данных для записи обработанных объектов и создания нового чертежа
                        dbTarget = new Database(true, false);
                        //Единицы измерения ВСЕГДА метры
                        dbTarget.Insunits = UnitsValue.Meters;
                        //Копирование объектов
                        db.Wblock(dbTarget, idToExtract, Point3d.Origin, DuplicateRecordCloning.Ignore);
                    }
                    tr.Commit();
                }



                if (dbTarget != null)
                {
                    ObjectIdCollection createdBtrs = new ObjectIdCollection();
                    using (Transaction trTarget = dbTarget.TransactionManager.StartTransaction())
                    {
                        continuousLtype = Utils.GetContinuousLinetype(dbTarget);
                        //Обработка объектов в новой базе данных
                        BlockTable btTarget
                            = trTarget.GetObject(dbTarget.BlockTableId, OpenMode.ForWrite) as BlockTable;
                        BlockTableRecord msTarget
                            = (BlockTableRecord)trTarget
                              .GetObject(btTarget[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                        foreach (ObjectId id in msTarget)
                        {
                            Entity   ent          = trTarget.GetObject(id, OpenMode.ForWrite) as Entity;
                            ObjectId createdBtrId = ObjectId.Null;
                            //Для полилинии имя нового блока должно быть равно имени типа линии + номер
                            //Для штриховки - "Штриховка" + номер
                            if (ent is Curve)
                            {
                                Curve curve = ent as Curve;
                                if (ent is Polyline2d)
                                {
                                    Polyline poly = new Polyline();
                                    poly.ConvertFrom(ent, false);
                                    curve = poly;
                                }

                                createdBtrId = ProcessEntity(curve as Polyline, btTarget);
                            }
                            else if (ent is Hatch)
                            {
                                createdBtrId = ProcessEntity(ent as Hatch, btTarget);
                            }

                            //Вставка нового вхождения блока
                            if (createdBtrId != ObjectId.Null)
                            {
                                createdBtrs.Add(createdBtrId);
                                //ЗДЕСЬ НЕ СОЗДАЕТ ВХОЖДЕНИЕ БЛОКА!
                                //BlockReference br = new BlockReference(Point3d.Origin, createdBtrId);
                                //msTarget.AppendEntity(br);
                                //trTarget.AddNewlyCreatedDBObject(br, true);
                            }


                            //Удаление исходного объекта
                            ent.Erase();
                        }



                        trTarget.Commit();
                    }

                    //Создание вхождений блоков
                    using (Transaction trTarget = dbTarget.TransactionManager.StartTransaction())
                    {
                        BlockTable btTarget
                            = trTarget.GetObject(dbTarget.BlockTableId, OpenMode.ForWrite) as BlockTable;
                        BlockTableRecord msTarget
                            = (BlockTableRecord)trTarget
                              .GetObject(btTarget[BlockTableRecord.ModelSpace], OpenMode.ForWrite);

                        foreach (ObjectId id in createdBtrs)
                        {
                            BlockReference br = new BlockReference(Point3d.Origin, id);
                            msTarget.AppendEntity(br);
                            trTarget.AddNewlyCreatedDBObject(br, true);
                        }
                    }


                    //TODO: Учесть возможные ошибки из-за отсутствия прав
                    //Создание нового чертежа и открытие его
                    //string targetDocFullPath = null;
                    //int n = 0;
                    //do
                    //{
                    //    targetDocFullPath = Path.Combine(Path.GetDirectoryName(adoc.Name), "RoadMarkingBoundaries" + n + ".dwg");
                    //    n++;
                    //} while (File.Exists(targetDocFullPath));

                    string targetDocFullPath
                        = Common.Utils.GetNonExistentFileName(Path.GetDirectoryName(adoc.Name), "RoadMarkingBoundaries", "dwg");
                    dbTarget.SaveAs(targetDocFullPath, DwgVersion.Current);
                    try
                    {
                        //если текущий документ никуда не сохранен, то не сможет открыть
                        adocTarget = Application.DocumentManager.Open(targetDocFullPath, false);
                    }
                    catch { }
                }
            }
            catch (System.Exception ex)
            {
                //Utils.ErrorToCommandLine(ed, "Ошибка при создании контуров разметки", ex);
                CommonException(ex, "Ошибка при создании контуров разметки");
            }
            finally
            {
                //Сброс подсветки!
                Unhighlight(ssToProcess, db);
            }
        }
Example #23
0
        private ErrorStatus selectPL()
        {
            Database db = HostApplicationServices.WorkingDatabase;

            Autodesk.AutoCAD.DatabaseServices.TransactionManager myTm = db.TransactionManager;
            Transaction myT = db.TransactionManager.StartTransaction();
            ErrorStatus es  = ErrorStatus.KeyNotFound;

            //Polylinien auswählen
            PromptSelectionOptions prSelOpt = new PromptSelectionOptions();

            //Filter
            TypedValue[] values = new TypedValue[] {
                new TypedValue((int)DxfCode.Operator, "<or"),
                new TypedValue((int)DxfCode.Start, "LWPolyline"),
                new TypedValue((int)DxfCode.Start, "Polyline"),
                new TypedValue((int)DxfCode.Start, "Line"),
                new TypedValue((int)DxfCode.Operator, "or>")
            };
            SelectionFilter selFilter = new SelectionFilter(values);

            PromptSelectionResult resSel = m_ed.GetSelection(prSelOpt, selFilter);

            if (resSel.Status == PromptStatus.OK)
            {
                //Polylinien nach Art in Listen schreiben
                SelectionSet ssRes = resSel.Value;

                //PolylinienLW iterativ bearbeiten
                ObjectId[] objID = ssRes.GetObjectIds();

                for (int i = 0; i < objID.Length; i++)
                {
                    DBObject dbObj  = myT.GetObject(objID[i], OpenMode.ForRead);
                    string   objTyp = dbObj.GetType().ToString();
                    objTyp = objTyp.Substring(objTyp.LastIndexOf('.') + 1);

                    switch (objTyp)
                    {
                    case "Line":
                        m_LineCollection.Add(objID[i], (Line)myT.GetObject(objID[i], OpenMode.ForRead));

                        break;

                    case "Polyline":
                        m_PolylineCollection.Add(objID[i], (Polyline)myT.GetObject(objID[i], OpenMode.ForRead));

                        break;

                    case "Polyline2d":
                        m_Polyline2dCollection.Add(objID[i], (Polyline2d)myT.GetObject(objID[i], OpenMode.ForRead));

                        break;
                    }

                    es = ErrorStatus.OK;
                }
            }

            myT.Commit();

            return(es);
        }
Example #24
0
        public void testJigMove()
        {
            Database db = HostApplicationServices.WorkingDatabase;
            Editor   ed = Application.DocumentManager.MdiActiveDocument.Editor;
            // 普通的选择集交互操作.
            PromptSelectionOptions opt = new PromptSelectionOptions();

            opt.MessageForAdding = "选择对象";
            opt.AllowDuplicates  = true;
            PromptSelectionResult res = ed.GetSelection(opt);

            if (res.Status != PromptStatus.OK)
            {
                return;
            }
            SelectionSet sSet = res.Value;

            ids = sSet.GetObjectIds();

            Entity[] oldEnt = new Entity[ids.Length];

            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                entCopy = new Entity[ids.Length];
                for (int i = 0; i <= ids.Length - 1; i++)
                {
                    oldEnt[i] = (Entity)trans.GetObject(ids[i], OpenMode.ForWrite);
                    // 将源对象设置为高亮状态.
                    oldEnt[i].Highlight();
                    // 复制.
                    entCopy[i] = (Entity)oldEnt[i].Clone();
                }

                // 得到移动的源点-----------------------------------------------
                PromptPointOptions optPoint = new PromptPointOptions("\n请输入基点<0,0,0>");
                optPoint.AllowNone = true;
                PromptPointResult resPoint = ed.GetPoint(optPoint);
                if (resPoint.Status != PromptStatus.Cancel)
                {
                    if (resPoint.Status == PromptStatus.None)
                    {
                        sourcePt = new Point3d(0, 0, 0);
                    }
                    else
                    {
                        sourcePt = resPoint.Value;
                    }
                }

                // 设置目标点和拖拽临时点的初值.
                targetPt = sourcePt;
                curPt    = targetPt;

                // 开始拖拽.
                PromptResult jigRes = ed.Drag(this);
                if (jigRes.Status == PromptStatus.OK)
                {
                    BlockTable       bt  = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);
                    BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                    for (int i = 0; i <= ids.Length - 1; i++)
                    {
                        btr.AppendEntity(entCopy[i]);
                        trans.AddNewlyCreatedDBObject(entCopy[i], true);
                    }
                    // 删除源对象.
                    for (int i = 0; i <= ids.Length - 1; i++)
                    {
                        oldEnt[i].Erase();
                    }
                }
                else
                {
                    // 取消源对象的高亮状态.
                    for (int i = 0; i <= ids.Length - 1; i++)
                    {
                        oldEnt[i].Unhighlight();
                    }
                }
                trans.Commit();
            }
        }
Example #25
0
        CollectEvent(object sender, CollectorEventArgs e)
        {
            // cast the sender object to the SnoopCollector we are expecting
            Collector snoopCollector = sender as Collector;

            if (snoopCollector == null)
            {
                Debug.Assert(false);    // why did someone else send us the message?
                return;
            }

            // see if it is a type we are responsible for
            Editor editor = e.ObjToSnoop as Editor;

            if (editor != null)
            {
                Stream(snoopCollector.Data(), editor);
                return;
            }

            PromptOptions promptOpts = e.ObjToSnoop as PromptOptions;

            if (promptOpts != null)
            {
                Stream(snoopCollector.Data(), promptOpts);
                return;
            }

            PromptStringOptionsEventArgs promptStringArgs = e.ObjToSnoop as PromptStringOptionsEventArgs;

            if (promptStringArgs != null)
            {
                Stream(snoopCollector.Data(), promptStringArgs);
                return;
            }

            PromptSelectionOptionsEventArgs promptSelectionArgs = e.ObjToSnoop as PromptSelectionOptionsEventArgs;

            if (promptSelectionArgs != null)
            {
                Stream(snoopCollector.Data(), promptSelectionArgs);
                return;
            }

            PromptSelectionOptions promptSelectionOpts = e.ObjToSnoop as PromptSelectionOptions;

            if (promptSelectionOpts != null)
            {
                Stream(snoopCollector.Data(), promptSelectionOpts);
                return;
            }

            PromptPointOptionsEventArgs promptPointArgs = e.ObjToSnoop as PromptPointOptionsEventArgs;

            if (promptPointArgs != null)
            {
                Stream(snoopCollector.Data(), promptPointArgs);
                return;
            }

            PromptNestedEntityResultEventArgs promptNestResultArgs = e.ObjToSnoop as PromptNestedEntityResultEventArgs;

            if (promptNestResultArgs != null)
            {
                Stream(snoopCollector.Data(), promptNestResultArgs);
                return;
            }

            PromptResult promptResult = e.ObjToSnoop as PromptResult;

            if (promptResult != null)
            {
                Stream(snoopCollector.Data(), promptResult);
                return;
            }

            PromptKeywordOptionsEventArgs promptKeywordArgs = e.ObjToSnoop as PromptKeywordOptionsEventArgs;

            if (promptKeywordArgs != null)
            {
                Stream(snoopCollector.Data(), promptKeywordArgs);
                return;
            }

            PromptIntegerOptionsEventArgs promptIntArgs = e.ObjToSnoop as PromptIntegerOptionsEventArgs;

            if (promptIntArgs != null)
            {
                Stream(snoopCollector.Data(), promptIntArgs);
                return;
            }

            PromptEntityOptionsEventArgs promptEntArgs = e.ObjToSnoop as PromptEntityOptionsEventArgs;

            if (promptEntArgs != null)
            {
                Stream(snoopCollector.Data(), promptEntArgs);
                return;
            }

            PromptDoubleOptionsEventArgs promptDoubleArgs = e.ObjToSnoop as PromptDoubleOptionsEventArgs;

            if (promptDoubleArgs != null)
            {
                Stream(snoopCollector.Data(), promptDoubleArgs);
                return;
            }

            PromptSelectionResult prSelRes = e.ObjToSnoop as PromptSelectionResult;

            if (prSelRes != null)
            {
                Stream(snoopCollector.Data(), prSelRes);
                return;
            }

            SelectionSet selSet = e.ObjToSnoop as SelectionSet;

            if (selSet != null)
            {
                Stream(snoopCollector.Data(), selSet);
                return;
            }

            SelectedObject selObj = e.ObjToSnoop as SelectedObject;

            if (selObj != null)
            {
                Stream(snoopCollector.Data(), selObj);
                return;
            }

            SelectedSubObject selSubObj = e.ObjToSnoop as SelectedSubObject;

            if (selSubObj != null)
            {
                Stream(snoopCollector.Data(), selSubObj);
                return;
            }

            SelectionDetails selDetails = e.ObjToSnoop as SelectionDetails;

            if (selDetails != null)
            {
                Stream(snoopCollector.Data(), selDetails);
                return;
            }

            SelectionRemovedEventArgs selRemovedArgs = e.ObjToSnoop as SelectionRemovedEventArgs;

            if (selRemovedArgs != null)
            {
                Stream(snoopCollector.Data(), selRemovedArgs);
                return;
            }

            SelectionAddedEventArgs selAddedArgs = e.ObjToSnoop as SelectionAddedEventArgs;

            if (selAddedArgs != null)
            {
                Stream(snoopCollector.Data(), selAddedArgs);
                return;
            }

            DraggingEndedEventArgs dragEndArgs = e.ObjToSnoop as DraggingEndedEventArgs;

            if (dragEndArgs != null)
            {
                Stream(snoopCollector.Data(), dragEndArgs);
                return;
            }

            InputPointContext inputPtCntxt = e.ObjToSnoop as InputPointContext;

            if (inputPtCntxt != null)
            {
                Stream(snoopCollector.Data(), inputPtCntxt);
                return;
            }

            Keyword keyword = e.ObjToSnoop as Keyword;

            if (keyword != null)
            {
                Stream(snoopCollector.Data(), keyword);
                return;
            }

            PointFilterEventArgs ptFilterEventArgs = e.ObjToSnoop as PointFilterEventArgs;

            if (ptFilterEventArgs != null)
            {
                Stream(snoopCollector.Data(), ptFilterEventArgs);
                return;
            }

            PointFilterResult ptFilterRes = e.ObjToSnoop as PointFilterResult;

            if (ptFilterRes != null)
            {
                Stream(snoopCollector.Data(), ptFilterRes);
                return;
            }

            PointMonitorEventArgs ptMonitorArgs = e.ObjToSnoop as PointMonitorEventArgs;

            if (ptMonitorArgs != null)
            {
                Stream(snoopCollector.Data(), ptMonitorArgs);
                return;
            }

            PromptAngleOptionsEventArgs promptAngleOptsArgs = e.ObjToSnoop as PromptAngleOptionsEventArgs;

            if (promptAngleOptsArgs != null)
            {
                Stream(snoopCollector.Data(), promptAngleOptsArgs);
                return;
            }

            PromptDistanceOptionsEventArgs promptDistanceOptsArgs = e.ObjToSnoop as PromptDistanceOptionsEventArgs;

            if (promptDistanceOptsArgs != null)
            {
                Stream(snoopCollector.Data(), promptDistanceOptsArgs);
                return;
            }

            PromptDoubleResultEventArgs promptDoubleResArgs = e.ObjToSnoop as PromptDoubleResultEventArgs;

            if (promptDoubleResArgs != null)
            {
                Stream(snoopCollector.Data(), promptDoubleResArgs);
                return;
            }

            PromptFileOptions promptFileOpts = e.ObjToSnoop as PromptFileOptions;

            if (promptFileOpts != null)
            {
                Stream(snoopCollector.Data(), promptFileOpts);
                return;
            }

            PromptForEntityEndingEventArgs promptForEntEndArgs = e.ObjToSnoop as PromptForEntityEndingEventArgs;

            if (promptForEntEndArgs != null)
            {
                Stream(snoopCollector.Data(), promptForEntEndArgs);
                return;
            }

            PromptForSelectionEndingEventArgs promptForSelEndArgs = e.ObjToSnoop as PromptForSelectionEndingEventArgs;

            if (promptForSelEndArgs != null)
            {
                Stream(snoopCollector.Data(), promptForSelEndArgs);
                return;
            }

            PromptNestedEntityOptions promptNestEntOpts = e.ObjToSnoop as PromptNestedEntityOptions;

            if (promptNestEntOpts != null)
            {
                Stream(snoopCollector.Data(), promptNestEntOpts);
                return;
            }

            PromptNestedEntityOptionsEventArgs promptNestEntOptsArgs = e.ObjToSnoop as PromptNestedEntityOptionsEventArgs;

            if (promptNestEntOptsArgs != null)
            {
                Stream(snoopCollector.Data(), promptNestEntOptsArgs);
                return;
            }

            PromptSelectionResultEventArgs promptSelResArgs = e.ObjToSnoop as PromptSelectionResultEventArgs;

            if (promptSelResArgs != null)
            {
                Stream(snoopCollector.Data(), promptSelResArgs);
                return;
            }

            // ValueTypes we have to treat a bit different
            if (e.ObjToSnoop is PickPointDescriptor)
            {
                Stream(snoopCollector.Data(), (PickPointDescriptor)e.ObjToSnoop);
                return;
            }
        }
Example #26
0
        public static List <FullSubentityPath> SelectEntity(SubentityType subentType, SelectionFilter selectionFilter, bool multiple)
        {
            var                    editor  = Application.DocumentManager.MdiActiveDocument.Editor;
            const string           selMode = "SELECTIONMODES";
            PromptSelectionOptions pso     = null;
            var                    oldVal  = Application.GetSystemVariable(selMode);

            if (DatabaseUtils.IsSubentity(subentType))
            {
                pso = new PromptSelectionOptions();
                switch (subentType)
                {
                case SubentityType.Face:
                    Application.SetSystemVariable(selMode, 2);
                    break;

                case SubentityType.Edge:
                    Application.SetSystemVariable(selMode, 1);
                    break;

                case SubentityType.Vertex:
                    Application.SetSystemVariable(selMode, 3);
                    break;
                }
                pso.ForceSubSelections = true;
            }
            else
            {
                Application.SetSystemVariable(selMode, 0);
            }

            if (!multiple)
            {
                if (pso == null)
                {
                    pso = new PromptSelectionOptions();
                }
                pso.SingleOnly        = true;
                pso.SinglePickInSpace = true;
            }
            var selFiler = selectionFilter;
            PromptSelectionResult selection = null;

            if (pso != null && selFiler != null)
            {
                selection = editor.GetSelection(pso, selFiler);
            }
            else if (pso != null)
            {
                selection = editor.GetSelection(pso);
            }
            else if (selFiler != null)
            {
                selection = editor.GetSelection(selFiler);
            }
            else
            {
                selection = editor.GetSelection();
            }

            Application.SetSystemVariable("SELECTIONMODES", oldVal);
            if (selection.Status != PromptStatus.OK)
            {
                return(null);
            }

            List <FullSubentityPath> selectedSubents = null;

            for (int i = 0; i < selection.Value.Count; ++i)
            {
                if (DatabaseUtils.IsSubentity(subentType))
                {
                    var subents = selection.Value[i].GetSubentities();
                    if (subents == null)
                    {
                        continue;
                    }

                    foreach (var subent in subents)
                    {
                        if (subent.FullSubentityPath.SubentId.Type != subentType)
                        {
                            continue;
                        }

                        if (selectedSubents == null)
                        {
                            selectedSubents = new List <FullSubentityPath>();
                        }
                        selectedSubents.Add(subent.FullSubentityPath);
                    }
                }
                else
                {
                    selectedSubents = selection.Value.GetObjectIds().Select(objId =>
                                                                            new FullSubentityPath(new ObjectId[] { objId },
                                                                                                  new SubentityId(SubentityType.Null, 0))).ToList();
                }
            }
            return(selectedSubents);
        }
Example #27
0
        public void JoinText()
        {
            var      acObjList       = new List <Entity>();
            var      acObjList_Mtext = new List <String>();
            Document acDoc           = acApp.DocumentManager.MdiActiveDocument;
            Database acCurDb         = acDoc.Database;

            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                BlockTable acBlkTbl;
                acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
                                             OpenMode.ForRead) as BlockTable;
                BlockTableRecord acBlkTblRec;
                acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
                                                OpenMode.ForWrite) as BlockTableRecord;

                // Request Mtext object to be selected
                PromptSelectionResult acSSPrompt = acDoc.Editor.GetSelection();

                // If OK
                if (acSSPrompt.Status == PromptStatus.OK)
                {
                    SelectionSet acSSet = acSSPrompt.Value;

                    // Step through the objects
                    foreach (SelectedObject acSSobj in acSSet)
                    {
                        // Check if valid
                        if (acSSobj != null)
                        {
                            // Open object for read
                            Entity acEnt = acTrans.GetObject(acSSobj.ObjectId,
                                                             OpenMode.ForRead) as Entity;

                            if (acEnt != null)
                            {
                                // Seperate out text and mtext entities
                                if (acEnt.GetType() == typeof(MText) || acEnt.GetType() == typeof(DBText))
                                {
                                    // add entity to array
                                    acObjList.Add(acEnt);
                                }
                            }
                        }
                    }
                }

                if (acObjList.Count != 0)
                {
                    //TO-DO:
                    //iterate through acObjList if object is mtext save over to acObjMtext
                    //if objuect is DBtext then convert to mtext and save over to acObjMtext
                    MText    acNewMText = new MText();
                    ObjectId objId;
                    Point3d  acPosition = new Point3d();

                    //get the insertion point of the new mtext block based on the first selected block of text
                    //TO-DO in future figure out which text is the on top in the drawing and use that point
                    if (acObjList[0].GetType() == typeof(DBText))
                    {
                        DBText tempDBtext = acTrans.GetObject(acObjList[0].ObjectId, OpenMode.ForRead) as DBText;
                        acPosition = tempDBtext.Position;
                    }
                    else if (acObjList[0].GetType() == typeof(MText))
                    {
                        MText tempMtext = acTrans.GetObject(acObjList[0].ObjectId, OpenMode.ForRead) as MText;
                        acPosition = tempMtext.Location;
                    }
                    else
                    {
                        acPosition = new Point3d(0, 0, 0);
                    }
                    //iterate though the list of entities and use properties of the first Mtext entity found
                    //for the new mtext entity

                    try
                    {
                        MText firstMtext = (MText)acObjList.Find(x => x.GetType() == typeof(MText));
                        //set relevant properties to the new mtext entity
                        acNewMText.SetDatabaseDefaults();
                        acNewMText.Location    = acPosition;
                        acNewMText.TextHeight  = firstMtext.TextHeight;
                        acNewMText.TextStyleId = firstMtext.TextStyleId;
                        acNewMText.Width       = firstMtext.Width;
                        acNewMText.Layer       = firstMtext.Layer;
                    }
                    catch (System.Exception)
                    {
                        //set relevant properties to the new mtext entity
                        MText firstMtext = new MText();
                        acNewMText.SetDatabaseDefaults();
                        acNewMText.Location = acPosition;
                    }

                    //iterate though each entity add the entities text to the acObjList_Mtext based on
                    //if the entity is DBText or Mtext
                    foreach (Entity acEnt in acObjList)
                    {
                        //test to see if acEnt is Mtext
                        if (acEnt.GetType() == typeof(MText))
                        {
                            //add text contents to acObjList_Mtest
                            MText acMtextTemp = acTrans.GetObject(acEnt.ObjectId, OpenMode.ForRead) as MText;
                            acObjList_Mtext.Add(acMtextTemp.Text);
                        }
                        //if acEnt is not mtext
                        else if (acEnt.GetType() == typeof(DBText))
                        {
                            //add text contents to acObjList_Mtext
                            DBText acDBText = acTrans.GetObject(acEnt.ObjectId, OpenMode.ForWrite) as DBText;
                            acObjList_Mtext.Add(acDBText.TextString);
                        }
                    }

                    //check to make sure that the List acObjList_Mtext is not empty
                    if (acObjList_Mtext.Count != 0)
                    {
                        //add all strings stored in acObjList_Mtext to the new acNewMtext entity
                        string tempStr = "";
                        foreach (string str in acObjList_Mtext)
                        {
                            tempStr += str;
                            tempStr += "\\P";
                        }
                        acNewMText.Contents = tempStr;
                        objId = acBlkTblRec.AppendEntity(acNewMText);
                        acTrans.AddNewlyCreatedDBObject(acNewMText, true);
                    }

                    //remove initially selected objects from the database.
                    for (int i = 0; i < acObjList.Count; i++)
                    {
                        Entity acEnt = acTrans.GetObject(acObjList[i].ObjectId, OpenMode.ForWrite) as Entity;
                        acEnt.Erase();
                        acEnt.Dispose();
                    }
                    acTrans.Commit();
                }
            }
        }
Example #28
0
        //这是转换操作函数
        private void convertToText(PromptSelectionResult SelResult)
        {
            //初始化转换计数
            int count = 0;

            //获取选择集所有实体的ID
            ObjectId[] ObIDs = SelResult.Value.GetObjectIds();
            //启动事务进行实体操作
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                //加一个try进行异常处理
                try
                {
                    //遍历选择集中的所有实体
                    foreach (ObjectId ObID in ObIDs)
                    {
                        //依据实体ID获取实体对象
                        //为加快系统处理速度,OpenMode使用ForRead,轮到需要的实体时再用UpgradeOpen()改为ForWrite
                        DBObject ent = trans.GetObject(ObID, OpenMode.ForRead) as DBObject;
                        //属性块的情况麻烦些,单独拎出来
                        if (ent != null)
                        {
                            if (ent.GetType().Name == "BlockReference")
                            {
                                BlockReference blk = ent as BlockReference;
                                //判断是否是动态块
                                if (blk.IsDynamicBlock)
                                {
                                    AttributeCollection ac = blk.AttributeCollection;
                                    foreach (ObjectId arID in ac)
                                    {
                                        AttributeReference ar = arID.GetObject(OpenMode.ForWrite) as AttributeReference;
                                        if (ar.HasFields)
                                        {
                                            ar.ConvertFieldToText();
                                            count++;
                                        }
                                    }
                                }
                            }
                            if (ent.HasFields)
                            {
                                //获取实体的类型进行判断
                                switch (ent.GetType().Name)
                                {
                                //单行文字
                                case "DBText":
                                {
                                    DBText Dt = (DBText)ent;
                                    //改为ForWrite
                                    Dt.UpgradeOpen();
                                    //利用DBText的ConvertFieldToText()方法转换
                                    //注:该方法用在不含有字段的文字时会报错
                                    Dt.ConvertFieldToText();
                                    count++;
                                    break;
                                }

                                //多行文字
                                case "MText":
                                {
                                    MText Dt = (MText)ent;
                                    Dt.UpgradeOpen();
                                    Dt.ConvertFieldToText();
                                    count++;
                                    break;
                                }
                                }
                            }
                        }
                    }
                    //提交事务保存
                    trans.Commit();
                }

                catch (Autodesk.AutoCAD.Runtime.Exception Ex)
                {
                    ed.WriteMessage("\n出错了!" + Ex.ToString());
                }
                finally
                {
                    //关闭事务
                    trans.Dispose();
                }
            }
            ed.WriteMessage("\n完成转换" + count + "个字段");
        }
Example #29
0
        public void ReadBlocksData()
        {
            Document doc = AcAp.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            // Diretório do desenho atual que chamou o comando.
            string curDwgPath = AcAp.GetSystemVariable("DWGPREFIX").ToString();

            // Arquivo onde será escrito os dados obtidos.
            StreamWriter fileOut = new StreamWriter(curDwgPath + "\\blocksData.txt");

            using (var tr = db.TransactionManager.StartTransaction())
            {
                var      BlkTbl       = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForWrite);
                var      BlkTblRec    = (BlockTableRecord)tr.GetObject(BlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                var      dbModelSpace = (DBObject)tr.GetObject(SymbolUtilityServices.GetBlockModelSpaceId(db), OpenMode.ForWrite);
                ObjectId extId        = dbModelSpace.ExtensionDictionary;
                var      dbExt        = (DBDictionary)tr.GetObject(extId, OpenMode.ForRead);

                PromptSelectionResult acSSRes = ed.GetSelection();
                if (acSSRes.Status == PromptStatus.OK)
                {
                    SelectionSet acSSet = acSSRes.Value;

                    foreach (SelectedObject selectedObject in acSSet)
                    {
                        // Início: Pega o id guardado em seu XDic******************************************************
                        var blkRef = (BlockReference)tr.GetObject(selectedObject.ObjectId, OpenMode.ForRead);

                        // Se o bloco não tem XDic, cria-o e já grava o dado
                        if (blkRef.ExtensionDictionary == ObjectId.Null)
                        {
                            blkRef.UpgradeOpen();
                            RecOnXDict(blkRef, "id", DxfCode.XTextString, dbExt.Count.ToString(), tr);
                            RecOnXDict(dbModelSpace, dbExt.Count.ToString(), DxfCode.Handle, blkRef.Handle, tr);
                        }

                        var          blkDic   = (DBDictionary)tr.GetObject(blkRef.ExtensionDictionary, OpenMode.ForRead);
                        var          xRecBlk  = (Xrecord)tr.GetObject(blkDic.GetAt("id"), OpenMode.ForRead);
                        ResultBuffer rb       = xRecBlk.Data;
                        TypedValue[] xRecData = rb.AsArray();
                        string       sBlkId   = xRecData[0].Value.ToString();
                        // Fim: Pega o id guardado em seu XDic*************************************************************************************

                        // Início: checa se o id do bloco confere com o handle registrado no MS ***************************************************
                        var blkRef2 = GetRefBlkFromIndex(db, dbExt, sBlkId);

                        if (blkRef.Id != blkRef2.Id)
                        {
                            RecOnXDict(blkRef, "id", DxfCode.XTextString, dbExt.Count.ToString(), tr);
                            RecOnXDict(dbModelSpace, dbExt.Count.ToString(), DxfCode.Handle, blkRef.Handle, tr);
                        }
                        // Fim: checa se o id do bloco confere com o handle registrado no MS ******************************************************

                        string blkName = blkRef.Name;

                        // Se é bloco dinamico, a forma de pegar o nome do bloco
                        // é desse jeito:
                        BlockTableRecord realBlock = null;
                        string           atts      = "";
                        if (blkRef.IsDynamicBlock)
                        {
                            realBlock = (BlockTableRecord)tr.GetObject(blkRef.DynamicBlockTableRecord, OpenMode.ForRead);
                            blkName   = realBlock.Name;

                            // Le os atributos do bloco
                            if (realBlock.HasAttributeDefinitions)
                            {
                                var     blkRefAtts = (AttributeCollection)blkRef.AttributeCollection;
                                RXClass rxClass    = RXClass.GetClass(typeof(AttributeReference));
                                foreach (ObjectId idAttDef in blkRefAtts)
                                {
                                    if (idAttDef.ObjectClass == rxClass)
                                    {
                                        AttributeReference obj = (AttributeReference)tr.GetObject(idAttDef, OpenMode.ForRead);

                                        atts += obj.Tag + "::" + obj.TextString + "//";
                                    }
                                }
                            }
                        }

                        double blkRot   = blkRef.Rotation * (180 / Math.PI);
                        string blkX     = blkRef.Position.X.ToString("n2");
                        string blkY     = blkRef.Position.Y.ToString("n2");
                        string blkLayer = blkRef.Layer;
                        string blkColor = Convert.ToString(blkRef.ColorIndex);

                        fileOut.WriteLine(sBlkId + ";" + blkName + ";" + blkRot + ";" + blkX + ";" + blkY + ";"
                                          + blkLayer + ";" + blkColor + ";" + atts + ";");
                    }
                }

                fileOut.Close();
                tr.Commit();
            }
        }
Example #30
0
        public override Result excute()
        {
            Database acCurDb = acDoc.Database;
            PromptSelectionResult      resutl  = acDoc.Editor.GetSelection();
            Dictionary <string, float> sumDict = new Dictionary <string, float>();
            string   selectLayer = "";
            ObjectId textStyle   = acCurDb.Textstyle;

            if (resutl.Status == PromptStatus.OK)
            {
                log("选择的个数:" + resutl.Value.Count);
                SelectionSet acSSet = resutl.Value;

                using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
                {
                    // Step through the objects in the selection set
                    foreach (SelectedObject acSSObj in acSSet)
                    {
                        // Check to make sure a valid SelectedObject object was returned
                        if (acSSObj != null)
                        {
                            // Open the selected object for write
                            Entity acEnt = acTrans.GetObject(acSSObj.ObjectId,
                                                             OpenMode.ForWrite) as Entity;
                            selectLayer = acEnt.Layer;
                            List <string> selectStrs = new List <string>();
                            if (acEnt != null)
                            {
                                if (acEnt.GetType() == typeof(MText))
                                {
                                    selectStrs.Add((acEnt as MText).Contents);
                                    textStyle = (acEnt as MText).TextStyleId;
                                }
                                else if (acEnt.GetType() == typeof(DBText))
                                {
                                    selectStrs.Add((acEnt as DBText).TextString);
                                }
                                else if (acEnt.GetType().ToString() == "")
                                {
                                }
                            }

                            foreach (string item in selectStrs)
                            {
                                Array result = getStrNumber(item, acDoc.Editor);
                                //acDoc.Editor.WriteMessage("\n Parse content " + result.GetValue(0) + "," + result.GetValue(1));
                                string numStr = result.GetValue(1) as string;
                                if (numStr.Length == 0)
                                {
                                    numStr = "0";
                                }
                                float num = 0;
                                try
                                {
                                    num = float.Parse(numStr);
                                }
                                catch (System.Exception e)
                                {
                                    acDoc.Editor.WriteMessage("\n文本的内容格式不正确,请修改后再运行命令:" + item);
                                    continue;
                                }
                                if (sumDict.ContainsKey(result.GetValue(0) as string))
                                {
                                    sumDict[result.GetValue(0) as string] += num;
                                }
                                else
                                {
                                    sumDict.Add(result.GetValue(0) as string, num);
                                }
                            }
                        }
                    }

                    string sumResult = "";
                    foreach (string key in sumDict.Keys)
                    {
                        sumResult += key + ":" + sumDict[key] + "\n";
                    }

                    List <object>         tempList;
                    List <List <object> > exResult = new List <List <object> >();
                    foreach (string key in sumDict.Keys)
                    {
                        tempList = new List <object>();
                        tempList.Add(key);
                        tempList.Add(sumDict[key]);
                        //result += key + ":" + sumDict[key] + "\n";
                        exResult.Add(tempList);
                    }
                    acTrans.Commit();
                    return(new Result(exResult));
                }
            }
            return(new Result("未选择目标"));
        }
Example #31
0
        //--------------------------------------------------------------------------
        //
        // ���ܣ�ɾ��ע������
        //
        //  ���ߣ�
        //
        //  ���ڣ�200708
        //
        //   ��ʷ��
        //--------------------------------------------------------------------------
        private void btnInsertOverride_Click(System.Object sender, System.EventArgs e)
        {
            try
            {
                //
                m_annoOverrides.Clear();

                int curSel = listbTemplates.SelectedIndex;
                if (LB_ERR == curSel)
                {
                    MessageBox.Show("����ѡ��ע��ģ��");
                    return;
                }

                m_selectedTemplateName = listbTemplates.SelectedItem.ToString();
                m_idTemplate = m_annotations[m_selectedTemplateName].BlockDefinitionId;
                m_templateName = m_selectedTemplateName;

                using (Transaction trans = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.TransactionManager.StartTransaction())
                {
                    BlockTableRecord blkTblRcd = (BlockTableRecord)(trans.GetObject(m_idTemplate, Autodesk.AutoCAD.DatabaseServices.OpenMode.ForRead));

                    //
                    string templateName = null;
                    if (!m_annotations.IsAnnotationTemplate(ref templateName, blkTblRcd))
                    {
                        MessageBox.Show("���ע��ģ��ʧ��.");
                        return;
                    }
                    trans.Commit();
                }

                try
                {
                    m_selSetResult = Utility.AcadEditor.GetSelection();

                    if ((m_selSetResult.Status == PromptStatus.OK) && (m_selSetResult.Value.Count > 0))
                    {
                        // Initialize the m_annoOverrides with values which we want to override
                        m_annoOverrides.RotationOverride = 0.0;
                        m_annoOverrides.ScaleFactorOverride = 0.0;

                        Autodesk.AutoCAD.Colors.Color greenClr = Autodesk.AutoCAD.Colors.Color.FromColorIndex(Autodesk.AutoCAD.Colors.ColorMethod.None, 3);
                        m_annoOverrides.ColorOverride = greenClr;
                        // Note: Above m_annoOverrides.ColorOverride will override the value
                        // which we set in the annotation template using the
                        // tagText.set_Color(color); if color is other than byblock

                        m_annoOverrides.LayerOverride = null;
                        m_annoOverrides.LinetypeOverride = null;
                        m_annoOverrides.LineweightOverride = null;
                        m_annoOverrides.RotationExpressionOverride = "(- .ANGLE 0.785398163)";   //��ת�ĽǶ�
                        m_annoOverrides.ScaleFactorExpressionOverride = null;

                        m_annoOverrides.ColorExpressionOverride = null;
                        m_annoOverrides.LayerExpressionOverride = null;
                        m_annoOverrides.LinetypeExpressionOverride = null;
                        m_annoOverrides.LineweightExpressionOverride = null;
                        m_annoOverrides.PositionExpressionOverride = null;

                        foreach (Autodesk.AutoCAD.EditorInput.SelectedObject selectedObject in m_selSetResult.Value)
                        {
                            ObjectId idInserted;
                            idInserted = m_annotations[m_selectedTemplateName].InsertReference(selectedObject.ObjectId, m_annoOverrides);
                        }
                        Regen();
                        // Close the dialog
                        DialogResult = DialogResult.OK;
                    }
                    else
                    {
                        MessageBox.Show("û��ѡ��ʵ�壬����ȡ��");
                    }
                }
                catch (Autodesk.AutoCAD.Runtime.Exception err)
                {
                    MessageBox.Show(string.Format("��������ʧ�� .\n{0}", err.Message));
                }
            }
            catch (System.Exception err)
            {
                MessageBox.Show(err.Message);
            }
        }
Example #32
0
        public static PromptNestedEntityThroughViewportResult GetNestedEntityThroughViewport(this Editor acadEditor, PromptNestedEntityThroughViewportOptions options)
        {
            Document      acadDocument  = acadEditor.Document;
            Database      acadDatabase  = acadDocument.Database;
            LayoutManager layoutManager = LayoutManager.Current;

            SelectThroughViewportJig stvpJig = new SelectThroughViewportJig(options);

            PromptResult pointResult = acadEditor.Drag(stvpJig);

            if (pointResult.Status == PromptStatus.OK)
            {
                Point3d pickedPoint = stvpJig.Result.Value;

                PromptNestedEntityOptions pneOpions = options.Options;
                pneOpions.NonInteractivePickPoint    = pickedPoint;
                pneOpions.UseNonInteractivePickPoint = true;

                PromptNestedEntityResult pickResult = acadEditor.GetNestedEntity(pneOpions);

                if ((pickResult.Status == PromptStatus.OK) ||
                    (acadDatabase.TileMode) ||
                    (acadDatabase.PaperSpaceVportId != acadEditor.CurrentViewportObjectId))
                {
                    return(new PromptNestedEntityThroughViewportResult(pickResult));
                }
                else
                {
                    SelectionFilter vportFilter = new SelectionFilter(new TypedValue[] { new TypedValue(0, "VIEWPORT"),
                                                                                         new TypedValue(-4, "!="),
                                                                                         new TypedValue(69, 1),
                                                                                         new TypedValue(410, layoutManager.CurrentLayout) });

                    PromptSelectionResult vportResult = acadEditor.SelectAll(vportFilter);

                    if (vportResult.Status == PromptStatus.OK)
                    {
                        using (Transaction trans = acadDocument.TransactionManager.StartTransaction())
                        {
                            foreach (ObjectId objectId in vportResult.Value.GetObjectIds())
                            {
                                Viewport viewport = (Viewport)trans.GetObject(objectId, OpenMode.ForRead, false, false);

                                if (viewport.ContainsPoint(pickedPoint))
                                {
                                    pneOpions.NonInteractivePickPoint    = TranslatePointPsToMs(viewport, pickedPoint);
                                    pneOpions.UseNonInteractivePickPoint = true;

                                    acadEditor.SwitchToModelSpace();

                                    Application.SetSystemVariable("CVPORT", viewport.Number);

                                    PromptNestedEntityResult pneResult = acadEditor.GetNestedEntity(pneOpions);

                                    acadEditor.SwitchToPaperSpace();

                                    if (pneResult.Status == PromptStatus.OK)
                                    {
                                        return(new PromptNestedEntityThroughViewportResult(pneResult, objectId));
                                    }
                                }
                            }
                        }
                    }

                    return(new PromptNestedEntityThroughViewportResult(pickResult));
                }
            }
            else
            {
                return(new PromptNestedEntityThroughViewportResult(pointResult));
            }
        }