Recent Posts

Pages: [1] 2 3 ... 10
1
Events / Re: EventHandler for Entity Selection
« Last post by keithbrown on February 26, 2014, 01:34:12 PM »
This is an older thread but i thought i would post anyway in case anyone heading this way wanted a solution.  As BlackBox said the event that you want is the ImpliedSelectionChanged event.  In the code snippet below I am checking the implied selection to see if a single object is selected.

Code: [Select]
       private void DocumentManager_ImpliedSelectionChanged(object sender, EventArgs e)
        {
            Document document = Application.DocumentManager.MdiActiveDocument;
            PromptSelectionResult promptSelectionResult = document.Editor.SelectImplied();

            // If no objects are selected then do something and return
            if (promptSelectionResult.Value == null)
            {
                // Do Something
                return;
            }

            // If more than one object is selected then do something
            if (promptSelectionResult.Value.Count > 1)
            {
                // Do Something
                return;
            }

            // At this point only one object should be selected.
            // Do Something             

 
            }

And below is the code that i would use to initiate the event handler

Code: [Select]
var document = Application.DocumentManager.MdiActiveDocument;
document.ImpliedSelectionChanged += DocumentManager_ImpliedSelectionChanged;

I just make sure to setup the event handler in each document as it is created and remove it as each document is destroyed.
2
Dimensions / Create leader with mtext
« Last post by fixo on January 28, 2014, 12:29:10 PM »
        C#
Code: [Select]
         [CommandMethod("LDM")]
        public void CreateLeaderWithMText()
        {

            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            Database db = doc.Database;

            PromptPointOptions prOpt = new PromptPointOptions("\nSelect first point ");
            PromptPointResult es = ed.GetPoint(prOpt);
            if (es.Status != PromptStatus.OK)
            {
                if (es.Status == PromptStatus.Cancel)
                {
                    ed.WriteMessage("\nInterrupted by user"); return;
                }
                else
                {
                    ed.WriteMessage("\nError on specifying a point"); return;
                }
            }
            Point3d p1 = es.Value;
            prOpt = new PromptPointOptions("\nSelect Second point ");
            prOpt.UseBasePoint = true;
            prOpt.UseDashedLine = true;
            prOpt.BasePoint = p1;
            es = ed.GetPoint(prOpt);
            if (es.Status != PromptStatus.OK)
            {
                if (es.Status == PromptStatus.Cancel)
                {
                    ed.WriteMessage("\nInterrupted by user"); return;
                }
                else
                {
                    ed.WriteMessage("\nError on specifying a point"); return;
                }
            }
            Point3d p2 = es.Value;

            Transaction tr = doc.TransactionManager.StartTransaction();

            using (tr)
            {

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

                ObjectId mtextId = ObjectId.Null;
                MText mtx = new MText();
                mtx.SetDatabaseDefaults();
                mtx.Contents = "TEXT STRING\\PNEW STRING";
                mtx.Location = p2;
                mtextId = btr.AppendEntity(mtx);
                tr.AddNewlyCreatedDBObject(mtx, true);
                // mtx.DowngradeOpen();
                ObjectId leaderId = ObjectId.Null;
                Leader ld = new Leader();
                ld.AppendVertex(p1);
                ld.AppendVertex(p2);
                ld.SetDatabaseDefaults();
                leaderId = btr.AppendEntity(ld);

                ld.Annotation = mtextId;
                if (p2.X < p1.X)
                {
                    mtx.Attachment = AttachmentPoint.MiddleRight;
                    mtx.Location = p2;
                }
                ld.EvaluateLeader();

                tr.AddNewlyCreatedDBObject(ld, true);
                tr.Commit();
            }
        }
VB.NET
Code: [Select]
<CommandMethod("LDM")> _
        Public Sub CreateLeaderWithMText()

            Dim doc As Document = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument
            Dim ed As Editor = doc.Editor
            Dim db As Database = doc.Database

            Dim prOpt As New PromptPointOptions(vbLf & "Select first point ")
            Dim es As PromptPointResult = ed.GetPoint(prOpt)
            If es.Status <> PromptStatus.OK Then
                If es.Status = PromptStatus.Cancel Then
                    ed.WriteMessage(vbLf & "Interrupted by user")
                    Return
                Else
                    ed.WriteMessage(vbLf & "Error on specifying a point")
                    Return
                End If
            End If
            Dim p1 As Point3d = es.Value
            prOpt = New PromptPointOptions(vbLf & "Select Second point ")
            prOpt.UseBasePoint = True
            prOpt.UseDashedLine = True
            prOpt.BasePoint = p1
            es = ed.GetPoint(prOpt)
            If es.Status <> PromptStatus.OK Then
                If es.Status = PromptStatus.Cancel Then
                    ed.WriteMessage(vbLf & "Interrupted by user")
                    Return
                Else
                    ed.WriteMessage(vbLf & "Error on specifying a point")
                    Return
                End If
            End If
            Dim p2 As Point3d = es.Value

            Dim tr As Transaction = doc.TransactionManager.StartTransaction()

            Using tr

                Dim btr As BlockTableRecord = DirectCast(tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite), BlockTableRecord)

                Dim mtextId As ObjectId = ObjectId.Null
                Dim mtx As New MText()
                mtx.SetDatabaseDefaults()
                mtx.Contents = "TEXT STRING\PNEW STRING"
                mtx.Location = p2
                mtextId = btr.AppendEntity(mtx)
                tr.AddNewlyCreatedDBObject(mtx, True)
                ' mtx.DowngradeOpen();
                Dim leaderId As ObjectId = ObjectId.Null
                Dim ld As New Leader()
                ld.AppendVertex(p1)
                ld.AppendVertex(p2)
                ld.SetDatabaseDefaults()
                leaderId = btr.AppendEntity(ld)

                ld.Annotation = mtextId
                If p2.X < p1.X Then
                    mtx.Attachment = AttachmentPoint.MiddleRight
                    mtx.Location = p2
                End If
                ld.EvaluateLeader()

                tr.AddNewlyCreatedDBObject(ld, True)
                tr.Commit()
            End Using
        End Sub
3
Layouts and printing / Re: Find out which paper size to use
« Last post by frits432 on December 24, 2013, 02:47:55 PM »
layout.Extents;
4
Layouts and printing / Re: zoom and rotate viewport
« Last post by frits432 on December 24, 2013, 02:45:06 PM »
Still need help with Viewport View settings?
5
Polylines / Re: Fillet
« Last post by fixo on December 17, 2013, 07:26:51 PM »
There is another way if somebody want to use it
Code: [Select]
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports Autodesk.AutoCAD.ApplicationServices
Imports Autodesk.AutoCAD.DatabaseServices
Imports Autodesk.AutoCAD.Runtime
Imports Autodesk.AutoCAD.Geometry
Imports Autodesk.AutoCAD.EditorInput
Imports System.Runtime.InteropServices
<Assembly: CommandClass(GetType(VBTemplate.PlineCommands))>
Namespace VBTemplate


    Public Class PlineCommands
        'ads_queueexpr
        ' A2010
        ' A2014
        <DllImport("acad.exe", CharSet:=CharSet.Unicode, CallingConvention:=CallingConvention.Cdecl, EntryPoint:="ads_queueexpr")> _
        Private Shared Function ads_queueexpr(command As Byte()) As Integer
        End Function
        '<DllImport("accore.dll", CharSet:=CharSet.Unicode, CallingConvention:=CallingConvention.Cdecl, EntryPoint:="ads_queueexpr")> _
       
        <CommandMethod("opl")> _
        Public Shared Sub TestDrawPolyExm()
            Dim doc As Document = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument

            Dim ed As Editor = doc.Editor

            Dim db As Database = HostApplicationServices.WorkingDatabase

            Dim plineId As ObjectId = ObjectId.Null

            Using doclock As DocumentLock = doc.LockDocument()

                doc.TransactionManager.EnableGraphicsFlush(True)

                Dim cme As Object = Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("cmdecho")

                Using tr As Transaction = db.TransactionManager.StartTransaction()
                    ' Select an object

                    Try
                        Dim btr As BlockTableRecord = TryCast(tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite), BlockTableRecord)

                        Dim plan As New Plane(Point3d.Origin, Vector3d.ZAxis)

                        Dim pts As New Point3dCollection()

                        Dim pline As New Polyline()

                        Dim fstPnt As Point3d = ed.GetPoint(vbLf & "Pick first point: ").Value

                        pts.Add(fstPnt)

                        While True
                            Dim ppo As New PromptPointOptions(vbLf & "Pick Next Point (or hit ""Enter"" to Exit): ")

                            ppo.AllowNone = True

                            Dim ppr As PromptPointResult

                            ppo.UseDashedLine = True

                            ppo.UseBasePoint = True

                            ppo.BasePoint = fstPnt

                            ppr = ed.GetPoint(ppo)

                            If (Not (ppr.Status = PromptStatus.OK)) Or (ppr.Status = PromptStatus.None) Then
                                Exit While
                            End If

                            Dim endPnt As Point3d = ppr.Value

                            pts.Add(endPnt)

                            ed.DrawVector(fstPnt, endPnt, 1, True)

                            fstPnt = endPnt
                        End While

                        Dim i As Integer = 0

                        For i = 0 To pts.Count - 1

                            pline.AddVertexAt(i, pts(i).Convert2d(plan), 0, 0, 0)
                        Next
                        pline.Closed = True

                        pline.ColorIndex = 5

                        plineId = btr.AppendEntity(pline)

                        tr.AddNewlyCreatedDBObject(pline, True)

                        tr.TransactionManager.QueueForGraphicsFlush()

                        ed.SetImpliedSelection(New ObjectId() {plineId})

                        Dim res As PromptSelectionResult = ed.SelectImplied()

                        If res.Status <> PromptStatus.OK Then
                            Return
                        End If


                        Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("cmdecho", 0)

                        Dim uEncode As New UnicodeEncoding()

                        ads_queueexpr(uEncode.GetBytes("(command ""_.FILLETRAD""" & """10""" & ")"))
                        ' <--  set fillet radius to your needs
                        uEncode = New UnicodeEncoding()

                        ads_queueexpr(uEncode.GetBytes("(command ""_.FILLET""" & """_P""" & """_L""" & ")"))

                        uEncode = New UnicodeEncoding()

                        ads_queueexpr(uEncode.GetBytes("(command ""_ZOOM"" ""_OB""" & """_L""" & """""" & ") "))

                        Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("cmdecho", cme)

                        ed.UpdateScreen() 'optional

                        doc.TransactionManager.FlushGraphics()

                        tr.Commit()

                        ed.Regen()
                    Catch ex As System.Exception
                        Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage(ex.Message)
                    Finally

                        Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("cmdecho", cme)
                    End Try
                End Using
            End Using
        End Sub
    End Class
End Namespace
C#_________________
Code: [Select]
       //ads_queueexpr
        [DllImport("acad.exe", CharSet = CharSet.Unicode,
CallingConvention = CallingConvention.Cdecl,
EntryPoint = "ads_queueexpr")]// A2010
//        [DllImport("accore.dll", CharSet = CharSet.Unicode,
//CallingConvention = CallingConvention.Cdecl,
//EntryPoint = "ads_queueexpr")]// A2014
        extern static private int ads_queueexpr(byte[] command);
        [CommandMethod("opl")]
        public static void TestDrawPolyExm()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Editor ed = doc.Editor;

            Database db = HostApplicationServices.WorkingDatabase;

            ObjectId plineId = ObjectId.Null;

            using (DocumentLock doclock = doc.LockDocument())
            {
                doc.TransactionManager.EnableGraphicsFlush(true);

                object cme = Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("cmdecho");

                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    // Select an object

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

                        Plane plan = new Plane(Point3d.Origin, Vector3d.ZAxis);

                        Point3dCollection pts = new Point3dCollection();

                        Polyline pline = new Polyline();

                        Point3d fstPnt = ed.GetPoint("\nPick first point: ").Value;

                        pts.Add(fstPnt);

                        while (true)
                        {
                            PromptPointOptions ppo = new PromptPointOptions("\nPick Next Point (or hit \"Enter\" to Exit): ");

                            ppo.AllowNone = true;

                            PromptPointResult ppr;

                            ppo.UseDashedLine = true;

                            ppo.UseBasePoint = true;

                            ppo.BasePoint = fstPnt;

                            ppr = ed.GetPoint(ppo);

                            if ((!(ppr.Status == PromptStatus.OK)) | (ppr.Status == PromptStatus.None))
                            {
                                break;
                            }

                            Point3d endPnt = ppr.Value;

                            pts.Add(endPnt);

                            ed.DrawVector(fstPnt, endPnt, 1, true);

                            fstPnt = endPnt;
                        }

                        int i = 0;

                        for (i = 0; i < pts.Count; i++)
                        {
                            pline.AddVertexAt(i, pts[i].Convert2d(plan), 0, 0, 0);

                        }
                        pline.Closed = true;

                        pline.ColorIndex = 5;

                       plineId= btr.AppendEntity(pline);

                        tr.AddNewlyCreatedDBObject(pline, true);

                        tr.TransactionManager.QueueForGraphicsFlush();

                        ed.SetImpliedSelection(new ObjectId[] { plineId });

                        PromptSelectionResult res = ed.SelectImplied();

                        if (res.Status != PromptStatus.OK)
                        {
                            return;
                        }
                       
                       
                        Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("cmdecho", 0);
                     
                        UnicodeEncoding uEncode = new UnicodeEncoding();

                        ads_queueexpr(uEncode.GetBytes("(command \"_.FILLETRAD\"" + "\"10\"" + ")"));// <--  set fillet radius to your needs

                        uEncode = new UnicodeEncoding();

                        ads_queueexpr(uEncode.GetBytes("(command \"_.FILLET\"" + "\"_P\"" + "\"_L\""  + ")"));

                        uEncode = new UnicodeEncoding();

                        ads_queueexpr(uEncode.GetBytes("(command \"_ZOOM\" \"_OB\"" + "\"_L\"" + "\"\"" + ") "));

                        Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("cmdecho", cme);
                       
                        ed.UpdateScreen();

                        doc.TransactionManager.FlushGraphics();

                        tr.Commit();

                        ed.Regen();
                    }
                    catch (System.Exception ex)
                    {
                        Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage(ex.Message);
                    }
                    finally
                    {
                        Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("cmdecho", cme);
               
                    }
                }
            }
        }
6
Selection sets / Polar increment of objects
« Last post by fixo on December 13, 2013, 02:41:11 PM »
     Code tested in A2014, in other release you probably may change the sorting alghoritm
     Editor handler function was brrowed from Gilles Chanteau
      VB.NET code
Code: [Select]
   <CommandMethod("TOCC")> _
        Public Sub SelectCirclesObjectsByCrossingWindow()
            Dim doc As Document = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument
            Dim db As Database = doc.Database
            Dim ed As Editor = doc.Editor
            Dim ent As Entity
            Dim plan As Plane = New Plane
            '  Dim points As Point3dCollection = New Point3dCollection
            Dim points As List(Of Point3d) = New List(Of Point3d)
            AddHandler ed.SelectionAdded, AddressOf ed_CircleSelectionAdded
            Try
                '' Create a crossing window from picked corner points
                Dim ppo As New PromptPointOptions(vbLf & "Select first corner: ")

                ppo.AllowNone = False

                Dim ppr As PromptPointResult = ed.GetPoint(ppo)

                If ppr.Status <> PromptStatus.OK Then

                    Return

                End If

                Dim pt1 As Point3d = ppr.Value

                Dim pco As New PromptCornerOptions(vbLf & "Select second clip corner: ", pt1)

                ppr = ed.GetCorner(pco)

                If ppr.Status <> PromptStatus.OK Then

                    Return
                End If

                Dim pt2 As Point3d = ppr.Value

                Dim res As PromptSelectionResult

                res = ed.SelectCrossingWindow(pt1, pt2)

                '' If the prompt status is OK, objects were selected
                If res.Status <> PromptStatus.OK Then Return

                Dim sset As SelectionSet = res.Value
                If sset.Count > 0 Then

                    Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("Number of objects selected: " & _
                                                sset.Count.ToString())
                Else
                    Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("Number of objects selected: 0")
                    Return
                End If
                Dim tr As Transaction = doc.TransactionManager.StartTransaction
                Using tr
                    For Each sobj As SelectedObject In sset
                        ent = TryCast(tr.GetObject(sobj.ObjectId, OpenMode.ForRead), Entity)
                        If ent Is Nothing Then Return
                        Dim circ As Circle = TryCast(ent, Circle)
                        If circ Is Nothing Then Return
                        plan = circ.GetPlane
                        points.Add(circ.Center)
                    Next


                    Dim cp As Point3d = New Point3d( _
                                                         points.Average(Function(x) Convert.ToDouble(x.X)), _
                                                       points.Average(Function(x) Convert.ToDouble(x.Y)), _
                                                       points.Average(Function(x) Convert.ToDouble(x.Z)))
                    cp.GetVectorTo(Point3d.Origin).AngleOnPlane(plan)

                    Dim sorted = points.OrderBy(Function(x) cp.GetVectorTo(x).AngleOnPlane(plan))
                    '' debug only
                    '' Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(String.Format("{0:f2},{1:f2},{2:f2} ", cp.X, cp.Y, cp.Z))
                    Dim cr As Circle = New Circle(cp, Vector3d.ZAxis, 10)
                    cr.ColorIndex = 130

                    Dim btr As BlockTableRecord = tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite)
                    btr.AppendEntity(cr)
                    tr.AddNewlyCreatedDBObject(cr, True)
                    Dim i As Integer = 1
                    For Each p As Point3d In sorted
                        Dim mtxt As MText = New MText
                        mtxt.Location = p
                        mtxt.Attachment = AttachmentPoint.MiddleCenter
                        mtxt.Contents = i.ToString
                        mtxt.ColorIndex = 1
                        btr.AppendEntity(mtxt)
                        tr.AddNewlyCreatedDBObject(mtxt, True)
                        i += 1
                    Next
                    tr.Commit()
                End Using

            Catch ex As Autodesk.AutoCAD.Runtime.Exception
                Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(ex.ErrorStatus)
            Finally
                RemoveHandler ed.SelectionAdded, AddressOf ed_CircleSelectionAdded
            End Try
        End Sub

        Private Shared Sub ed_CircleSelectionAdded(sender As Object, e As SelectionAddedEventArgs)
            Dim ids As ObjectId() = e.AddedObjects.GetObjectIds()
            For i As Integer = 0 To ids.Length - 1
                If Not ids(i).ObjectClass.IsDerivedFrom(RXClass.GetClass(GetType(Circle))) Then
                    e.Remove(i)
                End If
            Next
        End Sub


      C# code
Code: [Select]
        [CommandMethod("TOCC")]
        public void SelectCirclesObjectsByCrossingWindow()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Database db = doc.Database;

            Editor ed = doc.Editor;

            Entity ent = default(Entity);

            Plane plan = new Plane();

            List<Point3d> points = new List<Point3d>();
            // add editor SelectionAdded handler for sure the user selected circles only
            ed.SelectionAdded += ed_CircleSelectionAdded;
            try
            {
                // Create a crossing window from picked corner points
                PromptPointOptions ppo = new PromptPointOptions("\nSelect first corner: \n");

                ppo.AllowNone = false;

                PromptPointResult ppr = ed.GetPoint(ppo);


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

                }

                Point3d pt1 = ppr.Value;

                PromptCornerOptions pco = new PromptCornerOptions("\nSelect second clip corner: \n", pt1);

                ppr = ed.GetCorner(pco);


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

                Point3d pt2 = ppr.Value;

                PromptSelectionResult res = default(PromptSelectionResult);

                res = ed.SelectCrossingWindow(pt1, pt2);
                // If the prompt status is OK, objects were selected
                if (res.Status != PromptStatus.OK)
                    return;

                SelectionSet sset = res.Value;
                // display inform message for user, may be removed
                if (sset.Count > 0)
                {
                    Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("Number of objects selected: " + sset.Count.ToString());
                }
                else
                {
                    Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("Nothing selected!");

                    return;
                }
                // start transaction
                Transaction tr = doc.TransactionManager.StartTransaction();

                using (tr)
                {
                    foreach (SelectedObject sobj in sset)
                    {
                        ent = tr.GetObject(sobj.ObjectId, OpenMode.ForRead) as Entity;

                        if (ent == null) return;

                        Circle circ = ent as Circle;

                        if (circ == null) return;

                        plan = circ.GetPlane();

                        points.Add(circ.Center);
                    }


                    Point3d cp =
                        new Point3d(
                        points.Average(x => Convert.ToDouble(x.X)),
                        points.Average(x => Convert.ToDouble(x.Y)),
                        points.Average(x => Convert.ToDouble(x.Z))
                        );

                    cp.GetVectorTo(Point3d.Origin).AngleOnPlane(plan);

                    dynamic sorted = points.OrderBy(x => cp.GetVectorTo(x).AngleOnPlane(plan));
                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                    // debug only, commented
                    // Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(String.Format("{0:f2},{1:f2},{2:f2} ", cp.X, cp.Y, cp.Z))
                    //Circle cr = new Circle(cp, Vector3d.ZAxis, 10);
                    //cr.ColorIndex = 130;                   
                    //btr.AppendEntity(cr);
                    //tr.AddNewlyCreatedDBObject(cr, true);
                    // set increment starting number:
                    int i = 1;
                    foreach (Point3d p in sorted)
                    {
                        MText mtxt = new MText();
                        mtxt.SetDatabaseDefaults();
                        //_______________________
                        // you have put appropriate text size here instead:
                        mtxt.TextHeight = db.Dimtxt;
                        //__________________________
                        mtxt.Location = p;
                        mtxt.Attachment = AttachmentPoint.MiddleCenter;
                        mtxt.Contents = i.ToString();
                        mtxt.ColorIndex = 1;
                        btr.AppendEntity(mtxt);
                        tr.AddNewlyCreatedDBObject(mtxt, true);
                        // increase a number
                        i += 1;
                    }
                    // commit transaction
                    tr.Commit();
                }// end of using is meant to dispose transaction

            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(ex.ErrorStatus.ToString());
            }
            finally
            {
                // remove editor SelectionAdded haandler at the end
                ed.SelectionAdded -= ed_CircleSelectionAdded;
            }
        }

        private static void ed_CircleSelectionAdded(object sender, SelectionAddedEventArgs e)
        {
            ObjectId[] ids = e.AddedObjects.GetObjectIds();
            for (int i = 0; i <= ids.Length - 1; i++)
            {
                if (!ids[i].ObjectClass.IsDerivedFrom(RXClass.GetClass(typeof(Circle))))
                {
                    e.Remove(i);
                }
            }
        }
7
Layouts and printing / Find out which paper size to use
« Last post by madmat on December 11, 2013, 06:08:14 PM »
Hi,
I'm looking for a way to get the maximum size (Width & Length) of the boundary enclosing all the objects on the active layout (Autocad 2014).
My objective is to write a code that will automatically plot my layout, selecting the right paper size according to the real size of the objects on this Layout.

If anybody has some idea...
Thanks for your help in advance.
8
Cumulative and total sum of the distances indicated with selected points
Code: [Select]
        <CommandMethod("cud")> _
        Public Shared Sub CumulDist()
            Dim doc As Document = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument

            Dim db As Database = doc.Database

            Dim points As New Point3dCollection()

            Dim ed As Editor = doc.Editor

            Dim ptres2 As PromptPointResult
            Dim lst As List(Of Point3d)
            Dim cd As Double = 0
            Dim pto1 As New PromptPointOptions(vbLf & "Select first point, or press Enter to close: ")

            Dim ptres1 As PromptPointResult = ed.GetPoint(pto1)

            If ptres1.Status = PromptStatus.OK Then
                lst = New List(Of Point3d)
                Dim basept As Point3d = ptres1.Value
                lst.Add(basept)
                points.Add(basept)

                Do
                    Dim pto2 As New PromptPointOptions(vbLf & "Next point or [Enter to exit]: ", "Enter")

                    pto2.Keywords.[Default] = "Enter"

                    pto2.BasePoint = basept

                    pto2.UseBasePoint = True

                    ptres2 = ed.GetPoint(pto2)

                    basept = ptres2.Value

                    If ptres2.Status <> PromptStatus.Keyword Then
                        lst.Add(basept)
                        points.Add(basept)
                    End If
                   
                    If lst.Count = 2 Then
                        Dim td As Double = lst(0).DistanceTo(lst(1))
                        cd += td
                        ed.WriteMessage("Latest distance = {0:f3};  Cumulative distance = {1:f3}", td, cd)
                        lst.RemoveAt(0)
                    End If
                Loop While ptres2.Status <> PromptStatus.Keyword
                ed.WriteMessage("Total distance = {0:f3}", cd)

            End If
        End Sub

C#
Code: [Select]
        [CommandMethod("cud")]
        public static void CumulDist()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Database db = doc.Database;

            Point3dCollection points = new Point3dCollection();

            Editor ed = doc.Editor;

            PromptPointResult ptres2 = default(PromptPointResult);

            List<Point3d> lst = default(List<Point3d>);

            double cd = 0;

            PromptPointOptions pto1 = new PromptPointOptions("\nSelect first point, or press Enter to close: ");

            PromptPointResult ptres1 = ed.GetPoint(pto1);

            if (ptres1.Status == PromptStatus.OK)
            {
                lst = new List<Point3d>();

                Point3d basept = ptres1.Value;

                lst.Add(basept);

                points.Add(basept);

                do
                {
                    PromptPointOptions pto2 = new PromptPointOptions("\nNext point or [Enter to exit]: ", "Enter");

                    pto2.Keywords.Default = "Enter";

                    pto2.BasePoint = basept;

                    pto2.UseBasePoint = true;

                    ptres2 = ed.GetPoint(pto2);

                    basept = ptres2.Value;

                    if (ptres2.Status != PromptStatus.Keyword)
                    {
                        lst.Add(basept);
                        points.Add(basept);
                    }

                    if (lst.Count == 2)
                    {
                        double td = lst[0].DistanceTo(lst[1]);
                        cd += td;
                        ed.WriteMessage("\nLatest distance = {0:f3};  Cumulative distance = {1:f3}", td, cd);
                        lst.RemoveAt(0);
                    }
                } while (ptres2.Status != PromptStatus.Keyword);
                ed.WriteMessage("\nTotal distance = {0:f3}", cd);
            }
        }
9
Blocks / Synchronize attributes (ATTSYNC)
« Last post by (gile) on November 23, 2013, 05:43:42 PM »
Hi,

This is a simple and 'brute force' method to mimic the ATTSYNC command. It erases the existing AttributeReferences from the inserted BlockReferences and adds them new ones from the BlockTableRecord AttributeDefinitions.

The SynchronizeAttributes() method is defined as an extension method for the BlockTableRecord type so that it can be called as an instance method of this type.
Using example (assuming btr is a BlocTableRecord instance) : btr.SynchronizeAttributes()

<EDIT: works now w/ mtext attributes>
<EDIT: corrected an issue w/ attributes in dynamic blocks>
<EDIT: corrected an issue w/ constant attributes>

 C# code
Code: [Select]
using System;
using System.Collections.Generic;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Runtime;
using AcRx = Autodesk.AutoCAD.Runtime;

namespace Autodesk.AutoCAD.DatabaseServices
{
    public static class ExtensionMethods
    {
        static RXClass attDefClass = RXClass.GetClass(typeof(AttributeDefinition));

        public static void SynchronizeAttributes(this BlockTableRecord target)
        {
            if (target == null)
                throw new ArgumentNullException("target");

            Transaction tr = target.Database.TransactionManager.TopTransaction;
            if (tr == null)
                throw new AcRx.Exception(ErrorStatus.NoActiveTransactions);
            List<AttributeDefinition> attDefs = target.GetAttributes(tr);
            foreach (ObjectId id in target.GetBlockReferenceIds(true, false))
            {
                BlockReference br = (BlockReference)tr.GetObject(id, OpenMode.ForWrite);
                br.ResetAttributes(attDefs, tr);
            }
            if (target.IsDynamicBlock)
            {
                target.UpdateAnonymousBlocks();
                foreach (ObjectId id in target.GetAnonymousBlockIds())
                {
                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(id, OpenMode.ForRead);
                    attDefs = btr.GetAttributes(tr);
                    foreach (ObjectId brId in btr.GetBlockReferenceIds(true, false))
                    {
                        BlockReference br = (BlockReference)tr.GetObject(brId, OpenMode.ForWrite);
                        br.ResetAttributes(attDefs, tr);
                    }
                }
            }
        }

        private static List<AttributeDefinition> GetAttributes(this BlockTableRecord target, Transaction tr)
        {
            List<AttributeDefinition> attDefs = new List<AttributeDefinition>();
            foreach (ObjectId id in target)
            {
                if (id.ObjectClass == attDefClass)
                {
                    AttributeDefinition attDef = (AttributeDefinition)tr.GetObject(id, OpenMode.ForRead);
                    attDefs.Add(attDef);
                }
            }
            return attDefs;
        }

        private static void ResetAttributes(this BlockReference br, List<AttributeDefinition> attDefs, Transaction tr)
        {
            Dictionary<string, string> attValues = new Dictionary<string, string>();
            foreach (ObjectId id in br.AttributeCollection)
            {
                if (!id.IsErased)
                {
                    AttributeReference attRef = (AttributeReference)tr.GetObject(id, OpenMode.ForWrite);
                    attValues.Add(attRef.Tag,
                        attRef.IsMTextAttribute ? attRef.MTextAttribute.Contents : attRef.TextString);
                    attRef.Erase();
                }
            }
            foreach (AttributeDefinition attDef in attDefs)
            {
                AttributeReference attRef = new AttributeReference();
                attRef.SetAttributeFromBlock(attDef, br.BlockTransform);
                if (attDef.Constant)
                {
                    attRef.TextString = attDef.IsMTextAttributeDefinition ?
                        attDef.MTextAttributeDefinition.Contents :
                        attDef.TextString;
                }
                else if (attValues.ContainsKey(attRef.Tag))
                {
                    attRef.TextString = attValues[attRef.Tag];
                }
                br.AttributeCollection.AppendAttribute(attRef);
                tr.AddNewlyCreatedDBObject(attRef, true);
            }
        }
    }
}

VB code (have to clear the Root Namespace in the project to add these extension methods to Autodesk.AutoCAD.DatabaseServices)
Code: [Select]
Imports Autodesk.AutoCAD.DatabaseServices
Imports Autodesk.AutoCAD.Runtime

Namespace Autodesk.AutoCAD.DatabaseServices
    Public Module ExtensionMethods

        Dim attDefClass As RXClass = RXClass.GetClass(GetType(AttributeDefinition))

        <System.Runtime.CompilerServices.Extension> _
        Public Sub SynchronizeAttributes(target As BlockTableRecord)
            If target Is Nothing Then
                Throw New ArgumentNullException("target")
            End If

            Dim tr As Transaction = target.Database.TransactionManager.TopTransaction
            If tr Is Nothing Then
                Throw New Exception(ErrorStatus.NoActiveTransactions)
            End If

            Dim attDefs As List(Of AttributeDefinition) = target.GetAttributes(tr)
            For Each id As ObjectId In target.GetBlockReferenceIds(True, False)
                Dim br As BlockReference = _
                    DirectCast(tr.GetObject(id, OpenMode.ForWrite), BlockReference)
                br.ResetAttributes(attDefs, tr)
            Next
            If target.IsDynamicBlock Then
                target.UpdateAnonymousBlocks()
                For Each id As ObjectId In target.GetAnonymousBlockIds()
                    Dim btr As BlockTableRecord = _
                        DirectCast(tr.GetObject(id, OpenMode.ForRead), BlockTableRecord)
                    attDefs = btr.GetAttributes(tr)
                    For Each brId As ObjectId In btr.GetBlockReferenceIds(True, False)
                        Dim br As BlockReference = _
                            DirectCast(tr.GetObject(brId, OpenMode.ForWrite), BlockReference)
                        br.ResetAttributes(attDefs, tr)
                    Next
                Next
            End If
        End Sub

        <System.Runtime.CompilerServices.Extension> _
        Private Function GetAttributes(target As BlockTableRecord, tr As Transaction) As List(Of AttributeDefinition)
            Dim attdefs As List(Of AttributeDefinition) = New List(Of AttributeDefinition)
            For Each id As ObjectId In target
                If id.ObjectClass = attDefClass Then
                    Dim attDef As AttributeDefinition = _
                        DirectCast(tr.GetObject(id, OpenMode.ForRead), AttributeDefinition)
                    attdefs.Add(attDef)
                End If
            Next
            Return attdefs
        End Function

        <System.Runtime.CompilerServices.Extension> _
        Private Sub ResetAttributes(br As BlockReference, attDefs As List(Of AttributeDefinition), tr As Transaction)
            Dim attValues As New Dictionary(Of String, String)()
            For Each id As ObjectId In br.AttributeCollection
                If Not id.IsErased Then
                    Dim attRef As AttributeReference = _
                        DirectCast(tr.GetObject(id, OpenMode.ForWrite), AttributeReference)
                    attValues.Add( _
                        attRef.Tag, _
                        If(attRef.IsMTextAttribute, attRef.MTextAttribute.Contents, attRef.TextString))
                    attRef.Erase()
                End If
            Next
            For Each attDef As AttributeDefinition In attDefs
                Dim attRef As New AttributeReference()
                attRef.SetAttributeFromBlock(attDef, br.BlockTransform)
                If attDef.Constant Then
                    attRef.TextString = If(attDef.IsMTextAttributeDefinition, _
                                           attDef.MTextAttributeDefinition.Contents, _
                                           attDef.TextString)
                Else If attValues IsNot Nothing AndAlso attValues.ContainsKey(attDef.Tag) Then
                    attRef.TextString = attValues(attDef.Tag.ToUpper())
                End If
                br.AttributeCollection.AppendAttribute(attRef)
                tr.AddNewlyCreatedDBObject(attRef, True)
            Next
        End Sub

    End Module

End Namespace
10
Blocks / Re: How to insert multiline attributes
« Last post by bcinnv on November 18, 2013, 02:30:59 PM »
Thanks bud! You always have the answer :)
Pages: [1] 2 3 ... 10