示例#1
0
        Stream(ArrayList data, PromptNestedEntityResult res)
        {
            data.Add(new Snoop.Data.ClassSeparator(typeof(PromptNestedEntityResult)));

            data.Add(new Snoop.Data.Object("Transform", res.Transform));
            data.Add(new Snoop.Data.ObjectIdCollection("Containers", res.GetContainers()));
        }
 internal PromptNestedEntityThroughViewportResult(PromptNestedEntityResult pneResult)
 {
     m_status       = pneResult.Status;
     m_stringResult = pneResult.StringResult;
     m_pickPoint    = pneResult.PickedPoint;
     m_value        = pneResult.ObjectId;
     m_containers   = pneResult.GetContainers();
     m_mat          = pneResult.Transform;
     m_viewport     = Autodesk.AutoCAD.DatabaseServices.ObjectId.Null;
 }
 internal PromptNestedEntityThroughViewportResult(PromptNestedEntityResult pneResult, ObjectId viewport)
 {
     m_status       = pneResult.Status;
     m_stringResult = pneResult.StringResult;
     m_pickPoint    = pneResult.PickedPoint;
     m_value        = pneResult.ObjectId;
     m_containers   = pneResult.GetContainers();
     m_mat          = pneResult.Transform;
     m_viewport     = viewport;
 }
        private static bool DeleteLevelText(ObjectId fflToEditId)
        {
            Document acDoc    = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument;
            Database acCurrDb = acDoc.Database;
            Editor   acEditor = acDoc.Editor;

            // Loop so user can delete multiple levels
            bool deletingLevels = true;

            while (deletingLevels)
            {
                // Prompt the user to select the level to edit
                PromptNestedEntityOptions nestedEntOpt = new PromptNestedEntityOptions("\nPick the level to delete (spacebar to finish):");
                PromptNestedEntityResult  nestedEntRes = acEditor.GetNestedEntity(nestedEntOpt);
                if (nestedEntRes.Status == PromptStatus.OK)
                {
                    using (Transaction acTrans = acCurrDb.TransactionManager.StartTransaction())
                    {
                        try
                        {
                            Entity ent = acTrans.GetObject(nestedEntRes.ObjectId, OpenMode.ForRead) as Entity;
                            if (ent.GetType() == typeof(MText))
                            {
                                MText levelToDelete = ent as MText;
                                if (levelToDelete.Layer != StyleNames.JPP_APP_Levels_Layer)
                                {
                                    acEditor.WriteMessage("\nSelected text is on the wrong layer!");
                                    continue;
                                }
                                levelToDelete.UpgradeOpen();
                                levelToDelete.Erase();
                                // Update block graphics
                                BlockReference fflToEdit = acTrans.GetObject(fflToEditId, OpenMode.ForWrite) as BlockReference;
                                fflToEdit = acTrans.GetObject(fflToEditId, OpenMode.ForWrite) as BlockReference;
                                fflToEdit.RecordGraphicsModified(true);
                                acTrans.Commit();
                            }
                        }
                        catch (Autodesk.AutoCAD.Runtime.Exception acException)
                        {
                            Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog
                                ("The following exception was caught: \n" + acException.Message
                                + "\nError deleting level!\n");
                            acTrans.Abort();
                            return(false);
                        }
                    }
                }
                if (nestedEntRes.Status == PromptStatus.Cancel)
                {
                    deletingLevels = false;
                }
            }
            return(true);
        }
示例#5
0
        highlightNestedEntity()
        {
            Document doc =
                Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;

            PromptNestedEntityResult rs =
                ed.GetNestedEntity("\nSelect nested entity: ");

            if (rs.Status == PromptStatus.OK)
            {
                ObjectId[] objIds = rs.GetContainers();
                ObjectId   ensel  = rs.ObjectId;
                int        len    = objIds.Length;

                // Reverse the "containers" list
                ObjectId[] revIds = new ObjectId[len + 1];
                for (int i = 0; i < len; i++)
                {
                    ObjectId id =
                        (ObjectId)objIds.GetValue(len - i - 1);
                    revIds.SetValue(id, i);
                }
                // Now add the selected entity to the end
                revIds.SetValue(ensel, len);

                // Retrieve the sub-entity path for this entity
                SubentityId subEnt =
                    new SubentityId(SubentityType.Null, (IntPtr)0);
                FullSubentityPath path =
                    new FullSubentityPath(revIds, subEnt);

                try
                {
                    using (Transaction tr = BaseObjs.startTransactionDb())
                    {
                        // Open the outermost container...
                        ObjectId id  = (ObjectId)revIds.GetValue(0);
                        Entity   ent =
                            (Entity)tr.GetObject(id, OpenMode.ForRead);
                        // ... and highlight the nested entity
                        ent.Highlight(path, false);
                        tr.Commit();
                    }
                }
                catch (System.Exception ex)
                {
                    BaseObjs.writeDebug(ex.Message + " View.cs: line: 162");
                }
            }
        }
示例#6
0
        Stream(ArrayList data, PromptEntityResult res)
        {
            data.Add(new Snoop.Data.ClassSeparator(typeof(PromptEntityResult)));

            data.Add(new Snoop.Data.ObjectId("Object ID", res.ObjectId));
            data.Add(new Snoop.Data.Point3d("Picked point", res.PickedPoint));

            PromptNestedEntityResult promptNestedEntRes = res as PromptNestedEntityResult;

            if (promptNestedEntRes != null)
            {
                Stream(data, promptNestedEntRes);
                return;
            }
        }
示例#7
0
        public void NestEntSelect()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Editor   ed  = doc.Editor;

            PromptNestedEntityOptions pneo = new PromptNestedEntityOptions(
                "\nSelect nested entity:");

            PromptNestedEntityResult nestedBlock = ed.GetNestedEntity(pneo);

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

            using (Transaction Tx = doc.TransactionManager.StartTransaction())
            {
                //Containers
                ObjectId[] containerIds = nestedBlock.GetContainers();

                foreach (ObjectId id in containerIds)
                {
                    DBObject container = Tx.GetObject(id, OpenMode.ForRead);

                    if (container is BlockReference)
                    {
                        BlockReference bref = container as BlockReference;

                        ed.WriteMessage("\nContainer: " + bref.BlockName);
                    }
                }

                Entity entity = Tx.GetObject(nestedBlock.ObjectId, OpenMode.ForRead)
                                as Entity;

                ed.WriteMessage("\nEntity: " + entity.ToString());

                ed.WriteMessage("\nBlock: " + entity.BlockName);

                BlockTableRecord btr = Tx.GetObject(entity.BlockId, OpenMode.ForRead)
                                       as BlockTableRecord;

                Tx.Commit();
            }
        }
示例#8
0
        public PromptStatus PromptSlopeInsideBlock(out PromptNestedEntityResult res, KeywordCollection keywoeds = null,
                                                   Func <PromptNestedEntityResult, PromptStatus> promptAction   = null, string msg = "\nВыберите линиюю")
        {
            res = null;

            PromptNestedEntityOptions pneo = new PromptNestedEntityOptions(msg);

            pneo.UseNonInteractivePickPoint = false;
            if (keywoeds != null)
            {
                foreach (Keyword key in keywoeds)
                {
                    pneo.Keywords.Add(key.GlobalName, key.LocalName, key.DisplayName, key.Visible, key.Enabled);
                }
            }

            PromptNestedEntityResult pner = Tools.GetAcadEditor().GetNestedEntity(pneo);

            if (pner.Status == PromptStatus.Keyword)
            {
                if (promptAction != null)
                {
                    var kwRes = promptAction(pner);
                    if (kwRes != PromptStatus.OK)
                    {
                        return(kwRes);
                    }
                }
            }

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

            if (!pner.ObjectId.ObjectClass.IsDerivedFrom(Autodesk.AutoCAD.Runtime.RXClass.GetClass(typeof(Line))))
            {
                return(PromptStatus.Error);
            }

            res = pner;

            return(PromptStatus.OK);
        }
示例#9
0
        getNestedEntity(PromptEntityResult per, BlockReference br)
        {
            Entity ent = null;
            Editor ed  = BaseObjs._editor;
            PromptNestedEntityOptions pneo = new PromptNestedEntityOptions("");

            pneo.NonInteractivePickPoint    = per.PickedPoint;
            pneo.UseNonInteractivePickPoint = true;

            PromptNestedEntityResult pner = ed.GetNestedEntity(pneo);

            try
            {
                using (Transaction tr = BaseObjs.startTransactionDb())
                {
                    if (pner.Status == PromptStatus.OK)
                    {
                        ObjectId idSel = pner.ObjectId;
                        DBObject obj   = idSel.GetObject(OpenMode.ForRead);

                        if (obj is PolylineVertex3d || obj is Vertex2d)
                        {
                            idSel = obj.OwnerId;
                        }

                        if (obj is MText || obj is DBText)
                        {
                            return(null);
                        }

                        ent = (Entity)obj;
                    }
                    tr.Commit();
                }
            }
            catch (System.Exception ex)
            {
                BaseObjs.writeDebug(ex.Message + " xRef.cs: line: 639");
            }
            return(ent);
        }
示例#10
0
        private static void HighlightSubEntity(Document doc, PromptNestedEntityResult rs)
        {
            // Extract relevant information from the prompt object
            ObjectId selId = rs.ObjectId;

            ObjectId[] objIds = rs.GetContainers();

            int len = objIds.Length;

            // Reverse the "containers" list
            ObjectId[] revIds = new ObjectId[len + 1];
            for (int i = 0; i < len; i++)
            {
                ObjectId id = (ObjectId)objIds.GetValue(len - i - 1);
                revIds.SetValue(id, i);
            }

            // Now add the selected entity to the end
            revIds.SetValue(selId, len);

            // Retrieve the sub-entity path for this entity
            SubentityId subEnt = new SubentityId(SubentityType.Null, 0);

            FullSubentityPath path = new FullSubentityPath(revIds, subEnt);

            // Open the outermost container, relying on the open
            // transaction...

            ObjectId id2 = (ObjectId)revIds.GetValue(0);
            Entity   ent = id2.GetObject(OpenMode.ForRead) as Entity;

            // ... and highlight the nested entity
            if (ent != null)
            {
                ent.Highlight(path, false);
            }
        }
示例#11
0
        public bool SelectNestedEntitiesAuto(Editor ed, Point3d pos, out ObjectId id, out ObjectId[] ids, out string result, out Point3d point)
        {
            result = "";
            id     = ObjectId.Null;
            ids    = null;
            point  = default(Point3d);
            PromptNestedEntityResult nestedEntity = ed.GetNestedEntity(new PromptNestedEntityOptions("")
            {
                NonInteractivePickPoint    = pos,
                UseNonInteractivePickPoint = true
            });

            if (nestedEntity.Status == 5100)
            {
                id = nestedEntity.ObjectId;
                ObjectId        objectId = nestedEntity.ObjectId;
                List <ObjectId> list     = new List <ObjectId>(nestedEntity.GetContainers());
                list.Reverse();
                list.Add(objectId);
                ids   = list.ToArray();
                point = nestedEntity.PickedPoint;
            }
            return(nestedEntity.Status == 5100);
        }
示例#12
0
        SnoopNestedEntity()
        {
            Editor             ed     = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            ObjectIdCollection selSet = new ObjectIdCollection();

            while (true)
            {
                PromptNestedEntityOptions prOptNent = new PromptNestedEntityOptions("\nSelect nested entities or: ");
                prOptNent.AppendKeywordsToMessage = true;
                prOptNent.Keywords.Add("Done");

                PromptNestedEntityResult res = ed.GetNestedEntity(prOptNent);
                if (res.Status == PromptStatus.OK)
                {
                    selSet.Add(res.ObjectId);
                }
                else if (res.Status == PromptStatus.Keyword)
                {
                    break;
                }
                else
                {
                    return;
                }
            }

            using (TransactionHelper trHlp = new TransactionHelper()) {
                trHlp.Start();

                Snoop.Forms.DBObjects dbox = new Snoop.Forms.DBObjects(selSet, trHlp);
                dbox.Text = "Selected Entities";
                AcadApp.ShowModalDialog(dbox);

                trHlp.Commit();
            }
        }
示例#13
0
        OnPromptForEntityEnding(object sender, PromptForEntityEndingEventArgs e)
        {
            if (e.Result.Status == PromptStatus.OK)
            {
                Editor   ed    = sender as Editor;
                ObjectId objId = e.Result.ObjectId;
                Database db    = objId.Database;

                try
                {
                    using (Transaction tr = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Database.TransactionManager.StartTransaction())
                    {
                        // First get the currently selected object and check whether it's a block reference
                        BlockReference br = tr.GetObject(objId, OpenMode.ForRead) as BlockReference;
                        if (br != null)
                        {
                            // If so, we check whether the block table record to which it refers is actually from an XRef
                            ObjectId         btrId = br.BlockTableRecord;
                            BlockTableRecord btr   = tr.GetObject(btrId, OpenMode.ForRead) as BlockTableRecord;
                            if (btr != null)
                            {
                                if (btr.IsFromExternalReference)
                                {
                                    // If so, then we programmatically select the object underneath the pick-point already used
                                    PromptNestedEntityOptions pneo = new PromptNestedEntityOptions("");
                                    pneo.NonInteractivePickPoint    = e.Result.PickedPoint;
                                    pneo.UseNonInteractivePickPoint = true;

                                    PromptNestedEntityResult pner = ed.GetNestedEntity(pneo);

                                    if (pner.Status == PromptStatus.OK)
                                    {
                                        try
                                        {
                                            ObjectId selId = pner.ObjectId;

                                            // Let's look at this programmatically-selected object, to see what it is

                                            DBObject obj = selId.GetObject(OpenMode.ForRead);

                                            // If it's a polyline vertex, we need to go one level up to the polyline itself

                                            if (obj is PolylineVertex3d || obj is Vertex2d)
                                            {
                                                selId = obj.OwnerId;
                                            }

                                            // We don't want to do anything at all for textual stuff, let's also make sure we
                                            // are dealing with an entity (should always be the case)

                                            if (obj is MText || obj is DBText || !(obj is Entity))
                                            {
                                                return;
                                            }

                                            // Now let's get the name of the layer, to use later

                                            Entity           ent     = (Entity)obj;
                                            LayerTableRecord ltr     = (LayerTableRecord)tr.GetObject(ent.LayerId, OpenMode.ForRead);
                                            string           layName = ltr.Name;

                                            // Clone the selected object

                                            object o     = ent.Clone();
                                            Entity clone = o as Entity;

                                            // We need to manipulate the clone to make sure it works

                                            if (clone != null)
                                            {
                                                // Setting the properties from the block reference helps certain entities get the
                                                // right references (and allows them to be offset properly)
                                                clone.SetPropertiesFrom(br);

                                                // But we then need to get the layer information from the database to set the
                                                // right layer (at least) on the new entity

                                                LayerTable lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead);
                                                if (lt.Has(layName))
                                                {
                                                    clone.LayerId = lt[layName];
                                                }

                                                // Now we need to transform the entity for each of its Xref block reference containers
                                                // If we don't do this then entities in nested Xrefs may end up in the wrong place

                                                ObjectId[] conts = pner.GetContainers();
                                                foreach (ObjectId contId in conts)
                                                {
                                                    BlockReference cont = tr.GetObject(contId, OpenMode.ForRead) as BlockReference;
                                                    if (cont != null)
                                                    {
                                                        clone.TransformBy(cont.BlockTransform);
                                                    }
                                                }

                                                // Let's add the cloned entity to the current space

                                                BlockTableRecord space = tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;
                                                if (space == null)
                                                {
                                                    clone.Dispose();
                                                    return;
                                                }

                                                ObjectId cloneId = space.AppendEntity(clone);
                                                tr.AddNewlyCreatedDBObject(clone, true);

                                                // Now let's flush the graphics, to help our clone get displayed

                                                tr.TransactionManager.QueueForGraphicsFlush();

                                                // And we add our cloned entity to the list for deletion

                                                _ids.Add(cloneId);

                                                // Created a non-graphical selection of our newly created object and replace it with
                                                // the selection of the container Xref

                                                IntPtr         ip = (IntPtr)0;
                                                SelectedObject so = new SelectedObject(cloneId, SelectionMethod.NonGraphical, ip);  //?????????????????????????????????
                                                e.ReplaceSelectedObject(so);
                                            }
                                        }
                                        catch (System.Exception ex)
                                        {
                                            BaseObjs.writeDebug(ex.Message + " xRefOffsetApp.cs: line: 259");
                                        }
                                    }
                                }
                            }
                        }
                        tr.Commit();
                    }
                }
                catch (System.Exception ex)
                {
                    BaseObjs.writeDebug(ex.Message + " xRefOffsetApp.cs: line: 270");
                }
            }
        }
示例#14
0
        public void NestedEntityTest()
        {
            ObjectIdCollection        coll    = new ObjectIdCollection();
            Editor                    ed      = Application.DocumentManager.MdiActiveDocument.Editor;
            PromptNestedEntityOptions entopts = new PromptNestedEntityOptions("prompt nested entity");

            entopts.AllowNone = true;
            entopts.Keywords.Add("Done");
            PromptNestedEntityResult ent = null;
            Database db = Application.DocumentManager.MdiActiveDocument.Database;

            Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = db.TransactionManager;

            using (Transaction myT = tm.StartTransaction())
            {
                while (true)
                {
                    entopts.Message = "\nPick an entity of your choice from the drawing or type Done";

                    try
                    {
                        ent = ed.GetNestedEntity(entopts);
                    }
                    catch
                    {
                        ed.WriteMessage("\nYou did not select a valid nested entity");
                        break;
                    }
                    if (ent.Status == PromptStatus.Keyword)
                    {
                        if (ent.StringResult.Equals("Done"))
                        {
                            break;
                        }
                    }

                    try
                    {
                        if (ent.GetContainers().Length > 0)
                        {
                            Entity entity;
                            foreach (ObjectId oid in ent.GetContainers())
                            {
                                entity = (Entity)tm.GetObject(oid, OpenMode.ForRead, true);
                                ed.WriteMessage("You selected: " + entity.GetType().FullName);
                            }
                            break;
                        }
                        else
                        {
                            ed.WriteMessage("You did not select any nested entity");
                        }
                    }
                    catch
                    {
                        ed.WriteMessage("You are Done or did not select any nested entity");
                        myT.Commit();
                        return;
                    }
                }

                entopts.NonInteractivePickPoint    = new Point3d(30.4, 11.6, 0);
                entopts.UseNonInteractivePickPoint = true;

                try
                {
                    ent = ed.GetNestedEntity(entopts);
                    if (ent.GetContainers().Length > 0)
                    {
                        Entity entity;
                        foreach (ObjectId oid in ent.GetContainers())
                        {
                            entity = (Entity)tm.GetObject(oid, OpenMode.ForRead, true);
                            ed.WriteMessage(entity.GetType().FullName + " has been selected");
                        }
                    }
                    else
                    {
                        ed.WriteMessage("No nested entity was selected");
                    }
                }
                catch
                {
                    ed.WriteMessage("\nNo entity was selected");
                }
                myT.Commit();
            }
        }
示例#15
0
        getNestedEntity(PromptEntityResult per, BlockReference br, bool makeCopy, out string nameLayer)
        {
            nameLayer = "";
            Entity   ent = null;
            Editor   ed  = BaseObjs._editor;
            Database db  = BaseObjs._db;
            PromptNestedEntityOptions pneo = new PromptNestedEntityOptions("");

            pneo.NonInteractivePickPoint    = per.PickedPoint;
            pneo.UseNonInteractivePickPoint = true;

            PromptNestedEntityResult pner = ed.GetNestedEntity(pneo);

            try
            {
                using (Transaction tr = BaseObjs.startTransactionDb())
                {
                    if (pner.Status == PromptStatus.OK)
                    {
                        ObjectId idSel = pner.ObjectId;
                        DBObject OBJ   = idSel.GetObject(OpenMode.ForRead);

                        if (OBJ is PolylineVertex3d || OBJ is Vertex2d)
                        {
                            idSel = OBJ.OwnerId;
                        }

                        if (OBJ is MText || OBJ is DBText || !(OBJ is Entity))
                        {
                            return(null);
                        }

                        ent = (Entity)OBJ;
                        if (makeCopy == true)
                        {
                            object o     = ent.Clone();
                            Entity clone = o as Entity;

                            if (clone != null)
                            {
                                clone.SetPropertiesFrom(br);

                                ObjectId[] conts = pner.GetContainers();
                                foreach (ObjectId idCont in conts)
                                {
                                    BlockReference cont = (BlockReference)idCont.GetObject(OpenMode.ForRead);
                                    if (cont != null)
                                    {
                                        clone.TransformBy(cont.BlockTransform);
                                    }
                                }

                                BlockTableRecord space = (BlockTableRecord)db.CurrentSpaceId.GetObject(OpenMode.ForWrite);
                                if (space == null)
                                {
                                    clone.Dispose();

                                    nameLayer = ent.Layer;
                                    return(null);
                                }
                                space.AppendEntity(clone);
                                tr.AddNewlyCreatedDBObject(clone, true);
                                tr.Commit();

                                nameLayer = ent.Layer.ToString();
                                return(clone);
                            }
                        }
                        else
                        {
                            return(ent);
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                BaseObjs.writeDebug(ex.Message + " xRef.cs: line: 715");
            }
            return(ent);
        }
示例#16
0
        getNestedEntity(string prompt, out bool escape, out Point3d pnt3dX, out string nameLayer, out FullSubentityPath path)
        {
            nameLayer = "";
            Entity   ent = null;
            Database db  = BaseObjs._db;

            path = new FullSubentityPath();

            Editor ed = BaseObjs._editor;

            PromptNestedEntityOptions pneo = new PromptNestedEntityOptions(prompt);
            PromptNestedEntityResult  pner = ed.GetNestedEntity(pneo);

            if (pner.Status == PromptStatus.Cancel || pner.Status == PromptStatus.None)
            {
                pnt3dX = Pub.pnt3dO;
                escape = true;
                return(null);
            }

            pnt3dX = pner.PickedPoint;

            try
            {
                using (Transaction tr = BaseObjs.startTransactionDb())
                {
                    if (pner.Status == PromptStatus.OK)
                    {
                        escape = false;
                        ObjectId[] idsContainers = pner.GetContainers();
                        ObjectId   idSel         = pner.ObjectId;
                        int        len           = idsContainers.Length;

                        ObjectId[] idsRev = new ObjectId[len + 1];
                        //Reverse the "containers" list
                        for (int i = 0; i < len; i++)
                        {
                            ObjectId id = (ObjectId)idsContainers.GetValue(len - 1 - i);
                            idsRev.SetValue(id, i);
                        }
                        //Now add the selected entity to the end of the array
                        idsRev.SetValue(idSel, len);

                        //Retrieve the sub-entity path for this entity
                        SubentityId idSubEnt = new SubentityId(SubentityType.Null, (IntPtr)0);
                        path = new FullSubentityPath(idsRev, idSubEnt);

                        ObjectId idX = (ObjectId)idsRev.GetValue(0);
                        ent = (Entity)tr.GetObject(idX, OpenMode.ForRead);

                        ent.Highlight(path, false);

                        DBObject obj = idSel.GetObject(OpenMode.ForRead);

                        ObjectId idOwner = ObjectId.Null;

                        if (obj is PolylineVertex3d || obj is Vertex2d)
                        {
                            idOwner = obj.OwnerId;
                            ent     = (Entity)tr.GetObject(idOwner, OpenMode.ForRead);
                        }
                        else if (obj is MText || obj is DBText || !(obj is Entity))
                        {
                            return(ent);
                        }
                        else
                        {
                            ent = (Entity)obj;
                        }

                        object o     = ent.Clone();
                        Entity clone = (Entity)o;

                        if (clone != null)
                        {
                            //ObjectId[] conts = pner.GetContainers();
                            foreach (ObjectId idContainer in idsContainers)
                            {
                                BlockReference br = (BlockReference)idContainer.GetObject(OpenMode.ForRead);
                                if (br != null)
                                {
                                    clone.SetPropertiesFrom(br);
                                    clone.TransformBy(br.BlockTransform);
                                }
                            }

                            BlockTableRecord space = (BlockTableRecord)db.CurrentSpaceId.GetObject(OpenMode.ForWrite);
                            if (space == null)
                            {
                                clone.Dispose();
                                return(ent);
                            }
                            else if (clone is Arc)
                            {
                                Arc arc = (Arc)clone;
                                pnt3dX = arc.GetClosestPointTo(pnt3dX, false);
                            }
                            else if (clone is Line)
                            {
                                Line line = (Line)clone;
                                pnt3dX = line.GetClosestPointTo(pnt3dX, false);
                            }
                            else if (clone is Polyline)
                            {
                                Polyline poly = (Polyline)clone;
                                pnt3dX = poly.GetClosestPointTo(pnt3dX, false);
                            }
                            else
                            {
                                Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(string.Format("Selected item was of type: {0}.  Exiting...", clone.GetType().Name));
                            }
                            nameLayer = ent.Layer.ToString();

                            tr.Commit();

                            return(ent);
                        }
                    }
                    else
                    {
                        escape = true;
                    }
                }
            }
            catch (System.Exception ex)
            {
                BaseObjs.writeDebug(ex.Message + " xRef.cs: line: 842");
                escape = true;
            }
            return(ent);
        }
示例#17
0
        public static void InterpolatePoint()
        {
            Document doc = acadApp.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            PromptEntityOptions peoXref = new PromptEntityOptions("\nSelect Grading Xref.")
            {
                AllowObjectOnLockedLayer = true,
                AllowNone = false
            };
            PromptEntityOptions peoPolyLine1 = new PromptEntityOptions("\nSelect polyline 1.");
            PromptEntityOptions peoPolyLine2 = new PromptEntityOptions("\nSelect polyline 2.");
            PromptPointOptions  ppo          = new PromptPointOptions("\nSelect Point of intrest.");

            PromptPointResult ppr = ed.GetPoint(ppo);

            if (ppr.Status == PromptStatus.OK)
            {
                Transaction tr = doc.TransactionManager.StartTransaction();
                using (tr)
                {
                    try
                    {
                        Point3d            pt      = ppr.Value;
                        BlockTable         bt      = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
                        PromptEntityResult perXref = ed.GetEntity(peoXref);
                        if (perXref.Status == PromptStatus.OK)
                        {
                            BlockReference xrefRef = (BlockReference)tr.GetObject(perXref.ObjectId, OpenMode.ForRead);
                            if (xrefRef != null)
                            {
                                // If so, we check whether the block table record to which it refers is actually from an XRef

                                ObjectId         xrefId  = xrefRef.BlockTableRecord;
                                BlockTableRecord xrefBTR = (BlockTableRecord)tr.GetObject(xrefId, OpenMode.ForRead);
                                if (xrefBTR != null)
                                {
                                    if (xrefBTR.IsFromExternalReference)
                                    {
                                        // If so, then we prigrammatically select the object underneath the pick-point already used
                                        PromptNestedEntityOptions pneo = new PromptNestedEntityOptions("")
                                        {
                                            NonInteractivePickPoint    = perXref.PickedPoint,
                                            UseNonInteractivePickPoint = true
                                        };
                                        PromptNestedEntityResult pner = ed.GetNestedEntity(pneo);
                                        if (pner.Status == PromptStatus.OK)
                                        {
                                            try
                                            {
                                                ObjectId selId = pner.ObjectId;

                                                // Let's look at this programmatically-selected object, to see what it is
                                                DBObject obj = tr.GetObject(selId, OpenMode.ForRead);

                                                // If it's a polyline vertex, we need to go one level up to the polyline itself

                                                if (obj is PolylineVertex3d || obj is Vertex2d)
                                                {
                                                    selId = obj.OwnerId;
                                                }

                                                // We don't want to do anything at all for textual stuff, let's also make sure we are
                                                // dealing with an entity (should always be the case)

                                                if (obj is MText || obj is DBText || !(obj is Entity))
                                                {
                                                    return;
                                                }

                                                // Now let's get the name of the layer, to use later

                                                Entity           ent = (Entity)obj;
                                                LayerTableRecord ltr = (LayerTableRecord)tr.GetObject(ent.LayerId, OpenMode.ForRead);

                                                ed.WriteMessage("\nObject Selected is {0} on layer {1} in xref {2}.", selId.GetType(), ltr.Name, xrefBTR.Name);
                                            }
                                            catch
                                            {
                                                // A number of innocuous things could go wrong
                                                // so let's not worry about the details

                                                // In the worst case we are simply not trying
                                                // to replace the entity, so OFFSET will just
                                                // reject the selected Xref
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch
                    {
                        ed.WriteMessage("\nFailed in xrefSelect");
                    }
                    //BlockTableRecord ms = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                }
                tr.Commit();
            }
            else
            {
                ed.WriteMessage("Failed to find point of intrest.");
            }
        }
示例#18
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));
            }
        }
        private static bool EditLevelValue(ObjectId fflToEditId)
        {
            Document acDoc    = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument;
            Database acCurrDb = acDoc.Database;
            Editor   acEditor = acDoc.Editor;

            // Loop so user can edit multiple levels
            bool editingLevels = true;

            while (editingLevels)
            {
                // Prompt the user to select the level to edit
                PromptNestedEntityOptions nestedEntOpt = new PromptNestedEntityOptions("\nPick the level to edit (spacebar to finish):");
                PromptNestedEntityResult  nestedEntRes = acEditor.GetNestedEntity(nestedEntOpt);
                if (nestedEntRes.Status == PromptStatus.OK)
                {
                    using (Transaction acTrans = acCurrDb.TransactionManager.StartTransaction())
                    {
                        try
                        {
                            Entity ent = acTrans.GetObject(nestedEntRes.ObjectId, OpenMode.ForRead) as Entity;
                            if (ent.GetType() == typeof(MText))
                            {
                                MText levelToEdit = ent as MText;
                                if (levelToEdit.Layer != StyleNames.JPP_APP_Levels_Layer)
                                {
                                    acEditor.WriteMessage("\nSelected text is on the wrong layer!");
                                }
                                else
                                {
                                    // Fetch the Xdata for the MText - needed to update the vertex Xrecord on the outline
                                    Int32?vertexIndex = GetXdata(levelToEdit.Id);
                                    if (vertexIndex == null)
                                    {
                                        acEditor.WriteMessage("\nError, unable to retrieve level vertex index!");
                                    }
                                    else
                                    {
                                        // Prompt the user for the new level
                                        PromptDoubleResult newLevelValue = acEditor.GetDouble("\nEnter the new level: ");
                                        if (newLevelValue.Status == PromptStatus.OK)
                                        {
                                            double newLevel = newLevelValue.Value;
                                            // Call function to update the outline Xrecord of the block definition
                                            if (!UpdateOutline(fflToEditId, (Int32)vertexIndex, newLevel))
                                            {
                                                acEditor.WriteMessage("\nError, unable to update outline with edited level!");
                                            }
                                            // Update level text
                                            levelToEdit.UpgradeOpen();
                                            levelToEdit.Contents = newLevel.ToString("N3");
                                            levelToEdit.RecordGraphicsModified(true);
                                            // Update block graphics
                                            BlockReference fflToEdit = acTrans.GetObject(fflToEditId, OpenMode.ForWrite) as BlockReference;
                                            fflToEdit.RecordGraphicsModified(true);
                                        }
                                        else
                                        {
                                            acEditor.WriteMessage("\nInvalid level entered!");
                                        }
                                    }
                                    acTrans.Commit();
                                }
                            }
                        }
                        catch (Autodesk.AutoCAD.Runtime.Exception acException)
                        {
                            Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog
                                ("The following exception was caught: \n" + acException.Message
                                + "\nError editing level!\n");
                            acTrans.Abort();
                            return(false);
                        }
                    }
                }
                if (nestedEntRes.Status == PromptStatus.Cancel)
                {
                    editingLevels = false;
                }
            }
            return(true);
        }
        private static bool MoveLevelText(ObjectId fflToEditId)
        {
            Document acDoc    = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument;
            Database acCurrDb = acDoc.Database;
            Editor   acEditor = acDoc.Editor;


            // Loop so user can move multiple levels
            bool movingLevels = true;

            while (movingLevels)
            {
                // Prompt the user to select the level to move
                PromptNestedEntityOptions nestedEntOpt = new PromptNestedEntityOptions("\nPick the level to move (spacebar to finish):");
                PromptNestedEntityResult  nestedEntRes = acEditor.GetNestedEntity(nestedEntOpt);
                if (nestedEntRes.Status == PromptStatus.OK)
                {
                    using (Transaction acTrans = acCurrDb.TransactionManager.StartTransaction())
                    {
                        try
                        {
                            Entity ent = acTrans.GetObject(nestedEntRes.ObjectId, OpenMode.ForRead) as Entity;
                            if (ent.GetType() == typeof(MText))
                            {
                                MText textToEdit = ent as MText;

                                // All work will be done in the WCS so save the current UCS
                                // to restore later and set the UCS to WCS
                                Matrix3d CurrentUCS = acEditor.CurrentUserCoordinateSystem;
                                acEditor.CurrentUserCoordinateSystem = Matrix3d.Identity;

                                // Fetch the block reference for the outline
                                BlockReference fflToEdit = acTrans.GetObject(fflToEditId, OpenMode.ForWrite) as BlockReference;

                                // Calculate the corner coordinates. Text rotation will either be 0 to 90 degrees or
                                // 270 - 360 degrees.
                                // What happens if text is not in these ranges?
                                // Point3d textLocation = textToEdit.Location.TransformBy(fflToEdit.BlockTransform);
                                Point3d cornerPoint = CalculateCornerPoint(textToEdit, fflToEdit);

                                // Save the current text rotation angle for use later
                                double oldTextAngle = textToEdit.Rotation;

                                // Create a new UCS basesd on the corner point and the text rotation. The new UCS
                                // origin will be at the corner point and the X-axis aligned with the text direction.
                                if (!SwitchUCS(cornerPoint, textToEdit.Rotation))
                                {
                                    acEditor.WriteMessage("\nError, unable to create UCS!");
                                    acTrans.Abort();
                                    // Restore current UCS
                                    acEditor.CurrentUserCoordinateSystem = CurrentUCS;
                                    return(false);
                                }
                                // Prompt the user for the new position
                                Point3d            newLocation      = new Point3d(); // Declare here so in scope
                                AttachmentPoint    newJustification = new AttachmentPoint();
                                double             newAngle         = 0.0;
                                PromptPointResult  promptRes;
                                PromptPointOptions promptOpts = new PromptPointOptions("\nClick new text position: ");

                                promptRes = acEditor.GetPoint(promptOpts);
                                if (promptRes.Status != PromptStatus.OK)
                                {
                                    acEditor.WriteMessage("\nInvalid level text position picked - please try again.");
                                    acTrans.Abort();
                                    // Restore current UCS
                                    acEditor.CurrentUserCoordinateSystem = CurrentUCS;
                                    continue;
                                }
                                // If the text is justified TC or BC it's on a straight line so move to the other side, swap the
                                // justification and maintain the same rotation
                                if ((textToEdit.Attachment == AttachmentPoint.TopCenter) ||
                                    (textToEdit.Attachment == AttachmentPoint.BottomCenter))
                                {
                                    newAngle = Constants.Deg_0;
                                    if (promptRes.Value.Y > 0)
                                    {
                                        newLocation      = new Point3d(0.0, Constants.TextOffset, 0.0);
                                        newJustification = AttachmentPoint.BottomCenter;
                                    }
                                    else
                                    {
                                        newLocation      = new Point3d(0.0, -Constants.TextOffset, 0.0);
                                        newJustification = AttachmentPoint.TopCenter;
                                    }
                                }
                                else
                                {
                                    // Ask user if text needs to be rotated.
                                    PromptKeywordOptions promptKeyOpts = new PromptKeywordOptions("\nRotate text [Yes/No]: ", "Yes No");
                                    promptKeyOpts.Keywords.Default = "No";
                                    PromptResult promptRotRes = acEditor.GetKeywords(promptKeyOpts);
                                    if (promptRotRes.Status != PromptStatus.OK)
                                    {
                                        acEditor.WriteMessage("\nInvalid option - please try again.");
                                        acTrans.Abort();
                                        // Restore current UCS
                                        acEditor.CurrentUserCoordinateSystem = CurrentUCS;
                                        continue;
                                    }

                                    // Calculate the new location point and text justification
                                    if (promptRes.Value.X < 0)
                                    {
                                        if (promptRes.Value.Y < 0)
                                        {
                                            newLocation = new Point3d(-Constants.TextOffset * Math.Cos(Constants.Deg_45),
                                                                      -Constants.TextOffset * Math.Cos(Constants.Deg_45),
                                                                      0.0);
                                            if (promptRotRes.StringResult == "Yes")
                                            {
                                                if ((oldTextAngle >= Constants.Deg_0) && (oldTextAngle <= Constants.Deg_90))
                                                {
                                                    newJustification = AttachmentPoint.TopLeft;
                                                    newAngle         = Constants.Deg_270; // The UCS is origin currently lies at the corner point
                                                                                          // and the x-axis at the text rotation
                                                }
                                                else
                                                {
                                                    newJustification = AttachmentPoint.BottomRight;
                                                    newAngle         = Constants.Deg_90;
                                                }
                                            }
                                            else
                                            {
                                                newJustification = AttachmentPoint.TopRight;
                                                newAngle         = Constants.Deg_0;
                                            }
                                        }
                                        else
                                        {
                                            newLocation = new Point3d(-Constants.TextOffset * Math.Cos(Constants.Deg_45),
                                                                      Constants.TextOffset * Math.Cos(Constants.Deg_45),
                                                                      0.0);
                                            if (promptRotRes.StringResult == "Yes")
                                            {
                                                if ((oldTextAngle >= Constants.Deg_0) && (oldTextAngle <= Constants.Deg_90))
                                                {
                                                    newJustification = AttachmentPoint.TopRight;
                                                    newAngle         = Constants.Deg_270;
                                                }
                                                else
                                                {
                                                    newJustification = AttachmentPoint.BottomLeft;
                                                    newAngle         = Constants.Deg_90;
                                                }
                                            }
                                            else
                                            {
                                                newJustification = AttachmentPoint.BottomRight;
                                                newAngle         = Constants.Deg_0;
                                            }
                                        }
                                    }
                                    else if (promptRes.Value.X > 0)
                                    {
                                        if (promptRes.Value.Y < 0)
                                        {
                                            newLocation = new Point3d(Constants.TextOffset * Math.Cos(Constants.Deg_45),
                                                                      -Constants.TextOffset * Math.Sin(Constants.Deg_45),
                                                                      0.0);
                                            if (promptRotRes.StringResult == "Yes")
                                            {
                                                if ((oldTextAngle >= Constants.Deg_0) && (oldTextAngle <= Constants.Deg_90))
                                                {
                                                    newJustification = AttachmentPoint.BottomLeft;
                                                    newAngle         = Constants.Deg_270;
                                                }
                                                else
                                                {
                                                    newJustification = AttachmentPoint.TopRight;
                                                    newAngle         = Constants.Deg_90;
                                                }
                                            }
                                            else
                                            {
                                                newJustification = AttachmentPoint.TopLeft;
                                                newAngle         = Constants.Deg_0;
                                            }
                                        }
                                        else
                                        {
                                            newLocation = new Point3d(Constants.TextOffset * Math.Cos(Constants.Deg_45),
                                                                      Constants.TextOffset * Math.Cos(Constants.Deg_45),
                                                                      0.0);
                                            if (promptRotRes.StringResult == "Yes")
                                            {
                                                if ((oldTextAngle >= Constants.Deg_0) && (oldTextAngle <= Constants.Deg_90))
                                                {
                                                    newJustification = AttachmentPoint.BottomRight;
                                                    newAngle         = Constants.Deg_270;
                                                }
                                                else
                                                {
                                                    newJustification = AttachmentPoint.TopLeft;
                                                    newAngle         = Constants.Deg_90;
                                                }
                                            }
                                            else
                                            {
                                                newJustification = AttachmentPoint.BottomLeft;
                                                newAngle         = Constants.Deg_0;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        acEditor.WriteMessage("\nInvalid point picked - please try again.");
                                        acTrans.Abort();
                                        // Restore current UCS
                                        acEditor.CurrentUserCoordinateSystem = CurrentUCS;
                                        continue;
                                    }
                                }
                                // Translate these points to the WCS
                                ViewportTableRecord acVportTblRec = acTrans.GetObject(acEditor.ActiveViewportId, OpenMode.ForWrite) as ViewportTableRecord;
                                Matrix3d            jppMatrix     = new Matrix3d();
                                jppMatrix = Matrix3d.AlignCoordinateSystem(Point3d.Origin,
                                                                           Vector3d.XAxis,
                                                                           Vector3d.YAxis,
                                                                           Vector3d.ZAxis,
                                                                           acVportTblRec.Ucs.Origin,
                                                                           acVportTblRec.Ucs.Xaxis,
                                                                           acVportTblRec.Ucs.Yaxis,
                                                                           acVportTblRec.Ucs.Zaxis);
                                Point3d wcsNewLoc = newLocation.TransformBy(jppMatrix);
                                // Transform the new location to coordinates relative to the block reference
                                wcsNewLoc = wcsNewLoc.TransformBy(fflToEdit.BlockTransform.Inverse());
                                // wcsNewLoc = new Point3d(wcsNewLoc.X - fflToEdit.BlockTransform.Translation.X,
                                //                        wcsNewLoc.Y - fflToEdit.BlockTransform.Translation.Y,
                                //                        wcsNewLoc.Z - fflToEdit.BlockTransform.Translation.Z);

                                // Update the text
                                textToEdit.UpgradeOpen();
                                textToEdit.Attachment = newJustification;
                                textToEdit.Location   = wcsNewLoc;
                                textToEdit.Rotation   = newAngle;
                                // Update block graphics
                                // BlockReference fflToEdit = acTrans.GetObject(fflToEditId, OpenMode.ForWrite) as BlockReference;
                                fflToEdit = acTrans.GetObject(fflToEditId, OpenMode.ForWrite) as BlockReference;
                                fflToEdit.RecordGraphicsModified(true);

                                acTrans.Commit();
                                // Restore current UCS
                                acEditor.CurrentUserCoordinateSystem = CurrentUCS;
                            }
                        }
                        catch (Autodesk.AutoCAD.Runtime.Exception acException)
                        {
                            Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog
                                ("The following exception was caught: \n" + acException.Message
                                + "\nError moving level!\n");
                            acTrans.Abort();
                            return(false);
                        }
                    }
                }
                if (nestedEntRes.Status == PromptStatus.Cancel)
                {
                    movingLevels = false;
                }
            }
            return(true);
        }
示例#21
0
文件: xRef2.cs 项目: 15831944/EM
        getNestedEntityAndHighlight(Point3d pnt3d, BlockReference br, out FullSubentityPath path, out bool isClosed)
        {
            Entity ent = null;

            isClosed = false;
            path     = new FullSubentityPath();

            Editor ed = BaseObjs._editor;

            PromptNestedEntityOptions pneo = new PromptNestedEntityOptions("");

            pneo.NonInteractivePickPoint    = pnt3d;
            pneo.UseNonInteractivePickPoint = true;
            PromptNestedEntityResult pner = ed.GetNestedEntity(pneo);

            try
            {
                using (Transaction tr = BaseObjs.startTransactionDb())
                {
                    if (pner.Status == PromptStatus.OK)
                    {
                        ObjectId[] idsContainers = pner.GetContainers();
                        ObjectId   idSel         = pner.ObjectId;
                        int        len           = idsContainers.Length;

                        ObjectId[] idsRev = new ObjectId[len + 1];
                        //Reverse the "containers" list
                        for (int i = 0; i < len; i++)
                        {
                            ObjectId id = (ObjectId)idsContainers.GetValue(len - i - 1);
                            idsRev.SetValue(id, i);
                        }
                        //Now add the selected entity to the end of the array
                        idsRev.SetValue(idSel, len);

                        //Retrieve the sub-entity path for this entity
                        SubentityId idSubEnt = new SubentityId(SubentityType.Null, (IntPtr)0);
                        path = new FullSubentityPath(idsRev, idSubEnt);

                        ObjectId idX = (ObjectId)idsRev.GetValue(0);
                        ent = (Entity)tr.GetObject(idX, OpenMode.ForRead);

                        DBObject obj = idSel.GetObject(OpenMode.ForRead);

                        ObjectId idOwner   = ObjectId.Null;
                        DBObject objParent = null;

                        if (obj is PolylineVertex3d)
                        {
                            idOwner   = obj.OwnerId;
                            objParent = (Polyline3d)idOwner.GetObject(OpenMode.ForRead);
                            Polyline3d poly3d = (Polyline3d)obj;
                            poly3d.Highlight(path, false);
                            isClosed = poly3d.Closed;
                        }
                        else if (obj is Vertex2d)
                        {
                            idOwner   = obj.OwnerId;
                            objParent = (Polyline)idOwner.GetObject(OpenMode.ForRead);
                            Polyline poly = (Polyline)obj;
                            poly.Highlight(path, false);
                            isClosed = poly.Closed;
                        }
                        else if (obj is Polyline3d)
                        {
                            objParent = obj;
                            Polyline3d poly3d = (Polyline3d)obj;
                            poly3d.Highlight(path, false);
                            isClosed = poly3d.Closed;
                        }
                        else if (obj is Polyline)
                        {
                            objParent = obj;
                            Polyline poly = (Polyline)obj;
                            poly.Highlight(path, false);
                            isClosed = poly.Closed;
                        }
                        else if (obj is Arc)
                        {
                            objParent = obj;
                            Arc arc = (Arc)obj;
                            arc.Highlight(path, false);
                            isClosed = false;
                        }
                        else if (obj is MText || obj is DBText)
                        {
                            return(null);
                        }

                        ent = (Entity)objParent;
                    }
                    tr.Commit();
                }
            }
            catch (System.Exception ex)
            {
                BaseObjs.writeDebug(ex.Message + " xRef2.cs: line: 108");
            }
            return(ent);
        }
示例#22
0
        static public void Plan2HoePrSelHkBlockAndAtt()
        {
            try
            {
                if (!OpenHoePrPalette())
                {
                    return;
                }

                var      opts = Globs.TheHoePrOptions;
                Document doc  = Application.DocumentManager.MdiActiveDocument;

                using (DocumentLock m_doclock = doc.LockDocument())
                {
                    DocumentCollection dm = Application.DocumentManager;
                    if (doc == null)
                    {
                        return;
                    }
                    Editor ed = doc.Editor;
#if NEWSETFOCUS
                    doc.Window.Focus();
#else
                    Autodesk.AutoCAD.Internal.Utils.SetFocusToDwgView(); // previous 2014 AutoCAD - Versions
#endif

                    PromptNestedEntityResult per = ed.GetNestedEntity("\nHöhenkotenblock wählen: ");

                    if (per.Status == PromptStatus.OK)
                    {
                        using (var tr = doc.TransactionManager.StartTransaction())
                        {
                            DBObject       obj = tr.GetObject(per.ObjectId, OpenMode.ForRead);
                            BlockReference br  = obj as BlockReference;
                            if (br == null)
                            {
                                br = Plan2Ext.Globs.GetBlockFromItsSubentity(tr, per);
                                if (br == null)
                                {
                                    return;
                                }
                            }

                            opts.SetHKBlockname(br.Name);

                            tr.Commit();
                        }

                        per = ed.GetNestedEntity("\nHöhen-Attribut wählen: ");
                        if (per.Status != PromptStatus.OK)
                        {
                            return;
                        }
                        using (var tr = doc.TransactionManager.StartTransaction())
                        {
                            DBObject           obj = tr.GetObject(per.ObjectId, OpenMode.ForRead);
                            AttributeReference ar  = obj as AttributeReference;
                            if (ar == null)
                            {
                                return;
                            }

                            opts.SetHoehenAtt(ar.Tag);

                            tr.Commit();
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                Application.ShowAlertDialog(string.Format(CultureInfo.CurrentCulture, "Fehler in Plan2HoePrSelHkBlockAndAtt aufgetreten! {0}", ex.Message));
            }
        }
示例#23
0
        public void QB()
        {
            PromptEntityOptions selectCalloutOptions;
            PromptEntityResult  selectedCalloutResults;
            BlockReference      blkRef = null;
            string msAndKwds;
            string kwds;
            string verbose = "default";
            //string station;
            string lineNumber;

            //need editor to prompt user
            Editor ed = doc.Editor;

            //Prompt options for running line
            PromptNestedEntityOptions promptRunningLineOpt = new PromptNestedEntityOptions("\nSelect Running Line");

            promptRunningLineOpt.AllowNone = false;
            PromptNestedEntityResult runningLineResults = ed.GetNestedEntity(promptRunningLineOpt);

            if (runningLineResults.Status != PromptStatus.OK)
            {
                ed.WriteMessage("\nThe selected object is not running line");
                return;
            }

            //prompt for line number
            PromptStringOptions pStrOpts = new PromptStringOptions("\nEnter Line Number: ");

            pStrOpts.AllowSpaces = false;
            PromptResult pStrRes = ed.GetString(pStrOpts);

            //prompt user to select object only allow DFWT blocks
            PromptEntityOptions peo = new PromptEntityOptions("\nSelect DFWT Block");

            //check prompt results from user else return
            PromptEntityResult per = ed.GetEntity(peo);

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

            while (true)
            {
                //
                Transaction trans = database.TransactionManager.StartTransaction();
                using (trans)
                {
                    //access block table and create block table record
                    BlockTable       bt  = trans.GetObject(database.BlockTableId, OpenMode.ForRead) as BlockTable;
                    BlockTableRecord btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

                    //get the running line
                    Polyline runningLine = trans.GetObject(runningLineResults.ObjectId, OpenMode.ForRead) as Polyline;



                    //get the block reference
                    //Entity nestedBlockEntity = trans.GetObject(per.ObjectId, OpenMode.ForRead) as Entity;
                    //try {
                    //BlockReference blkRef = trans.GetObject(per.ObjectId, OpenMode.ForRead) as BlockReference;
                    //}
                    //catch
                    //{

                    //}

                    // ObjectId[] containerIds = per.GetContainers();

                    // foreach (ObjectId id in containerIds)
                    // {
                    //DBObject container = trans.GetObject(id, OpenMode.ForRead);

                    //if (container is BlockReference)
                    //{
                    //  blkRef = container as BlockReference;
                    //}

                    // }

                    try
                    {
                        Entity entity = trans.GetObject(per.ObjectId, OpenMode.ForRead) as Entity;
                        blkRef = trans.GetObject(per.ObjectId, OpenMode.ForRead) as BlockReference;
                    }
                    catch (InvalidCastException)
                    {
                        ed.WriteMessage("error when selecting block");
                    }



                    string str = String.Format("{0:0}", runningLine.GetDistAtPoint(blkRef.Position));
                    switch (str.Length)
                    {
                    case 1:
                        str = "0+0" + str;
                        break;

                    case 2:
                        str = "0+" + str;
                        break;

                    default:
                        str = str.Substring(0, str.Length - 2) + "+" + str.Substring(str.Length - 2);
                        break;
                    }

                    if (pStrRes.StringResult != "")
                    {
                        str = str + " LINE " + pStrRes.StringResult;
                    }

                    //
                    switch (blkRef.BlockName.ToUpper())
                    {
                    case "CPR":
                        msAndKwds = "\nSelect Type:[Drop Bucket/Tap pedestal/ Splitter Pedestal]";
                        kwds      = "'Drop Bucket' 'Tap Pedestal' 'Tap Splitter'";

                        selectCalloutOptions   = new PromptEntityOptions(msAndKwds, kwds);
                        selectedCalloutResults = ed.GetEntity(selectCalloutOptions);

                        switch (selectedCalloutResults.StringResult.ToUpper())
                        {
                        case "DROP BUCKET":
                            verbose = DROP_BUCKET;
                            break;

                        case "TAP PEDESTAL":
                            verbose = TAP_PED;
                            break;

                        default:
                            break;
                        }

                        break;

                    case "CPS":
                        break;

                    default:
                        ed.WriteMessage(blkRef.BlockName);
                        break;
                    }

                    //.string msAndKwds = "\nCPR or [A/B/C]";
                    //string kwds = "Apple Bob Cat";
                    //peo.SetMessageAndKeywords(msAndKwds, kwds);
                    //ed.WriteMessage(per1.StringResult);

/************************************************************************************************
 *			Prompting for callout box insertion point
 *			Set geometry for placing box
 ***********************************************************************************************/
                    PromptPointOptions pPtOpt = new PromptPointOptions("\nEnter Insertion Point");
                    PromptPointResult  pPtRes = ed.GetPoint(pPtOpt);
                    Point3d            insPt  = pPtRes.Value;

                    CoordinateSystem3d cs = Application.DocumentManager.MdiActiveDocument.Editor.CurrentUserCoordinateSystem.CoordinateSystem3d;
                    Plane plane           = new Plane(Point3d.Origin, cs.Zaxis);

                    //create polyline
                    Polyline rec = new Polyline();
                    rec.AddVertexAt(0, insPt.Convert2d(plane), 0, 0, 0);

                    bool Xdir = true;
                    bool Ydir = true;

                    if (insPt.X < blkRef.Position.X)
                    {
                        Xdir = false;
                    }
                    //

                    if (insPt.Y < blkRef.Position.Y)
                    {
                        Ydir = false;
                    }

                    if (Xdir)
                    {
                        if (Ydir)
                        {
                            //quadrant I
                            rec.AddVertexAt(0, new Point2d(insPt.X + recLength, insPt.Y), 0, 0, 0);
                            rec.AddVertexAt(1, new Point2d(insPt.X + recLength, insPt.Y + recWidth), 0, 0, 0);
                            rec.AddVertexAt(2, new Point2d(insPt.X, insPt.Y + recWidth), 0, 0, 0);
                        }
                        else
                        {
                            //quadrant IV
                            rec.AddVertexAt(0, new Point2d(insPt.X + recLength, insPt.Y), 0, 0, 0);
                            rec.AddVertexAt(1, new Point2d(insPt.X + recLength, insPt.Y - recWidth), 0, 0, 0);
                            rec.AddVertexAt(2, new Point2d(insPt.X, insPt.Y - recWidth), 0, 0, 0);
                        }
                    }
                    else
                    {
                        if (Ydir)
                        {
                            //quadrant II
                            rec.AddVertexAt(0, new Point2d(insPt.X - recLength, insPt.Y), 0, 0, 0);
                            rec.AddVertexAt(1, new Point2d(insPt.X - recLength, insPt.Y + recWidth), 0, 0, 0);
                            rec.AddVertexAt(2, new Point2d(insPt.X, insPt.Y + recWidth), 0, 0, 0);
                        }
                        else
                        {
                            //quadrant III
                            rec.AddVertexAt(0, new Point2d(insPt.X - recLength, insPt.Y), 0, 0, 0);
                            rec.AddVertexAt(1, new Point2d(insPt.X - recLength, insPt.Y - recWidth), 0, 0, 0);
                            rec.AddVertexAt(2, new Point2d(insPt.X, insPt.Y - recWidth), 0, 0, 0);
                        }
                    }
                    rec.Closed = true;
                    rec.SetDatabaseDefaults();

/************************************************************************************************
 *			Add object to block table and Commit Transaction
 *
 ***********************************************************************************************/

                    MText mt = new MText();
                    mt.Contents = verbose;

                    btr.AppendEntity(rec);
                    btr.AppendEntity(mt);

                    trans.AddNewlyCreatedDBObject(rec, true);
                    trans.AddNewlyCreatedDBObject(mt, true);
                    trans.Commit();
                }
            }
        }
示例#24
0
        public void drawTable()
        {
            try
            {
                //测试结束后 下边4行注释掉
                string[] sArr = new string[] { "表头1", "表头2", "表头3", "表头4" };
                setValue(10, sArr.Length, 2, 12, sArr);
                ExcelClass.selectRow = 5;
                ExcelClass.selectCol = 2;
                //
                Document doc = Application.DocumentManager.MdiActiveDocument;
                Database db  = doc.Database;
                Editor   ed  = doc.Editor;

                ObjectId currentTableId = createTable(db);//创建表格

                PromptNestedEntityResult entResult = ed.GetNestedEntity("\n请选择文字:");
                while (entResult.Status == PromptStatus.OK)
                {
                    using (Transaction trans = db.TransactionManager.StartTransaction())
                    {
                        Table    currentTable = trans.GetObject(currentTableId, OpenMode.ForRead) as Table;
                        DBObject obj          = entResult.ObjectId.GetObject(OpenMode.ForRead);
                        DBText   txtobj       = obj as DBText;
                        string   txt          = "";
                        if (txtobj != null)
                        {
                            txt = txtobj.TextString;
                        }
                        else
                        {
                            MText mtxt = obj as MText;
                            if (mtxt != null)
                            {
                                txt = mtxt.Contents;
                            }
                            else
                            {
                                txt = "";
                            }
                        }
                        if (txt.Length != 0)
                        {
                            ed.WriteMessage(txt);
                            //判断是否修改表格行数列数
                            currentTable.UpgradeOpen();//打开编辑
                            //如果选择行>=表格行数或者选择列>=表格列数,根据ExcelClass的行数列数重新定义表格行数列数
                            if (ExcelClass.selectCol >= currentTable.Columns.Count || ExcelClass.selectRow >= currentTable.Rows.Count)
                            {
                                currentTable.SetSize(ExcelClass.rowNum, ExcelClass.colNum);//根据行个数,列个数扩大
                                currentTable.SetRowHeight(ExcelClass.rowHeight);
                            }
                            //对应单元格设定为选择的文字
                            currentTable.Cells[ExcelClass.selectRow, ExcelClass.selectCol].TextString = txt;
                            currentTable.DowngradeOpen();//关闭编辑
                        }
                        else
                        {
                            ed.WriteMessage("\n您选择的不是文字,请重新选择!");
                        }
                        trans.Commit();
                    }
                    entResult = ed.GetNestedEntity("\n请选择文字:");
                }
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                Application.ShowAlertDialog("发生错误:" + ex.Message);
            }
        }
示例#25
0
        public static void AppendAttributeTest()
        {
            Document doc = AcAp.DocumentManager.MdiActiveDocument;

            Editor ed = doc.Editor;

            Database db = doc.Database;

            try
            {
                using (doc.LockDocument())
                {
                    using (Transaction tr = db.TransactionManager.StartTransaction())
                    {
                        BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;

                        BlockTableRecord currSp = tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;


                        PromptNestedEntityOptions pno =

                            new PromptNestedEntityOptions("\nSelect source attribute to append new attribute below this one >>");

                        PromptNestedEntityResult nres =

                            ed.GetNestedEntity(pno);

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

                        ObjectId id = nres.ObjectId;

                        Entity ent = (Entity)tr.GetObject(id, OpenMode.ForRead);

                        Point3d pnt = nres.PickedPoint;

                        ObjectId owId = ent.OwnerId;

                        AttributeReference attref = null;

                        if (id.ObjectClass.IsDerivedFrom(RXClass.GetClass(typeof(AttributeReference))))
                        {
                            attref = tr.GetObject(id, OpenMode.ForWrite) as AttributeReference;
                        }


                        BlockTableRecord btr = null;

                        BlockReference bref = null;

                        if (owId.ObjectClass.IsDerivedFrom(RXClass.GetClass(typeof(BlockReference))))
                        {
                            bref = tr.GetObject(owId, OpenMode.ForWrite) as BlockReference;

                            if (bref.IsDynamicBlock)
                            {
                                btr = tr.GetObject(bref.DynamicBlockTableRecord, OpenMode.ForRead) as BlockTableRecord;
                            }
                            else
                            {
                                btr = tr.GetObject(bref.BlockTableRecord, OpenMode.ForRead) as BlockTableRecord;
                            }
                        }

                        Point3d insPt = attref.Position.TransformBy(bref.BlockTransform);

                        btr.UpgradeOpen();

                        ObjectIdCollection bids = new ObjectIdCollection();

                        AttributeDefinition def = null;

                        foreach (ObjectId defid in btr)
                        {
                            if (defid.ObjectClass.IsDerivedFrom(RXClass.GetClass(typeof(AttributeDefinition))))
                            {
                                def = tr.GetObject(defid, OpenMode.ForRead) as AttributeDefinition;

                                if (def.Tag == attref.Tag)
                                {
                                    def.UpgradeOpen();

                                    bids.Add(defid);

                                    break;
                                }
                            }
                        }



                        IdMapping map = new IdMapping();

                        db.DeepCloneObjects(bids, btr.ObjectId, map, true);

                        ObjectIdCollection coll = new ObjectIdCollection();

                        AttributeDefinition attDef = null;

                        foreach (IdPair pair in map)
                        {
                            if (pair.IsPrimary)
                            {
                                Entity oent = (Entity)tr.GetObject(pair.Value, OpenMode.ForWrite);

                                if (oent != null)
                                {
                                    if (pair.Value.ObjectClass.IsDerivedFrom(RXClass.GetClass(typeof(AttributeDefinition))))
                                    {
                                        attDef = oent as AttributeDefinition;

                                        attDef.UpgradeOpen();

                                        attDef.SetPropertiesFrom(def as Entity);
                                        // add other properties from source attribute definition to suit here:

                                        attDef.Justify = def.Justify;

                                        attDef.Position = btr.Origin.Add(

                                            new Vector3d(attDef.Position.X, attDef.Position.Y - attDef.Height * 1.25, attDef.Position.Z)).TransformBy(Matrix3d.Identity

                                                                                                                                                      );

                                        attDef.Tag = "NEW_TAG";

                                        attDef.TextString = "New Prompt";

                                        attDef.TextString = "New Textstring";

                                        coll.Add(oent.ObjectId);
                                    }
                                }
                            }
                        }
                        btr.AssumeOwnershipOf(coll);

                        btr.DowngradeOpen();

                        attDef.Dispose();//optional

                        bref.RecordGraphicsModified(true);

                        tr.TransactionManager.QueueForGraphicsFlush();

                        doc.TransactionManager.FlushGraphics();//optional

                        ed.UpdateScreen();

                        tr.Commit();
                    }
                }
            }

            catch (System.Exception ex)
            {
                ed.WriteMessage(ex.Message + "\n" + ex.StackTrace);
            }
            finally
            {
                AcAp.ShowAlertDialog("Call command \"ATTSYNC\" manually");
            }
        }