2007年1月30日

Adding to the AutoCAD pickfirst set with .NET

Adding to the AutoCAD pickfirst set with .NET

Adding to the AutoCAD pickfirst set with .NET

Back in a much earlier post we looked at some code to access the pickfirst selection set.

I thought I'd now take a look at the more specific case of defining a command that adds entities into the current pickfirst selection set.

Here's some C# code I used to do this, with comments describing its behaviour. The most interesting point is that once we get the contents of the existing pickfirst set we then clear it and rehighlight the entities manually, to give the user a graphical clue of the previous contents.

using Autodesk.AutoCAD.ApplicationServices;

using Autodesk.AutoCAD.DatabaseServices;

using Autodesk.AutoCAD.EditorInput;

using Autodesk.AutoCAD.Runtime;


namespace SelectionTest

{

  public class PickfirstTestCmds

  {

    [CommandMethod("PFA", CommandFlags.Modal |

                          CommandFlags.UsePickSet |

                          CommandFlags.Redraw)

    ]

    public void AddToPickfirstSet()

    {

      Document doc =

        Application.DocumentManager.MdiActiveDocument;


      Editor ed = doc.Editor;


      // First let's get the initial pickfirst set

      PromptSelectionResult sr =

        ed.SelectImplied();


      // Create a collection containing the initial set

      //  (could have used an array, but a collection is

      //  easier in dynamic situations, such as this)

      ObjectIdCollection objs;

      if (sr.Status == PromptStatus.OK)

        objs =

          new ObjectIdCollection(

          sr.Value.GetObjectIds()

        );

      else

        objs = new ObjectIdCollection();


      // Clear the pickfirst set...

      ed.SetImpliedSelection(new ObjectId[0]);

      // ...but highlight the objects

      if (objs.Count > 0)

        HighlightEntities(objs);


      // No ask the user to select objects

      sr = ed.GetSelection();

      if (sr.Status == PromptStatus.OK)

      {

        // Add them all to the collection

        foreach (ObjectId obj in sr.Value.GetObjectIds())

        {

          objs.Add(obj);

        }

        // Dump the collection to an array

        ObjectId[] ids = new ObjectId[objs.Count];

        objs.CopyTo(ids, 0);


        // And finally set the pickfirst set

        ed.SetImpliedSelection(ids);

      }

    }


    // Highlight the entities by opening them one by one

    private void HighlightEntities(ObjectIdCollection objIds)

    {

      Document doc =

        Application.DocumentManager.MdiActiveDocument;

      Transaction tr =

        doc.TransactionManager.StartTransaction();

      using (tr)

      {

        foreach (ObjectId objId in objIds)

        {

          Entity ent =

            tr.GetObject(objId, OpenMode.ForRead)

            as Entity;

          if (ent != null)

            ent.Highlight();

        }

      }

    }

  }

}

留下您的评论