Show Posts

This section allows you to view all posts made by this member. Note that you can only see posts made in areas you currently have access to.


Topics - fixo

Pages: 1 [2] 3 4 ... 8
16
External databases / Draw Polylines using Excel
« on: April 20, 2013, 08:28:38 PM »
Here is complete code, tested on AutoCAD 2010, Excel 2010:
Code: [Select]
Imports System.IO
Imports Microsoft.Office.Interop.Excel
Imports Autodesk.AutoCAD.Runtime
Imports Autodesk.AutoCAD.ApplicationServices
Imports Autodesk.AutoCAD.DatabaseServices
Imports Autodesk.AutoCAD.EditorInput
Imports Autodesk.AutoCAD.Geometry
Imports System.Runtime.InteropServices
Imports Excel = Microsoft.Office.Interop.Excel
'Imports MyProjectName.MyProjectName

<Assembly: CommandClass(GetType(MyProjectName.MyClassName))>
Namespace MyProjectName
    Public Class MyClassName

        <CommandMethod("hex")> _
        Public Sub ExcelToAcad()
            ReadExcelRange("C:\Test\TestXL.xlsx", "Sheet1")'<-- change file name and sheet name here
        End Sub

        Public Sub ReadExcelRange(ByVal xlFileName As String, ByVal xlSheetName As String)
            Dim lstPlines As New List(Of List(Of Object))
            If System.IO.File.Exists(xlFileName) Then

                Dim xlApp As Excel.Application = Nothing
                Dim xlWorkBooks As Excel.Workbooks = Nothing
                Dim xlWorkBook As Excel.Workbook = Nothing
                Dim xlWorkSheet As Excel.Worksheet = Nothing
                Dim xlWorkSheets As Excel.Sheets = Nothing
                Dim xlCells As Excel.Range = Nothing
                Dim xlRange As Excel.Range = Nothing

                xlApp = New Excel.Application
                Try
                    xlApp.DisplayAlerts = False
                    xlWorkBooks = xlApp.Workbooks
                    xlWorkBook = xlWorkBooks.Open(xlFileName)
                    xlApp.Visible = False
                    xlWorkSheets = xlWorkBook.Sheets
                    xlWorkSheet = CType(xlWorkSheets(xlSheetName), Excel.Worksheet)

                    xlRange = CType(xlWorkSheet.UsedRange.CurrentRegion, Excel.Range)


                    Dim xlRow As Excel.Range = Nothing
                    Dim xlCell As Excel.Range = Nothing

                    For irow As Integer = 1 To xlRange.Rows.Count

                        xlRow = CType(xlRange.Rows(irow), Excel.Range)
                        Dim lstRow As New List(Of Object)
                        For icol As Integer = 1 To xlRow.Cells.Count
                            xlCell = CType(xlRange.Cells(irow, icol), Excel.Range)
                            If xlCell.Value IsNot Nothing Then
                                lstRow.Add(xlCell.Value)
                            End If
                        Next

                        lstPlines.Add(lstRow)

                    Next
                    releaseObject(xlCell)
                    releaseObject(xlRow)
                    releaseObject(xlRange)

                    xlWorkBook.Close()

                    xlApp.Quit()

                    releaseObject(xlWorkSheets)
                    releaseObject(xlWorkSheet)
                    releaseObject(xlWorkBook)
                    releaseObject(xlWorkBooks)
                    releaseObject(xlApp)
                Catch ex As System.Exception

                    System.Windows.MessageBox.Show(ex.Message)

                End Try

                If lstPlines.Count > 0 Then
                    Dim doc As Document = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument
                    Dim ed As Editor = doc.Editor
                    Dim db As Database = doc.Database
                    Using tr As Transaction = db.TransactionManager.StartTransaction
                        Dim btr As BlockTableRecord = DirectCast(tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite), BlockTableRecord)

                        For Each lstCoords As List(Of Object) In lstPlines
                            Dim pline As New Polyline
                            Dim n As Integer = 0
                            Dim i As Integer = 0
                            For n = 0 To lstCoords.Count - 1 Step 2
                                Dim x As Double = Convert.ToDouble(lstCoords(n))
                                Dim y As Double = Convert.ToDouble(lstCoords(n + 1))

                                Dim pp As Point2d = New Point2d(x, y)
                                pline.AddVertexAt(i, pp, 0, 0, 0)
                                i += 1
                            Next
                            btr.AppendEntity(pline)
                            tr.AddNewlyCreatedDBObject(pline, True)
                        Next
                        tr.Commit()
                      System.Windows.MessageBox.Show("See result.")
                    End Using
                End If
            Else
                System.Windows.MessageBox.Show("'" & xlFileName & "' does not found.")
            End If
        End Sub
        Public Sub releaseObject(ByVal obj As Object)
            Try
                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obj)
                obj = Nothing
            Catch ex As System.Exception
                System.Diagnostics.Debug.Print(ex.ToString())
                obj = Nothing
            Finally
                GC.Collect()
            End Try
        End Sub
End Namespace

Please, see about Excel VB.NET for more :
http://www.siddharthrout.com/tag/vb-net-and-excel/
http://code.msdn.microsoft.com/Basics-of-using-Excel-4453945d
In the attached picture is data used for this code

17
Blocks / Numbering multileader with user block content
« on: March 24, 2013, 10:38:52 PM »
       
In this code used multileader with attributed block "Callout Bubble - Imperial",
after this block is inserted, then deleted, we can create multileader with block "_DetailCallout".
Then we can to number multileader this way:
Code: [Select]
         [CommandMethod("mab")]
        public static void MleaderBlockNumbering()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            Database db = doc.Database;

            Transaction tr = db.TransactionManager.StartTransaction();
            try
            {
                using (tr)
                {
                    BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite, false) as BlockTableRecord;
                    string prefix = ""; string suffix = ""; string atag = "SHEETNUMBER";// used "_DetailCallout" block fro Annotation palette
                    int start; int step; bool first = true;
                    ObjectId attnum = ObjectId.Null;
                    PromptStringOptions psto = new PromptStringOptions("\nPrefix: ");
                    psto.AllowSpaces = true;
                    PromptResult res;
                    res = ed.GetString(psto);
                    if (res.Status != PromptStatus.None)
                        prefix = res.StringResult;
                    psto = new PromptStringOptions("\nSuffix: ");
                    psto.AllowSpaces = true;
                    res = ed.GetString(psto);
                    if (res.Status != PromptStatus.None)
                        suffix = res.StringResult;
                    PromptIntegerOptions pio = new PromptIntegerOptions("");
                    pio.Message = "\nStarting number: ";
                    // Restrict input to positive and non-negative values
                    pio.AllowZero = false;
                    pio.AllowNegative = false;
                    pio.DefaultValue = 1;
                    PromptIntegerResult pires = ed.GetInteger(pio);
                    if (pires.Status != PromptStatus.OK) return;
                    start = pires.Value;
                    pio = new PromptIntegerOptions("");
                    pio.Message = "\nIncrement step: ";
                    // Restrict input to positive and non-negative values
                    pio.AllowZero = false;
                    pio.AllowNegative = false;
                    pio.DefaultValue = 1;
                    pires = ed.GetInteger(pio);
                    if (pires.Status != PromptStatus.OK) return;
                    step = pires.Value;
                    doc.TransactionManager.EnableGraphicsFlush(true);
                    //------------------------------------------------------------------------------------------
                    while (true)
                    {
                        PromptSelectionOptions pso = new PromptSelectionOptions();
                        pso.MessageForRemoval = "\nWrong object type or multileader with no block selected";
                        pso.MessageForAdding = "\nSelect multileader with block: ";
                        pso.SingleOnly = true;
                        pso.SinglePickInSpace = true;
                        TypedValue[] tvs = new TypedValue[] {
                new TypedValue((int) DxfCode.Operator, "<AND"),
                new TypedValue((int) DxfCode.Start, "multileader"),
                new TypedValue((int)  DxfCode.Operator, "<NOT"),
                new TypedValue((int)  DxfCode.Operator, "<OR"),
                new TypedValue(296, 0), new TypedValue(296, 1),
                new TypedValue((int)  DxfCode.Operator, "OR>"),
                new TypedValue((int) DxfCode.Operator, "NOT>"),
                new TypedValue((int) DxfCode .Operator, "AND>")
            };

                        SelectionFilter sf = new SelectionFilter(tvs);

                        PromptSelectionResult psr = ed.GetSelection(pso, sf);

                        if (psr.Status != PromptStatus.OK)
                        {
                            ed.WriteMessage("\nWrong selection");
                            break;

                        }

                        Entity ent;
                        ObjectId id = ObjectId.Null;
                        SelectionSet sset = psr.Value;
                        ObjectId[] ids = sset.GetObjectIds();
                        id = ids[0];
                        ent = (Entity)tr.GetObject(id, OpenMode.ForRead, false);
                        MLeader mlead = ent as MLeader;
                        if (mlead == null) return;
                        mlead.UpgradeOpen();
                        if (first)
                        {
                            ObjectId blkid = mlead.BlockContentId;
                            BlockTableRecord mbtr = (BlockTableRecord)tr.GetObject(blkid, OpenMode.ForRead, false) as BlockTableRecord;

                            foreach (ObjectId attid in mbtr)
                            {
                                DBObject obj = tr.GetObject(attid, OpenMode.ForRead);
                                if (obj is AttributeDefinition)
                                {
                                    AttributeDefinition attdef = obj as AttributeDefinition;
                                    if (attdef.Tag == atag)
                                    {
                                        attnum = attdef.ObjectId;
                                        break;
                                    }
                                }
                            }
                            first = false;
                        }
                        AttributeReference attref = mlead.GetBlockAttribute(attnum);
                        attref.TextString = prefix + start.ToString() + suffix;
                        mlead.SetBlockAttribute(attnum, attref);
                        start = start + step;
                        tr.TransactionManager.QueueForGraphicsFlush();
                    }
                    doc.TransactionManager.FlushGraphics();
                    tr.Commit();
                    ed.UpdateScreen();
                }
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                ed.WriteMessage("\n" + ex.Message + "\n" + ex.StackTrace);
            }
            finally
            {

            }
        }

18
Selection sets / Move selection to origin
« on: March 17, 2013, 07:39:16 AM »
      C#
   
Code: [Select]
        [System.Security.SuppressUnmanagedCodeSecurity]
        [DllImport("acad.exe", EntryPoint = "acedCmd", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
        extern static private int acedCmd(IntPtr resbuf);

        [CommandMethod("moveToOrig, mto", CommandFlags.UsePickSet | CommandFlags.Redraw)]
        static public void testMoveToOrigin()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            Database db = doc.Database;
            ResultBuffer rb = new ResultBuffer();
            try
            {

                rb.Add(new TypedValue(5005, "_Zoom"));
                rb.Add(new TypedValue(5005, "_Extents"));
                acedCmd(rb.UnmanagedObject);

                Matrix3d ucs = ed.CurrentUserCoordinateSystem;
                CoordinateSystem3d ccos = ucs.CoordinateSystem3d;
                Point3d orig = ccos.Origin.TransformBy(Matrix3d.Identity);
                // select all objects
                SelectionSet sset = ed.SelectAll().Value;
                if (sset == null) return;
                List<Point3d> pts = new List<Point3d>();
                List<Entity> ents = new List<Entity>();
                Matrix3d mmx = new Matrix3d();
                using (Transaction tr = doc.TransactionManager.StartTransaction())
                {
                    // iterate through selected objects
                    foreach (ObjectId id in sset.GetObjectIds())
                    {

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

                        Extents3d ext = ent.GeometricExtents;
                        if (ext != null)
                        {
                            Point3d minpt = ext.MinPoint.TransformBy(Matrix3d.Identity);
                            // collect entities to List for the future work
                            ents.Add(ent);
                            pts.Add(minpt);
                        }
                    }
                    // Get most lower left point of screen
                    Point3d xpt = pts.OrderBy(p => p.X).First();// calculate minimal X value
                    Point3d ypt = pts.OrderBy(p => p.Y).First();// calculate minimal Y value
                 Point3d mp = new Point3d(xpt.X, ypt.Y, orig.Z).TransformBy(Matrix3d.Identity);
                    mmx = Matrix3d.Displacement(orig-mp );
                    // iterate through gathrered entities again
                    foreach (Entity e in ents)
                    {
                        e.UpgradeOpen();
                        // apply transformation matrix
                        e.TransformBy(mmx);
                    }

                    tr.Commit();
                }
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                ed.WriteMessage("\n" + ex.Message + "\n" + ex.StackTrace);
            }
            finally
            {
                rb = new ResultBuffer();
                rb.Add(new TypedValue(5005, "_Zoom"));
                rb.Add(new TypedValue(5005, "_Extents"));
                acedCmd(rb.UnmanagedObject);
            }
        }

      VB.NET

      
Code: [Select]
<System.Security.SuppressUnmanagedCodeSecurity> _
<DllImport("acad.exe", EntryPoint := "acedCmd", CharSet := CharSet.Unicode, CallingConvention := CallingConvention.Cdecl)> _
Private Shared Function acedCmd(resbuf As IntPtr) As Integer
End Function

<CommandMethod("moveToOrig, mto", CommandFlags.UsePickSet Or CommandFlags.Redraw)> _
Public Shared Sub testMoveToOrigin()
Dim doc As Document = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument
Dim ed As Editor = doc.Editor
Dim db As Database = doc.Database
Dim rb As New ResultBuffer()
Try

rb.Add(New TypedValue(5005, "_Zoom"))
rb.Add(New TypedValue(5005, "_Extents"))
acedCmd(rb.UnmanagedObject)

Dim ucs As Matrix3d = ed.CurrentUserCoordinateSystem
Dim ccos As CoordinateSystem3d = ucs.CoordinateSystem3d
Dim orig As Point3d = ccos.Origin.TransformBy(Matrix3d.Identity)
' select all objects
Dim sset As SelectionSet = ed.SelectAll().Value
If sset Is Nothing Then
Return
End If
Dim pts As New List(Of Point3d)()
Dim ents As New List(Of Entity)()
Dim mmx As New Matrix3d()
Using tr As Transaction = doc.TransactionManager.StartTransaction()
' iterate through selected objects
For Each id As ObjectId In sset.GetObjectIds()

Dim ent As Entity = DirectCast(tr.GetObject(id, OpenMode.ForRead, False), Entity)

Dim ext As Extents3d = ent.GeometricExtents
If ext IsNot Nothing Then
Dim minpt As Point3d = ext.MinPoint.TransformBy(Matrix3d.Identity)
' collect entities to List for the future work
ents.Add(ent)
pts.Add(minpt)
End If
Next
' Get most lower left point of screen
Dim xpt As Point3d = pts.OrderBy(Function(p) p.X).First()
' calculate minimal X value
Dim ypt As Point3d = pts.OrderBy(Function(p) p.Y).First()
' calculate minimal Y value
Dim mp As Point3d = New Point3d(xpt.X, ypt.Y, orig.Z).TransformBy(Matrix3d.Identity)
mmx = Matrix3d.Displacement(orig - mp)
' iterate through gathrered entities again
For Each e As Entity In ents
e.UpgradeOpen()
' apply transformation matrix
e.TransformBy(mmx)
Next

tr.Commit()
End Using
Catch ex As Autodesk.AutoCAD.Runtime.Exception
ed.WriteMessage((vbLf + ex.Message & vbLf) + ex.StackTrace)
Finally
rb = New ResultBuffer()
rb.Add(New TypedValue(5005, "_Zoom"))
rb.Add(New TypedValue(5005, "_Extents"))
acedCmd(rb.UnmanagedObject)
End Try
End Sub

19
Blocks / Change text object in block reference
« on: March 15, 2013, 04:57:16 PM »
   C#
Code: [Select]
     
        // Change the text object in the BlockTableRecord by selecting them on screen
        // This method may have any name
        [CommandMethod("cato", CommandFlags.UsePickSet | CommandFlags.Redraw)]
        public static void ChangeTextInBlockDef()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Database db = doc.Database;

            Editor ed = doc.Editor;

            Transaction tr = db.TransactionManager.StartTransaction();
            using (tr)
            {
                doc.TransactionManager.EnableGraphicsFlush(true);
                PromptNestedEntityOptions pno = new PromptNestedEntityOptions("\nSelect text within block instance: ");
                pno.AllowNone = true;
                pno.UseNonInteractivePickPoint = false;
                PromptNestedEntityResult rs = ed.GetNestedEntity(pno);
                if (rs.Status != PromptStatus.OK) return;
                Entity selent = (Entity)tr.GetObject(rs.ObjectId, OpenMode.ForRead);
                ed.WriteMessage("\nSelected type of {0}", selent.GetType().Name);

                PromptStringOptions pso = new PromptStringOptions("\nEnter new text: ");
                pso.AllowSpaces = true;
                PromptResult res;
                res = ed.GetString(pso);
                if (res.Status != PromptStatus.OK) return;
                string newstr = res.StringResult;
                ed.WriteMessage("\nNew Text Entered:\t{0}", newstr);

                BlockTableRecord btrec = tr.GetObject(selent.OwnerId, OpenMode.ForWrite) as BlockTableRecord;
                // prevent work with attributes and embedded blocks
                if (selent.ObjectId.ObjectClass.IsDerivedFrom(RXClass.GetClass(typeof(AttributeReference))) |
                    selent.ObjectId.ObjectClass.IsDerivedFrom(RXClass.GetClass(typeof(BlockReference)))) return;
                if (selent.ObjectId.ObjectClass.IsDerivedFrom(RXClass.GetClass(typeof(DBText))))
                {
                    DBText txt = selent as DBText;
                    string oldstr = txt.TextString;

                    BlockTableRecord owner = (BlockTableRecord)tr.GetObject(txt.OwnerId, OpenMode.ForRead);
                    ed.WriteMessage("\nName:\t{0}", owner.Name);
                    owner.UpgradeOpen();
                    foreach (ObjectId id in owner)
                    {
                        if (!id.ObjectClass.IsDerivedFrom(RXClass.GetClass(typeof(DBText)))) continue;
                        DBObject obj = tr.GetObject(id, OpenMode.ForRead);
                        DBText blktxt = obj as DBText;
                        if (blktxt.TextString != oldstr) continue;
                        blktxt.UpgradeOpen();
                        blktxt.TextString = newstr;

                    }

                    //--------------------------------------------------------------
                    // add other possible types such as mtext, dimension etc here
                    //--------------------------------------------------------------


                    tr.TransactionManager.QueueForGraphicsFlush();

                    doc.TransactionManager.FlushGraphics();

                    tr.Commit();

                    ed.Regen();
                }
            }
        }

   VB.NET
Code: [Select]
        ' Change the text object in the BlockTableRecord by selecting them on screen
        ' This method may have any name
        <CommandMethod("cato", CommandFlags.UsePickSet Or CommandFlags.Redraw)> _
        Public Shared Sub ChangeTextInBlockDef()
            Dim doc As Document = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument

            Dim db As Database = doc.Database

            Dim ed As Editor = doc.Editor

            Dim tr As Transaction = db.TransactionManager.StartTransaction()
            Using tr
                doc.TransactionManager.EnableGraphicsFlush(True)
                Dim pno As New PromptNestedEntityOptions(vbLf & "Select text within block instance: ")
                pno.AllowNone = True
                pno.UseNonInteractivePickPoint = False
                Dim rs As PromptNestedEntityResult = ed.GetNestedEntity(pno)
                If rs.Status <> PromptStatus.OK Then
                    Return
                End If
                Dim selent As Entity = DirectCast(tr.GetObject(rs.ObjectId, OpenMode.ForRead), Entity)
                ed.WriteMessage(vbLf & "Selected type of {0}", selent.[GetType]().Name)

                Dim pso As New PromptStringOptions(vbLf & "Enter new text: ")
                pso.AllowSpaces = True
                Dim res As PromptResult
                res = ed.GetString(pso)
                If res.Status <> PromptStatus.OK Then
                    Return
                End If
                Dim newstr As String = res.StringResult
                ed.WriteMessage(vbLf & "New Text Entered:" & vbTab & "{0}", newstr)

                Dim btrec As BlockTableRecord = TryCast(tr.GetObject(selent.OwnerId, OpenMode.ForWrite), BlockTableRecord)
                ' prevent work with attributes and embedded blocks
                If selent.ObjectId.ObjectClass.IsDerivedFrom(RXClass.GetClass(GetType(AttributeReference))) Or selent.ObjectId.ObjectClass.IsDerivedFrom(RXClass.GetClass(GetType(BlockReference))) Then
                    Return
                End If
                If selent.ObjectId.ObjectClass.IsDerivedFrom(RXClass.GetClass(GetType(DBText))) Then
                    Dim txt As DBText = TryCast(selent, DBText)
                    Dim oldstr As String = txt.TextString

                    Dim owner As BlockTableRecord = DirectCast(tr.GetObject(txt.OwnerId, OpenMode.ForRead), BlockTableRecord)
                    ed.WriteMessage(vbLf & "Name:" & vbTab & "{0}", owner.Name)
                    owner.UpgradeOpen()
                    For Each id As ObjectId In owner
                        If Not id.ObjectClass.IsDerivedFrom(RXClass.GetClass(GetType(DBText))) Then
                            Continue For
                        End If
                        Dim obj As DBObject = tr.GetObject(id, OpenMode.ForRead)
                        Dim blktxt As DBText = TryCast(obj, DBText)
                        If blktxt.TextString <> oldstr Then
                            Continue For
                        End If
                        blktxt.UpgradeOpen()

                        blktxt.TextString = newstr
                    Next

                    '--------------------------------------------------------------
                    ' add other possible types such as mtext, dimension etc here
                    '--------------------------------------------------------------


                    tr.TransactionManager.QueueForGraphicsFlush()

                    doc.TransactionManager.FlushGraphics()

                    tr.Commit()

                    ed.Regen()
                End If
            End Using
        End Sub

20
Text / Place Text to center using calculated text width
« on: March 12, 2013, 05:52:23 PM »
   C# 
       
Code: [Select]
   
       // Place Text to center using calculated text width
        // tested on A2010 .NET Framework 3.5
        [CommandMethod("tcenter")]
        public static void textToCenter()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Autodesk.AutoCAD.GraphicsInterface.TextStyle style = new Autodesk.AutoCAD.GraphicsInterface.TextStyle();
            byte n;

            Transaction tr = db.TransactionManager.StartTransaction();
            try
            {
                using (tr)
                {
                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                    // setup the text
                    string text = "1234567890";
                    // add new dbtext to current space
                    DBText txt = new DBText();
                    txt.SetDatabaseDefaults();
                    txt.TextString = text;
                    txt.Position = new Point3d(100, 200, 0);
                    btr.AppendEntity(txt);
                    tr.AddNewlyCreatedDBObject(txt, true);
                    // get textstyle of newly created text
                    TextStyleTableRecord txtbtr = (TextStyleTableRecord)tr.GetObject(txt.TextStyleId, OpenMode.ForRead);
                    // copy properties from TextStyleTableRecord and dbtext to temp AcGi.TextStyle (just very limited one for the future calculation)
                    style.FileName = txtbtr.FileName;
                    // then copy properties from existing text
                    style.TextSize = txt.Height;  // txtbtr.TextSize;
                    style.ObliquingAngle = txt.Oblique;
                    style.XScale = txt.WidthFactor;
                    // load temp style record
                    try
                    {
                        n = style.LoadStyleRec;
                    }
                    catch { return; }// something wrong then exit on error

                    // set new position of text center, i.e. some dummy point
                    Point3d cpt = new Point3d(20, -45, 0);

                    // find out the extents
                    Point2d minpt, maxpt;
                    // get extends of text
                    Extents2d ex = style.ExtentsBox(text, true, true, null);

                    minpt = ex.MinPoint;
                    maxpt = ex.MaxPoint;
                    // work out the insertion point
                    Point3d newpos = cpt - new Vector3d((minpt.X + maxpt.X) / 2.0, (minpt.Y + maxpt.Y) / 2.0, 0);
                    // change text position to be centered in this point, independently of text alignment mode
                    txt.Position = newpos;
                    style.Dispose();// it's not a database resident, so dispose style, optional
                    tr.Commit();
                }
            }
            catch (System.Exception exc)
            {
                Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(exc.Message + "\n" + exc.StackTrace);
            }
            finally { }
        }

   VB.NET

Code: [Select]
      ' Place Text to center using calculated text width
        ' tested on A2010 .NET Framework 3.5
        <CommandMethod("tcenter")> _
        Public Shared Sub textToCenter()
            Dim doc As Document = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument
            Dim db As Database = doc.Database
            Dim style As New Autodesk.AutoCAD.GraphicsInterface.TextStyle()
            Dim n As Byte

            Dim tr As Transaction = db.TransactionManager.StartTransaction()
            Try
                Using tr
                    Dim btr As BlockTableRecord = DirectCast(tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite), BlockTableRecord)
                    ' setup the text
                    Dim text As String = "1234567890"
                    ' add new dbtext to current space
                    Dim txt As New DBText()
                    txt.SetDatabaseDefaults()
                    txt.TextString = text
                    txt.Position = New Point3d(100, 200, 0)
                    btr.AppendEntity(txt)
                    tr.AddNewlyCreatedDBObject(txt, True)
                    ' get textstyle of newly created text
                    Dim txtbtr As TextStyleTableRecord = DirectCast(tr.GetObject(txt.TextStyleId, OpenMode.ForRead), TextStyleTableRecord)
                    ' copy properties from TextStyleTableRecord and dbtext to temp AcGi.TextStyle (just very limited one for the future calculation)
                    style.FileName = txtbtr.FileName
                    ' then copy properties from existing text
                    style.TextSize = txt.Height
                    ' txtbtr.TextSize;
                    style.ObliquingAngle = txt.Oblique
                    style.XScale = txt.WidthFactor
                    ' load temp style record
                    Try
                        n = style.LoadStyleRec
                    Catch
                        Return
                    End Try
                    ' something wrong then exit on error
                    ' set new position of text center, i.e. some dummy point
                    Dim cpt As New Point3d(20, -45, 0)

                    ' find out the extents
                    Dim minpt As Point2d, maxpt As Point2d
                    ' get extends of text
                    Dim ex As Extents2d = style.ExtentsBox(text, True, True, Nothing)

                    minpt = ex.MinPoint
                    maxpt = ex.MaxPoint
                    ' work out the insertion point
                    Dim newpos As Point3d = cpt - New Vector3d((minpt.X + maxpt.X) / 2.0, (minpt.Y + maxpt.Y) / 2.0, 0)
                    ' change text position to be centered in this point, independently of text alignment mode
                    txt.Position = newpos
                    style.Dispose()
                    ' it's not a database resident, so dispose style, optional
                    tr.Commit()
                End Using
            Catch exc As System.Exception
                Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(exc.Message & vbLf & exc.StackTrace)
            Finally
            End Try
        End Sub

21
Dimensions / Draw runned dimensions for panel holes
« on: March 11, 2013, 10:15:46 PM »
For horizontal dimensions the first point is on left or right edge of panel,
for vertical dimensions it would be on top or bottom edge of panel for your choice

Code: [Select]
#Region "Runned Dimensions"
        <CommandMethod("rundim")> _
        Public Sub testRunnedDimensions()
            Dim doc As Document = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument
            Dim db As Database = doc.Database
            Dim ed As Editor = doc.Editor
            Dim ucs As Matrix3d = ed.CurrentUserCoordinateSystem
            Dim pko As New PromptKeywordOptions(vbLf & "Choose Dimension direction [Horizontal/Vertical]: ", "Horizontal Vertical")
            ' The default depends on our current settings
            pko.Keywords.Default = "Horizontal"
            Dim pres As PromptResult = ed.GetKeywords(pko)
            If pres.Status <> PromptStatus.OK Then
                Return
            End If
            Dim choice As String = pres.StringResult

            Dim spt As New Point3d
            Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("osmode", 513)
            If Not GetFirstPoint(ed, "Pick first point (press Enter to Exit loop): ", spt) Then Return
            Dim oids() As ObjectId = GetUserPickedObjects(doc, "Select circles: ")
            ed.Regen()
            doc.TransactionManager.EnableGraphicsFlush(True)
            Dim up As Double = db.Dimtxt * 4
            Using tr As Transaction = doc.Database.TransactionManager.StartTransaction()

                Dim btr As BlockTableRecord = CType(tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite), BlockTableRecord)
                Dim cnt As Integer = 0
                Dim ang As Double
                Dim rdim As RotatedDimension = Nothing
                For Each id As ObjectId In oids
                    If (Not id.ObjectClass.IsDerivedFrom(RXClass.GetClass(GetType(Circle)))) Then Continue For
                    Dim ent As DBObject = tr.GetObject(id, OpenMode.ForRead, False)
                    Dim circ As Circle = TryCast(ent, Circle)
                    If circ Is Nothing Then Return
                    Dim cp As Point3d = circ.Center
                    Dim gap As Double = cp.X - spt.X
                    If cnt = 0 Then
                        up = circ.Radius + up
                        If choice = "Horizontal" Then
                            spt = New Point3d(spt.X, cp.Y, spt.Z)
                        Else
                            spt = New Point3d(cp.X, spt.Y, spt.Z)
                        End If
                        cnt += 1
                    End If
                    Dim txp As Point3d
                    If choice = "Horizontal" Then
                        ang = 0.0
                        txp = spt.Add(New Vector3d(0, up, 0))
                        rdim = New RotatedDimension(ang, spt, cp, txp, "", db.Dimstyle)
                        Dim hdist As Double
                        Dim hpt As Point3d
                        If spt.X < cp.X Then
                            hdist = rdim.Measurement - db.Dimtxt * 6
                        Else
                            hdist = -rdim.Measurement + db.Dimtxt * 6
                        End If
                        hpt = txp.Add(New Vector3d(hdist, 0, 0))
                        rdim.Dimsd1 = True
                        rdim.Dimse1 = True
                        rdim.TextPosition = hpt
                    Else
                        ang = Math.PI / 2
                        txp = spt.Add(New Vector3d(up, 0, 0))
                        rdim = New RotatedDimension(ang, spt, cp, txp, "", db.Dimstyle)
                        Dim vdist As Double
                        Dim vpt As Point3d
                        If spt.Y < cp.Y Then
                            vdist = rdim.Measurement - db.Dimtxt * 6
                        Else
                            vdist = -rdim.Measurement + db.Dimtxt * 6
                        End If
                        vpt = txp.Add(New Vector3d(0, vdist, 0))
                        rdim.Dimsd1 = True
                        rdim.Dimse1 = True
                        rdim.TextPosition = vpt
                        rdim.TextRotation = ang
                    End If

                    btr.AppendEntity(rdim)
                    tr.AddNewlyCreatedDBObject(rdim, True)
                    tr.TransactionManager.QueueForGraphicsFlush()
                Next
                doc.TransactionManager.FlushGraphics()
                tr.Commit()
                ed.UpdateScreen()
            End Using
        End Sub
 


        Private Shared Function GetUserPickedObjects(ByVal doc As Document, msg As String) As ObjectId()
            Dim ids As New List(Of ObjectId)
            Using tr As Transaction = doc.Database.TransactionManager.StartTransaction()
                Dim go As Boolean = True
                While go
                    go = False

                    Dim opt As New PromptEntityOptions(vbLf & msg)
                    Dim res As PromptEntityResult = doc.Editor.GetEntity(opt)

                    If res.Status = PromptStatus.OK Then
                        Dim exists As Boolean = False
                        For Each id As ObjectId In ids
                            If id = res.ObjectId Then
                                exists = True
                                Exit For
                            End If
                        Next

                        If Not exists Then
                            'Highlight
                            Dim ent As Entity = DirectCast(tr.GetObject(res.ObjectId, OpenMode.ForWrite), Entity)

                            ent.Highlight()

                            ids.Add(res.ObjectId)
                            go = True
                        End If
                    End If
                End While

                tr.Commit()
            End Using

            Return ids.ToArray()
        End Function
#End Region

22
Dimensions / Draw stacked dimensions for panel holes
« on: March 11, 2013, 08:13:12 PM »
For horizontal dimensions the first point is on left or right edge of panel,
for vertical dimensions it would be on top or bottom edge of panel for your choice

Code: [Select]
       #Region "Stacked Dimension"
        <CommandMethod("stackdim")> _
        Public Sub testDimStackHoles()
            Dim doc As Document = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument
            Dim db As Database = doc.Database
            Dim ed As Editor = doc.Editor
            Dim pko As New PromptKeywordOptions(vbLf & "Choose Dimension direction [Horizontal/Vertical]: ", "Horizontal Vertical")
            ' The default depends on our current settings
            pko.Keywords.Default = "Horizontal"
            Dim pres As PromptResult = ed.GetKeywords(pko)
            If pres.Status <> PromptStatus.OK Then
                Return
            End If
            Dim choice As String = pres.StringResult

            Dim spt As New Point3d
            Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("osmode", 513)
            If Not GetFirstPoint(ed, "Pick first point (press Enter to Exit loop): ", spt) Then Return
            Dim oids() As ObjectId = GetUserPickedObjects(doc, "Select circles: ")
            ed.Regen()
            doc.TransactionManager.EnableGraphicsFlush(True)
            Dim up As Double = db.Dimtxt * 4
            Using tr As Transaction = doc.Database.TransactionManager.StartTransaction()

                Dim btr As BlockTableRecord = CType(tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite), BlockTableRecord)
                Dim cnt As Integer = 0
                Dim ang As Double
                Dim rdim As RotatedDimension = Nothing
                For Each id As ObjectId In oids
                    If (Not id.ObjectClass.IsDerivedFrom(RXClass.GetClass(GetType(Circle)))) Then Continue For
                    Dim ent As DBObject = tr.GetObject(id, OpenMode.ForRead, False)
                    Dim circ As Circle = TryCast(ent, Circle)
                    If circ Is Nothing Then Return
                    Dim cp As Point3d = circ.Center
                    Dim gap As Double = cp.X - spt.X
                    If cnt = 0 Then
                        up = circ.Radius + up
                        If choice = "Horizontal" Then
                            spt = New Point3d(spt.X, cp.Y, spt.Z)
                        Else
                            spt = New Point3d(cp.X, spt.Y, spt.Z)
                        End If
                        cnt += 1
                    End If
                    If choice = "Horizontal" Then
                        ang = 0.0
                        rdim = New RotatedDimension(ang, spt, cp, spt + New Vector3d(0, up, 0), "", db.Dimstyle)
                    Else
                        ang = Math.PI / 2
                        rdim = New RotatedDimension(ang, spt, cp, spt - New Vector3d(up, 0, 0), "", db.Dimstyle)
                    End If
                    up += db.Dimtxt * 2
                    btr.AppendEntity(rdim)
                    tr.AddNewlyCreatedDBObject(rdim, True)
                    tr.TransactionManager.QueueForGraphicsFlush()
                Next
                doc.TransactionManager.FlushGraphics()
                tr.Commit()
                ed.UpdateScreen()
            End Using
        End Sub


        Private Shared Function GetUserPickedObjects(ByVal doc As Document, msg As String) As ObjectId()
            Dim ids As New List(Of ObjectId)
            Using tr As Transaction = doc.Database.TransactionManager.StartTransaction()
                Dim go As Boolean = True
                While go
                    go = False

                    Dim opt As New PromptEntityOptions(vbLf & msg)
                    Dim res As PromptEntityResult = doc.Editor.GetEntity(opt)

                    If res.Status = PromptStatus.OK Then
                        Dim exists As Boolean = False
                        For Each id As ObjectId In ids
                            If id = res.ObjectId Then
                                exists = True
                                Exit For
                            End If
                        Next

                        If Not exists Then
                            'Highlight
                            Dim ent As Entity = DirectCast(tr.GetObject(res.ObjectId, OpenMode.ForWrite), Entity)

                            ent.Highlight()

                            ids.Add(res.ObjectId)
                            go = True
                        End If
                    End If
                End While

                tr.Commit()
            End Using

            Return ids.ToArray()
        End Function
#End Region

23
Windows forms / Use dinamically created form in the project
« on: March 11, 2013, 07:11:42 PM »
I've created simple project to show the way
how to use dinamic form for user interaction
Please see attached .zip file and read HowTo.txt for more

24
Text / Create Mtext using Notepad for input string (A2010)
« on: March 04, 2013, 10:00:47 AM »
     C#
Code: [Select]
        [System.Security.SuppressUnmanagedCodeSecurity]
        [DllImport("acad.exe", EntryPoint = "acedCmd", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
        extern static private int acedCmd(IntPtr resbuf);
        //-----------------------------------------------------------//
        // AutoCAD 2010 (eng.)
        [CommandMethod("mtx")]
        public void createMtext()
        {
            Clipboard.Clear();
            Document doc = doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Editor ed = doc.Editor;
            Database db = doc.Database;
            Transaction tr = db.TransactionManager.StartTransaction();
            Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("Add then \"Cut\" text from Notepad");
            System.Threading.Thread.Sleep(500);

            ResultBuffer rb = new ResultBuffer();

            rb.Add(new TypedValue((int)LispDataType.Text, "_startapp"));
            rb.Add(new TypedValue((int)LispDataType.Text, "notepad"));
            rb.Add(new TypedValue((int)LispDataType.Text, ""));// open Unnamed.txt
            rb.Add(new TypedValue((int)LispDataType.Text, "\n"));
            acedCmd(rb.UnmanagedObject);
            ed.Regen();
            using (tr)
            {   
                Point3d pt = ed.GetPoint("\nPick mtext location: ").Value;
                MText mtx = new MText();
                mtx.Location = pt;
                mtx.SetDatabaseDefaults();
                mtx.TextStyleId = db.Textstyle;// current text size
                mtx.TextHeight = db.Dimtxt;// current textstyle
                mtx.Width = 0.0;
                mtx.Contents = Clipboard.GetText();// paste mtext contents from clipboard
                // set alignment wharever you need:
                mtx.Attachment = AttachmentPoint.BottomCenter;
                mtx.SetAttachmentMovingLocation(mtx.Attachment);
                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                btr.AppendEntity(mtx);
                tr.AddNewlyCreatedDBObject(mtx, true);
                mtx.Width = mtx.ActualWidth;
                tr.Commit();
            }
           // Clipboard.Clear();// optional, if you won't use it then
        }

   VB.NET

   
Code: [Select]
  <System.Security.SuppressUnmanagedCodeSecurity()> _
<DllImport("acad.exe", EntryPoint:="acedCmd", CharSet:=CharSet.Unicode, CallingConvention:=CallingConvention.Cdecl)> _
        Private Shared Function acedCmd(resbuf As IntPtr) As Integer
        End Function
        '-----------------------------------------------------------//
        ' AutoCAD 2010 (32bit eng.) Win7
        <CommandMethod("mtx")> _
        Public Sub createMtext()
            System.Windows.Clipboard.Clear()
            Dim doc As Document = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument

            Dim ed As Editor = doc.Editor
            Dim db As Database = doc.Database
            Dim tr As Transaction = db.TransactionManager.StartTransaction()
            Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("Add then ""Cut"" text from Notepad")
            System.Threading.Thread.Sleep(500)

            Dim rb As New ResultBuffer()

            rb.Add(New TypedValue(CInt(LispDataType.Text), "_startapp"))
            rb.Add(New TypedValue(CInt(LispDataType.Text), "notepad"))
            rb.Add(New TypedValue(CInt(LispDataType.Text), ""))
            ' open file Unnamed.txt:
            rb.Add(New TypedValue(CInt(LispDataType.Text), vbLf))
            acedCmd(rb.UnmanagedObject)
            ed.Regen()
            Using tr
                Dim pt As Point3d = ed.GetPoint(vbLf & "Pick mtext location: ").Value
                Dim mtx As New MText()
                mtx.Location = pt
                mtx.SetDatabaseDefaults()
                mtx.TextStyleId = db.Textstyle
                ' current text size
                mtx.TextHeight = db.Dimtxt
                ' current textstyle
                mtx.Width = 0.0
                ' paste mtext contents from clipboard
                mtx.Contents = System.Windows.Clipboard.GetText()
                ' set alignment wharever you need:
                mtx.Attachment = AttachmentPoint.BottomCenter
                mtx.SetAttachmentMovingLocation(mtx.Attachment)
                Dim btr As BlockTableRecord = DirectCast(tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite), BlockTableRecord)
                btr.AppendEntity(mtx)
                tr.AddNewlyCreatedDBObject(mtx, True)
                mtx.Width = mtx.ActualWidth
                tr.Commit()
            End Using
            ' System.Windows.Clipboard.Clear();'' optional, if you won't use it then
        End Sub

25
Text / Copy mtext to new location
« on: March 03, 2013, 03:09:42 PM »
      Reliable way to check every user input, the result should displayed
      in the command line after the command will end 


     C#

Code: [Select]
        [CommandMethod("AMMC", CommandFlags.UsePickSet)]     // copy mtext to new location
        public void testPlaceMtextBetween()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            Entity ent;
            bool isok = true;
            Transaction tr = db.TransactionManager.StartTransaction();
           
                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForRead);
                try
                {
            PromptPointOptions ppo = new PromptPointOptions("\nLeft Point: ");
            PromptPointResult ppr = ed.GetPoint(ppo);
            Point3d p1 = ppr.Value;
            if (ppr.Status != PromptStatus.OK)
            {
                isok = false;
                return;
            }
            ppo = new PromptPointOptions("\nRight point: ");
            ppo.UseBasePoint = true;
            ppo.BasePoint = p1;
            PromptPointResult pcr = ed.GetPoint(ppo);
            if (pcr.Status != PromptStatus.OK)
            {
                isok = false;
                return;
            }
            Point3d p2 = pcr.Value;
            if (p1.X == p2.X || p1.Y == p2.Y)
            {
                ed.WriteMessage("\nInvalid coordinate specification");
                isok = false;
                return;
            }
            Point3d mp = new Point3d((p1.X + p2.X) / 2, (p1.Y + p2.Y) / 2, (p1.Z + p2.Z) / 2).TransformBy(Matrix3d.Identity);
            PromptSelectionOptions pso = new PromptSelectionOptions();
            pso.MessageForRemoval = "\nNot a mtext object, exit.";
            pso.MessageForAdding = "\nPick a single MText: ";
            pso.SingleOnly = true;
            pso.SinglePickInSpace = true;
             pso.PrepareOptionalDetails = true;

            SelectionFilter filter = new SelectionFilter(new TypedValue[] { new TypedValue(0, "mtext") });
            PromptSelectionResult res = ed.GetSelection(pso, filter);
            SelectionSet sset = res.Value;
            if (sset.Count == 0) return;

           
                    SelectedObject sobj = res.Value[0];

                    if (!sobj.ObjectId.IsValid) return;

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

                    if (ent is MText)
                    {
                        ent.UpgradeOpen();
                        Plane plan = new Plane(Point3d.Origin, Vector3d.ZAxis);
                        MText mtxt = ent as MText;
                        Point3d ip = mtxt.Location.TransformBy(Matrix3d.Identity);

                        Entity clonen = (Entity)ent.Clone();
                        MText clon = (MText)clonen as MText;
                        if (clon == null) return;
                        if (!clon.IsWriteEnabled) clon.UpgradeOpen();
                        Matrix3d mx = Matrix3d.Displacement(mp.GetVectorTo(ip));
                        clon.TransformBy(mx);
                        clon.Rotation = 0.0;
                        double ang = p1.GetVectorTo(p2).AngleOnPlane(plan);
                        // justify mtext to be more readable
                        if ((ang > Math.PI / 2) && (ang < Math.PI * 1.5))
                            ang = ang + Math.PI;
                        mx = Matrix3d.Rotation(p1.GetVectorTo(p2).AngleOnPlane(plan), Vector3d.ZAxis, mp);
                        clon.TransformBy(mx);
                        clon.Location = mp;
                        clon.Attachment = AttachmentPoint.MiddleCenter;
                        clon.SetAttachmentMovingLocation(clon.Attachment);
                        PromptKeywordOptions pko = new PromptKeywordOptions
                            ("\nSave old text or create new one instead? " + "[Old/New]: ", "Old New");
                        pko.AllowNone = true;
                        // The default depends on our current settings
                        pko.Keywords.Default = "Old";
                        PromptResult pr = ed.GetKeywords(pko);
                        if (pr.Status != PromptStatus.OK) return;
                        if (pr.StringResult == "New")
                        {

                            PromptStringOptions psto =
                                 new PromptStringOptions("\nEnter text (use \\P to jump next line): ");
                            psto.AllowSpaces = true;
                           
                            PromptResult stres = ed.GetString(psto);
                            if (stres.Status != PromptStatus.OK)   return;
                            string cont = stres.StringResult;
                            if (string.IsNullOrEmpty(cont))
                            {
                                isok = false;
                                return;
                            }
                            else
                            clon.Contents = cont;
                        }
                        else
                        clon.Contents = mtxt.Contents;
                        clon.Width = clon.ActualWidth;
                        clon.Height = clon.ActualHeight;
                        btr.UpgradeOpen();
                        btr.AppendEntity(clon);
                        tr.AddNewlyCreatedDBObject(clon, true);

                        tr.Commit();
                        isok = true;
                    }
                }
                catch (System.Exception ex)
                {
                    isok = false;
                    ed.WriteMessage(ex.Message);
                    tr.Abort();
                }
                finally
                {
                    string result = isok == true ? "success" : "fail";
                    Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage
                        ("\n\t---\tCommand is ended up with result of {0}.  \t---\n",result);
                    tr.Dispose();
                }
            }

 VB.NET

 
Code: [Select]
      ' copy mtext to new location
        <CommandMethod("AMMC", CommandFlags.UsePickSet)> _
        Public Sub testPlaceMtextBetween()
            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 isok As Boolean = True
            Dim tr As Transaction = db.TransactionManager.StartTransaction()

            Dim btr As BlockTableRecord = DirectCast(tr.GetObject(db.CurrentSpaceId, OpenMode.ForRead), BlockTableRecord)
            Try
                Dim ppo As New PromptPointOptions(vbLf & "Left Point: ")
                Dim ppr As PromptPointResult = ed.GetPoint(ppo)
                Dim p1 As Point3d = ppr.Value
                If ppr.Status <> PromptStatus.OK Then
                    isok = False
                    Return
                End If
                ppo = New PromptPointOptions(vbLf & "Right point: ")
                ppo.UseBasePoint = True
                ppo.BasePoint = p1
                Dim pcr As PromptPointResult = ed.GetPoint(ppo)
                If pcr.Status <> PromptStatus.OK Then
                    isok = False
                    Return
                End If
                Dim p2 As Point3d = pcr.Value
                If p1.X = p2.X OrElse p1.Y = p2.Y Then
                    ed.WriteMessage(vbLf & "Invalid coordinate specification")
                    isok = False
                    Return
                End If
                Dim mp As Point3d = New Point3d((p1.X + p2.X) / 2, (p1.Y + p2.Y) / 2, (p1.Z + p2.Z) / 2).TransformBy(Matrix3d.Identity)
                Dim pso As New PromptSelectionOptions()
                pso.MessageForRemoval = vbLf & "Not a mtext object, exit."
                pso.MessageForAdding = vbLf & "Pick a single MText: "
                pso.SingleOnly = True
                pso.SinglePickInSpace = True
                pso.PrepareOptionalDetails = True

                Dim filter As New SelectionFilter(New TypedValue() {New TypedValue(0, "mtext")})
                Dim res As PromptSelectionResult = ed.GetSelection(pso, filter)
                Dim sset As SelectionSet = res.Value
                If sset.Count = 0 Then
                    Return
                End If


                Dim sobj As SelectedObject = res.Value(0)

                If Not sobj.ObjectId.IsValid Then
                    Return
                End If

                ent = DirectCast(tr.GetObject(sobj.ObjectId, OpenMode.ForRead), Entity)

                If TypeOf ent Is MText Then
                    ent.UpgradeOpen()
                    Dim plan As New Plane(Point3d.Origin, Vector3d.ZAxis)
                    Dim mtxt As MText = TryCast(ent, MText)
                    Dim ip As Point3d = mtxt.Location.TransformBy(Matrix3d.Identity)

                    Dim clonen As Entity = DirectCast(ent.Clone(), Entity)
                    Dim clon As MText = TryCast(DirectCast(clonen, MText), MText)
                    If clon Is Nothing Then
                        Return
                    End If
                    If Not clon.IsWriteEnabled Then
                        clon.UpgradeOpen()
                    End If
                    Dim mx As Matrix3d = Matrix3d.Displacement(mp.GetVectorTo(ip))
                    clon.TransformBy(mx)
                    clon.Rotation = 0.0
                    Dim ang As Double = p1.GetVectorTo(p2).AngleOnPlane(plan)
                    ' justify mtext to be more readable
                    If (ang > Math.PI / 2) AndAlso (ang < Math.PI * 1.5) Then
                        ang = ang + Math.PI
                    End If
                    mx = Matrix3d.Rotation(p1.GetVectorTo(p2).AngleOnPlane(plan), Vector3d.ZAxis, mp)
                    clon.TransformBy(mx)
                    clon.Location = mp
                    clon.Attachment = AttachmentPoint.MiddleCenter
                    clon.SetAttachmentMovingLocation(clon.Attachment)
                    Dim pko As New PromptKeywordOptions(vbLf & "Save old text or create new one instead? " & "[Old/New]: ", "Old New")
                    pko.AllowNone = True
                    ' The default depends on our current settings
                    pko.Keywords.[Default] = "Old"
                    Dim pr As PromptResult = ed.GetKeywords(pko)
                    If pr.Status <> PromptStatus.OK Then
                        Return
                    End If
                    If pr.StringResult = "New" Then

                        Dim psto As New PromptStringOptions(vbLf & "Enter text (use \P to jump next line): ")
                        psto.AllowSpaces = True

                        Dim stres As PromptResult = ed.GetString(psto)
                        If stres.Status <> PromptStatus.OK Then
                            Return
                        End If
                        Dim cont As String = stres.StringResult
                        If String.IsNullOrEmpty(cont) Then
                            isok = False
                            Return
                        Else
                            clon.Contents = cont
                        End If
                    Else
                        clon.Contents = mtxt.Contents
                    End If
                    clon.Width = clon.ActualWidth
                    clon.Height = clon.ActualHeight
                    btr.UpgradeOpen()
                    btr.AppendEntity(clon)
                    tr.AddNewlyCreatedDBObject(clon, True)

                    tr.Commit()
                    isok = True
                End If
            Catch ex As System.Exception
                isok = False
                ed.WriteMessage(ex.Message)
                tr.Abort()
            Finally
                Dim result As String = If(isok = True, "success", "fail")
                Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage(vbLf & vbTab & "---" & vbTab & "Command is ended up with result of {0}.  " & vbTab & "---" & vbLf, result)
                tr.Dispose()
            End Try
        End Sub

26
Layers / Work on locked layers sample
« on: February 28, 2013, 08:42:56 PM »
 
Code: [Select]
       [CommandMethod("WorkWithLockedLayers","wlock", CommandFlags.UsePickSet | CommandFlags.Redraw)]
        public void testWorkOnLockedLayers()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            bool fine = true;
            ObjectIdCollection locked = new ObjectIdCollection();
            try
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    LayerTable lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead);

                    foreach (ObjectId ltId in lt)
                    {
                        if (ltId.IsValid && ltId.IsResident && !ltId.IsErased) // just drawing layers were allowed
                        {
                            LayerTableRecord ltr = (LayerTableRecord)tr.GetObject(ltId, OpenMode.ForRead);

                            if (ltr.IsLocked)
                            {
                                locked.Add(ltId);
                                ltr.UpgradeOpen();
                                ltr.IsLocked = false;
                                ltr.DowngradeOpen();// optional
                            }
                        }
                    }
                    //
                    // Here you begin to work with objects and not worry that they are in the locked layers
                    // e.g. itrerate through selection etc. (poor code commented)
                    //SelectionSet ss = ed.SelectAll().Value;
                    //foreach (ObjectId id in ss.GetObjectIds())
                    //{
                    //    Entity ent = (Entity)tr.GetObject(id, OpenMode.ForWrite);
                    //    ent.ColorIndex = 121;
                    //}
                    //
                    foreach (ObjectId ltId in lt)
                    {
                        LayerTableRecord ltr = (LayerTableRecord)tr.GetObject(ltId, OpenMode.ForWrite);
                        ltr.IsLocked = true;

                    }
                    tr.Commit();
                }
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                fine = false;
                ed.WriteMessage(ex.ToString());
            }
            finally
            {
                if (!fine)
                    doc.SendStringToExecute("_layerp", true, false, false);
            }
        }

27
Polylines / Offset curve toward centroid
« on: February 26, 2013, 07:13:16 PM »
// Offset curve toward centroid

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

            Editor ed = doc.Editor;

            Database db = doc.Database;

            Transaction tr = doc.TransactionManager.StartTransaction();

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

                        PromptEntityOptions peo = new PromptEntityOptions("\nSelect curve to Offset Toward: ");

                        peo.SetRejectMessage("\nSelect curve only: ");

                        peo.AddAllowedClass(typeof(Line), true);

                        peo.AddAllowedClass(typeof(Arc), true);

                        peo.AddAllowedClass(typeof(Circle), true);

                        peo.AddAllowedClass(typeof(Ellipse), true);

                        peo.AddAllowedClass(typeof(Polyline), true);

                        peo.AddAllowedClass(typeof(Spline), true);

                        PromptEntityResult pres = ed.GetEntity(peo);

                        if ((pres.Status != PromptStatus.OK)) return;

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

                        // add the polylines to the array
                        DBObjectCollection dbobjs = new DBObjectCollection();
                        dbobjs.Add(ent);
                        // create the region
                        Region objreg = new Region();

                        DBObjectCollection objRegions = new DBObjectCollection();

                        objRegions = Region.CreateFromCurves(dbobjs);

                        objreg = objRegions[0] as Region;
                       
                        Curve curv = ent as Curve;

                        PromptDoubleResult dres = ed.GetDouble("\nDistance for Offset: ");

                        double dist = dres.Value;

                        DBObjectCollection ids = curv.GetOffsetCurves(dist);
                        DBObjectCollection ids2 = curv.GetOffsetCurves(-1 * dist);
                       double leg= ((ids[0]) as Curve).Area;
                       double leg2 = ((ids2[0]) as Curve).Area;
                       if (leg - leg2 < 0)
                       {
                           foreach (Entity oEnt in ids)
                           {
                               btr.AppendEntity(oEnt);
                               tr.AddNewlyCreatedDBObject(oEnt, true);
                           }
                       }
                       else
                       {

                           foreach (Entity oEnt in ids2)
                           {
                               btr.AppendEntity(oEnt);
                               tr.AddNewlyCreatedDBObject(oEnt, true);
                           }
                       }
                       
                       objRegions.Dispose();
                       ids.Dispose();
                       ids2.Dispose();
                       doc.TransactionManager.FlushGraphics();
                        tr.Commit();
                        ed.UpdateScreen();
                    }

                    catch (Autodesk.AutoCAD.Runtime.Exception ex)
                    {
                        ed.WriteMessage("\nError: {0}\nTrace: {1}", ex.Message, ex.StackTrace);
                    }
                }
            }

28
Tables / How to change cell value in previously selected table (A2010)
« on: February 24, 2013, 09:40:48 PM »
       
Code: [Select]
        // Select table on screen, then perform command SelCell:
        [CommandMethod("SelCell", CommandFlags.UsePickSet)]
        public static void testSelectFromTable()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            ObjectId id = ObjectId.Null;
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {

                PromptSelectionResult res = ed.SelectImplied();
                if (res.Status == PromptStatus.OK)
                {
                    SelectionSet sset = res.Value;
                    id = sset.GetObjectIds()[0];
                    Table table = tr.GetObject(id, OpenMode.ForRead) as Table;

                    PromptPointOptions pto = new PromptPointOptions("\nPick inside a single cell: ");

                    PromptPointResult pres = ed.GetPoint(pto);

                    if (pres.Status != PromptStatus.OK)
                    {
                        ed.WriteMessage("\nInvalid point specification!");
                        return;
                    }
                    Point3d pt = pres.Value;
                    TableHitTestInfo hit = table.HitTest(pt, Vector3d.ZAxis);
                    int i = hit.Row;
                    int j = hit.Column;
                    Cell cell = table.Cells[i, j];
                    CellRange cr = CellRange.Create(table, i, j, i, j);
                    table.SubSelection = cr;
                    Vector3d vec = table.Normal;
                    Point3dCollection pts = cell.GetExtents();
                    double ht = table.Rows[cell.TopRow].Height;
                    double wid = table.Columns[cell.LeftColumn].Width;
                    table.SelectSubRegion(pts[0], pts[2], vec, vec, SelectType.Window, false, true, new FullSubentityPath[] { });
                    if (table.HasSubSelection)
                    {
                        cr = table.SubSelection;
                        if (cr.IsSingleCell)
                        {
                            cell = table.Cells[cr.TopRow, cr.LeftColumn];
                            string celltxt = cell.GetTextString(FormatOption.ForExpression);
                            ed.WriteMessage("\n{0}\n", celltxt);
                            table.UpgradeOpen();
                            cell.Contents[0].TextString = "Abracadabra";// add your value here
                        }

                    }
                    if (table.HasSubSelection)
                    {
                        ed.WriteMessage("\nSubSelection remove");
                        ed.GetString("\nPress any key: ");
                        table.ClearSubSelection();
                    }
                }
                tr.Commit();
            }
        }

29
Polylines / Regular polygons example
« on: February 21, 2013, 08:19:48 AM »
          C#
Code: [Select]
       // by Tony Tanzillo
        public static Point3d PolarPoint(Point3d basepoint, double angle, double distance)
        {
            return new Point3d(
            basepoint.X + (distance * Math.Cos(angle)),
            basepoint.Y + (distance * Math.Sin(angle)),
            basepoint.Z);
        }
        [CommandMethod("preg", CommandFlags.UsePickSet)]
        public void testPolygonRegular()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            PromptIntegerOptions pio = new PromptIntegerOptions("");
            pio.Message = "\nNumber of sides: ";

            // Restrict input to positive and non-negative values
            pio.AllowZero = false;
            pio.AllowNegative = false;
            // Add default value
            pio.DefaultValue = 3;
            pio.AllowNone = true;
            // Get the value entered by the user
            PromptIntegerResult ires = ed.GetInteger(pio);
            if (ires.Status != PromptStatus.OK) return;
            int n = ires.Value;

            PromptDoubleOptions pdo = new PromptDoubleOptions("\nEnter radius: ");
            pdo.AllowZero = false;
            pdo.AllowNegative = false;
            pdo.AllowNone = true;
            pdo.UseDefaultValue = true;
            pdo.DefaultValue = 3.0;

            PromptDoubleResult res;
            res = ed.GetDouble(pdo);
            if (res.Status != PromptStatus.OK) return;

            double rad = res.Value;

            double ang = Math.PI * 2 / n;
            Point3d cp, p1,p2;
            // Center point
            cp = new Point3d(0, 0,0);

            Polyline poly = new Polyline(n);
            Polyline poly2 = new Polyline(n);
            for (int th = 0; th < n; th++)
            {
                // Circumscribed
                p1 = PolarPoint(cp, th * ang, rad / Math.Cos(ang / 2)).TransformBy(Matrix3d.Identity);
                poly.AddVertexAt(th, new Point2d(p1.X, p1.Y), 0, 0, 0);
                // Inscribed
                 p2 = PolarPoint(cp, th * ang, rad).TransformBy(Matrix3d.Identity);
                poly2.AddVertexAt(th, new Point2d(p2.X, p2.Y), 0, 0, 0);
            }
            poly.Closed = true;
            poly.ColorIndex = 1;
            poly2.Closed = true;
            poly2.ColorIndex = 3;
            // Add circle for imagination only
            Circle circ = new Circle(new Point3d(0, 0, 0), Vector3d.ZAxis, rad);
            circ.ColorIndex = 5;
            Transaction tr = doc.TransactionManager.StartTransaction();

            using (tr)
            {
                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                btr.AppendEntity(poly);
                tr.AddNewlyCreatedDBObject(poly, true);
                btr.AppendEntity(poly2);
                tr.AddNewlyCreatedDBObject(poly2, true);
                btr.AppendEntity(circ);
                tr.AddNewlyCreatedDBObject(circ, true);
                tr.Commit();
            }
        }
      VB.NET
Code: [Select]
        ' by Tony Tanzillo
        Public Shared Function PolarPoint(basepoint As Point3d, angle As Double, distance As Double) As Point3d
            Return New Point3d(basepoint.X + (distance * Math.Cos(angle)), basepoint.Y + (distance * Math.Sin(angle)), basepoint.Z)
        End Function

        <CommandMethod("preg", CommandFlags.UsePickSet)> _
        Public Sub testPolygonRegular()
            Dim doc As Document = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument
            Dim db As Database = doc.Database
            Dim ed As Editor = doc.Editor
            Dim pio As New PromptIntegerOptions("")
            pio.Message = vbLf & "Number of sides: "

            ' Restrict input to positive and non-negative values
            pio.AllowZero = False
            pio.AllowNegative = False
            ' Add default value
            pio.DefaultValue = 3
            pio.AllowNone = True
            ' Get the value entered by the user
            Dim ires As PromptIntegerResult = ed.GetInteger(pio)
            If ires.Status <> PromptStatus.OK Then
                Return
            End If
            Dim n As Integer = ires.Value

            Dim pdo As New PromptDoubleOptions(vbLf & "Enter radius: ")
            pdo.AllowZero = False
            pdo.AllowNegative = False
            pdo.AllowNone = True
            pdo.UseDefaultValue = True
            pdo.DefaultValue = 3.0

            Dim res As PromptDoubleResult
            res = ed.GetDouble(pdo)
            If res.Status <> PromptStatus.OK Then
                Return
            End If

            Dim rad As Double = res.Value

            Dim ang As Double = Math.PI * 2 / n
            Dim cp As Point3d, p1 As Point3d, p2 As Point3d
            ' Center point
            cp = New Point3d(0, 0, 0)

            Dim poly As New Polyline(n)
            Dim poly2 As New Polyline(n)
            For th As Integer = 0 To n - 1
                ' Circumscribed
                p1 = PolarPoint(cp, th * ang, rad / Math.Cos(ang / 2)).TransformBy(Matrix3d.Identity)
                poly.AddVertexAt(th, New Point2d(p1.X, p1.Y), 0, 0, 0)
                ' Inscribed
                p2 = PolarPoint(cp, th * ang, rad).TransformBy(Matrix3d.Identity)
                poly2.AddVertexAt(th, New Point2d(p2.X, p2.Y), 0, 0, 0)
            Next
            poly.Closed = True
            poly.ColorIndex = 1
            poly2.Closed = True
            poly2.ColorIndex = 3
            ' Add circle for imagination only
            Dim circ As New Circle(New Point3d(0, 0, 0), Vector3d.ZAxis, rad)
            circ.ColorIndex = 5
            Dim tr As Transaction = doc.TransactionManager.StartTransaction()

            Using tr
                Dim btr As BlockTableRecord = DirectCast(tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite), BlockTableRecord)
                btr.AppendEntity(poly)
                tr.AddNewlyCreatedDBObject(poly, True)
                btr.AppendEntity(poly2)
                tr.AddNewlyCreatedDBObject(poly2, True)
                btr.AppendEntity(circ)
                tr.AddNewlyCreatedDBObject(circ, True)
                tr.Commit()
            End Using
        End Sub

30
Math and Geometry / Draw bisector between 2 lines
« on: February 19, 2013, 08:02:37 PM »
Code: [Select]
        [CommandMethod("bis", CommandFlags.UsePickSet)]
        public static void drawBisector()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = HostApplicationServices.WorkingDatabase;
            Editor ed = doc.Editor;
            PromptEntityOptions peo = new PromptEntityOptions("\nSelect first line: ");
            peo.SetRejectMessage("Wrong object or nothing selected.");
            peo.AddAllowedClass(typeof(Line), false);
            PromptEntityResult res;
            ObjectId objId1 = ObjectId.Null;
            ObjectId objId2 = ObjectId.Null;
            Entity ent;
            Point3d p1, p2;
            res = ed.GetEntity(peo);

            if (res.Status != PromptStatus.OK)
                return;;
            objId1 = res.ObjectId;
            p1 = res.PickedPoint;
            peo.Message="\nSelect second line: ";
            res = ed.GetEntity(peo);

            if (res.Status != PromptStatus.OK)
                return;
            objId2 = res.ObjectId;
            p2 = res.PickedPoint;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                ent = tr.GetObject(objId1, OpenMode.ForRead) as Entity;
                if (ent == null)   return;
                Line ln1 = ent as Line;
                if (ln1 == null) return;
                ent = tr.GetObject(objId2, OpenMode.ForRead) as Entity;
                if (ent == null) return;
                Line ln2 = ent as Line;
                if (ln2 == null) return;

                p1 = ln1.GetClosestPointTo(p1,false);
                p2 = ln2.GetClosestPointTo(p2, false);

                Point3d tmp,p1f, p2f, p1n, p2n;

                p1f = ln1.StartPoint;
                p2f = ln1.EndPoint;
                p1n = ln2.StartPoint;
                p2n = ln2.EndPoint;
                // swap poins for easier math
                if (p1f.DistanceTo(p1n) > p1f.DistanceTo(p2n))
                {
                    tmp = p2n;
                    p2n = p1n;
                    p1n=tmp;
                }
   
                Point3d mp1 = new Point3d((p1f.X + p1n.X) / 2, (p1f.Y + p1n.Y) / 2, (p1f.Z + p1n.Z) / 2);
                Point3d mp2 = new Point3d((p2f.X + p2n.X) / 2, (p2f.Y + p2n.Y) / 2, (p2f.Z + p2n.Z) / 2);
                Line bis = new Line(mp1, mp2);

                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                btr.AppendEntity(bis);
                tr.AddNewlyCreatedDBObject(bis, true);
                tr.Commit();
            }
        }

Pages: 1 [2] 3 4 ... 8