Search code examples
c#autocadautocad-plugin

Is there a way to get all Polylines in autocad (.dwg) using C#?


I don't want to select the specific polyline in runtime. Is there a way to directly get all polylines in .dwg file using C# without selection during runtime ? AutoCAD has a command called DATAEXTRACTION to get related information for different objects (e.g polyline, circle, point ...etc), but I don't know if it can be called and used in C#.

FYI: Sample code to get specific polyline during runtime from
http://through-the-interface.typepad.com/through_the_interface/2007/04/iterating_throu.html:

Transaction tr = db.TransactionManager.StartTransaction();
using (tr)
{
   DBObject obj = tr.GetObject(per.ObjectId, OpenMode.ForRead);
   Polyline lwp = obj as Polyline; // Get the selected polyline during runtime
   ...
}

Solution

  • Sounds like you're looking for something like this. Remove the layer criteria if not needed.

    public ObjectIdCollection SelectAllPolylineByLayer(string sLayer)
    {
        Document oDwg = Application.DocumentManager.MdiActiveDocument; 
        Editor oEd = oDwg.Editor;
    
        ObjectIdCollection retVal = null;
    
        try {
            // Get a selection set of all possible polyline entities on the requested layer
            PromptSelectionResult oPSR = null;
    
            TypedValue[] tvs = new TypedValue[] {
                new TypedValue(Convert.ToInt32(DxfCode.Operator), "<and"),
                new TypedValue(Convert.ToInt32(DxfCode.LayerName), sLayer),
                new TypedValue(Convert.ToInt32(DxfCode.Operator), "<or"),
                new TypedValue(Convert.ToInt32(DxfCode.Start), "POLYLINE"),
                new TypedValue(Convert.ToInt32(DxfCode.Start), "LWPOLYLINE"),
                new TypedValue(Convert.ToInt32(DxfCode.Start), "POLYLINE2D"),
                new TypedValue(Convert.ToInt32(DxfCode.Start), "POLYLINE3d"),
                new TypedValue(Convert.ToInt32(DxfCode.Operator), "or>"),
                new TypedValue(Convert.ToInt32(DxfCode.Operator), "and>")
            };
    
            SelectionFilter oSf = new SelectionFilter(tvs);
    
            oPSR = oEd.SelectAll(oSf);
    
            if (oPSR.Status == PromptStatus.OK) {
                retVal = new ObjectIdCollection(oPSR.Value.GetObjectIds());
            } else {
                retVal = new ObjectIdCollection();
            }
        } catch (System.Exception ex) {
            ReportError(ex);
        }
    
        return retVal;
    }