Recent Posts

Pages: [1] 2 3 ... 10
1
Display / Zoom (Editor extension methods)
« Last post by (gile) on March 10, 2017, 11:05:03 PM »
Some extension methods to perform Zoom.

Code: [Select]
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Runtime;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Autodesk.AutoCAD.EditorInput
{
    public static class ExtensionMethods
    {
        public static Matrix3d EyeToWorld(this ViewTableRecord view)
        {
            if (view == null)
                throw new ArgumentNullException("view");

            return
                Matrix3d.Rotation(-view.ViewTwist, view.ViewDirection, view.Target) *
                Matrix3d.Displacement(view.Target - Point3d.Origin) *
                Matrix3d.PlaneToWorld(view.ViewDirection);
        }

        public static Matrix3d WorldToEye(this ViewTableRecord view)
        {
            return view.EyeToWorld().Inverse();
        }

        public static void Zoom(this Editor ed, Extents3d ext)
        {
            if (ed == null)
                throw new ArgumentNullException("ed");

            using (ViewTableRecord view = ed.GetCurrentView())
            {
                ext.TransformBy(view.WorldToEye());
                view.Width = ext.MaxPoint.X - ext.MinPoint.X;
                view.Height = ext.MaxPoint.Y - ext.MinPoint.Y;
                view.CenterPoint = new Point2d(
                    (ext.MaxPoint.X + ext.MinPoint.X) / 2.0,
                    (ext.MaxPoint.Y + ext.MinPoint.Y) / 2.0);
                ed.SetCurrentView(view);
            }
        }

        public static void ZoomExtents(this Editor ed)
        {
            if (ed == null)
                throw new ArgumentNullException("ed");

            Database db = ed.Document.Database;
            Extents3d ext = (short)Application.GetSystemVariable("cvport") == 1 ?
                new Extents3d(db.Pextmin, db.Pextmax) :
                new Extents3d(db.Extmin, db.Extmax);
            ed.Zoom(ext);
        }

        public static void ZoomWindow(this Editor ed, Point3d p1, Point3d p2)
        {
            using (Line line = new Line(p1, p2))
            {
                ed.Zoom(line.GeometricExtents);
            }
        }

        public static void ZoomScale(this Editor ed, double scale)
        {
            if (ed == null)
                throw new ArgumentNullException("ed");

            using (ViewTableRecord view = ed.GetCurrentView())
            {
                view.Width /= scale;
                view.Height /= scale;
                ed.SetCurrentView(view);
            }
        }

        public static void ZoomObjects(this Editor ed, IEnumerable<ObjectId> ids)
        {
            if (ed == null)
                throw new ArgumentNullException("ed");

            using (Transaction tr = ed.Document.TransactionManager.StartTransaction())
            {
                Extents3d ext = ids
                    .Where(id => id.ObjectClass.IsDerivedFrom(RXObject.GetClass(typeof(Entity))))
                    .Select(id => ((Entity)tr.GetObject(id, OpenMode.ForRead)).GeometricExtents)
                    .Aggregate((e1, e2) => { e1.AddExtents(e2); return e1; });
                ed.Zoom(ext);
                tr.Commit();
            }
        }

        public static void ZoomCenter(this Editor ed, Point3d center, double scale = 1.0)
        {
            if (ed == null)
                throw new ArgumentNullException("ed");

            using (ViewTableRecord view = ed.GetCurrentView())
            {
                center = center.TransformBy(view.WorldToEye());
                view.Height /= scale;
                view.Width /= scale;
                view.CenterPoint = new Point2d(center.X, center.Y);
                ed.SetCurrentView(view);
            }
        }
    }
}
2
Tables / Re: Create simple table
« Last post by Jeff H on November 18, 2015, 11:22:03 AM »
Thanks old friend was very helpful.
3
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.
4
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
5
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;
6
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?
7
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);
               
                    }
                }
            }
        }
8
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);
                }
            }
        }
9
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.
10
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);
            }
        }
Pages: [1] 2 3 ... 10