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] 5 6 7
46
Polylines / Draw grid by picking corners
« on: December 29, 2012, 06:30:51 PM »
        [CommandMethod("gds")]
Code: [Select]
        public static void TestGraph()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            Matrix3d ucs = ed.CurrentUserCoordinateSystem;
            PromptPointOptions ppo = new PromptPointOptions("\nJust a Lower Left corner: ");
            PromptPointResult ppr = ed.GetPoint(ppo);
            if (ppr.Status != PromptStatus.OK)
            {
                return;
            }
            PromptCornerOptions pco = new PromptCornerOptions("\nUpper Right corner: ", ppr.Value);
            PromptPointResult pcr = ed.GetCorner(pco);
            if (pcr.Status != PromptStatus.OK)
            {
                return;
            }
            Point3d p1 = ppr.Value;
            Point3d p2 = pcr.Value;
            if (((p1.X == p2.X || p1.Y == p2.Y) & (p2.X > p1.X || p2.Y > p1.Y)))
            {
                ed.WriteMessage("\nWrong coordinate specification");
                return;
            }
            // Calculate the four corner points of the box
            // and add them to a Point3dCollection:
            Point3dCollection points = new Point3dCollection();
            points.Add(p1);
            points.Add(new Point3d(p2.X, p1.Y, 0.0));
            points.Add(p2);
            points.Add(new Point3d(p1.X, p2.Y, 0.0));
            double leng = 0;
            leng = p2.X - p1.X;
            double wid = 0;
            wid = p2.Y - p1.Y;

            //'-------------------------------------------------------''
            PromptIntegerOptions pio = new PromptIntegerOptions("");
            pio.Message = "\nEnter the number of rows: ";

            // Restrict input to positive and non-negative values
            pio.AllowZero = false;
            pio.AllowNegative = false;
            // Add default value
            pio.DefaultValue = 4;
            pio.AllowNone = true;

            // Get the value entered by the user
            PromptIntegerResult ires = ed.GetInteger(pio);
            if (ires.Status != PromptStatus.OK)
            {
                return;
            }

            int rownum = ires.Value;

            pio.Message = "\nnEnter the number of columns: ";

            // Restrict input to positive and non-negative values
            pio.AllowZero = false;
            pio.AllowNegative = false;
            // Add default value
            pio.DefaultValue = 8;
            pio.AllowNone = true;

            // Get the value entered by the user
            PromptIntegerResult ires2 = ed.GetInteger(pio);
            if (ires2.Status != PromptStatus.OK)
            {
                return;
            }

            int colnum = ires2.Value;

            double rowstep = 0;
            rowstep = wid / rownum;

            double colstep = 0;
            colstep = leng / colnum;
           
            Database db = ed.Document.Database;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                BlockTableRecord btr = tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;
                Plane plan = new Plane(Point3d.Origin, Vector3d.ZAxis);
                Polyline poly = new Polyline(4);
                int i = 0;
                foreach (Point3d pt in points)
                {
                    poly.AddVertexAt(i, pt.Convert2d(plan), 0, 0, 0);
                    i += 1;
                }
                poly.Closed = true;
                btr.AppendEntity(poly);
                tr.AddNewlyCreatedDBObject(poly, true);

                Point3dCollection vps = new Point3dCollection();
                Point3dCollection hps = new Point3dCollection();
                for (i = 1; i <= rownum - 1; i++)
                {
                    vps.Add(new Point3d(p1.X, p1.Y + (i * rowstep), p1.Z));
                }
                for (i = 1; i <= colnum - 1; i++)
                {
                    hps.Add(new Point3d(p1.X + (i * colstep), p1.Y, p1.Z));
                }
                Line ln = new Line();

                foreach (Point3d pt in vps)
                {
                    ln = new Line(pt, new Point3d(pt.X + leng, pt.Y, 0));
                    btr.AppendEntity(ln);
                    tr.AddNewlyCreatedDBObject(ln, true);
                }
                foreach (Point3d pt in hps)
                {
                    ln = new Line(pt, new Point3d(pt.X, pt.Y + wid, 0));
                    btr.AppendEntity(ln);
                    tr.AddNewlyCreatedDBObject(ln, true);
                }
                tr.Commit();
            }
        }

47
Selection sets / Copy selected objects to other document
« on: December 25, 2012, 02:41:08 PM »
Code: [Select]
        //using System.Windows.Forms;

        static public void createCopyDoc(string fileName) // This method can have any name
        {
            DocumentCollection dm = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager;
            Document doc = dm.MdiActiveDocument;
            try
            {
            using (DocumentLock docloc = doc.LockDocument())
            {

                if (!File.Exists(fileName))
                {
                    Document newdoc = dm.Add("");
                    Database newdb=newdoc.Database;
                    newdb.SaveAs(fileName, DwgVersion.Current);
                    newdoc.CloseAndDiscard();
                }
            }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        [CommandMethod("CSset", CommandFlags.Session)]

        static public void CopySelectedText() // This method can have any name
        {
            string fileName = "c:\\test\\CopySet.dwg"; // add target drawing full name here
            DocumentCollection dm = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager;
            Document doc = dm.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            try
            {
            using (DocumentLock docloc = doc.LockDocument())
            {
                Transaction tr = db.TransactionManager.StartTransaction();

                using (tr)
                {
                    BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);

                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead);

                    // build filter to select texts and mtexts in the model space
                    TypedValue[] tv = new TypedValue[] { new TypedValue((int)DxfCode.Start, "*text"), new TypedValue(410, "Model") };

                    SelectionFilter filt = new SelectionFilter(tv);
                    //perform selection on screen
                    PromptSelectionResult res = ed.GetSelection(filt);

                    SelectionSet sset = res.Value;

                    ObjectId[] idcoll = sset.GetObjectIds();

                    ed.WriteMessage("\nSelected: {0}",  idcoll.Length);

                    ObjectIdCollection ids = new ObjectIdCollection();

                    foreach (ObjectId id in idcoll)
                    {
                        ids.Add(id);
                    } // may use ids.CopyTo(idcoll,idcoll.Length-1) instead

                    // create drawing if does not exists
                    if (!File.Exists(fileName))
                    {
                        createCopyDoc(fileName);

                    }

                    using (Database newdb = new Database(false, true))
                    {

                        newdb.ReadDwgFile(fileName,    System.IO.FileShare.ReadWrite, true, "");

                        using (Transaction newtr = newdb.TransactionManager.StartTransaction())
                        {

                           // Get Block table of target database
                            BlockTable  newbt = (BlockTable)newtr.GetObject(newdb.BlockTableId, OpenMode.ForRead);
                            // Get model space of target database
                            BlockTableRecord newbtr = (BlockTableRecord)newtr.GetObject(newbt[BlockTableRecord.ModelSpace], OpenMode.ForRead);

                        if (ids.Count != 0)
                        {
                            IdMapping iMap = new IdMapping();

                            db.WblockCloneObjects(ids, newbtr.ObjectId, iMap, DuplicateRecordCloning.Ignore, false);
                            // Save target drawing
                            newdb.SaveAs(fileName, DwgVersion.Current);// [A2010] this syntax ought be different for other Acad release
                           

                        }
                        }

                    }

                    tr.Commit();
                }//end using transaction
            }
            }
            catch (System.Exception ex)
            {
                // informative message
                ed.WriteMessage("\n{0}\n", ex.ToString());
                MessageBox.Show(ex.ToString());
            }
        }

48
Polylines / Total length and area of curves
« on: December 12, 2012, 05:12:12 PM »
You can add other entity type to build selection,
here is 2 small programs, tested on A2010
Code: [Select]
    [CommandMethod("tot")]
       
        public void testTotalLength()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Database db = doc.Database;

            Editor ed = doc.Editor;

            double total = 0;

            Transaction tr = doc.TransactionManager.StartOpenCloseTransaction();

            using (tr)
            {

                TypedValue[] tv = new TypedValue[] { new TypedValue((int)DxfCode.Start, "*LINE,ARC") };

                SelectionFilter flt = new SelectionFilter(tv);

                PromptSelectionResult res = ed.GetSelection(flt);

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

                SelectionSet sset = res.Value;

                if (sset.Count == 0) return;

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

                    Curve curv = ent as Curve;

                    if (curv != null)

                        total += curv.GetDistanceAtParameter(curv.EndParam);
                }
                ed.WriteMessage("\nTotal Length:\t{0:f3}\n",total);
            }
        }
      [CommandMethod("toa")]

      public void testTotalArea()
      {
          Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

          Database db = doc.Database;

          Editor ed = doc.Editor;

          double total = 0;

          Transaction tr = doc.TransactionManager.StartOpenCloseTransaction();

          using (tr)
          {
              // build filter to select closed curves and circles
              TypedValue[] tv = new TypedValue[]
              { new TypedValue(-4, "<or"),
                  new TypedValue(-4, "<and"),
                  new TypedValue(0, "*LINE"),
                  new TypedValue(70, 1), new TypedValue(-4, "and>"),
                  new TypedValue(0, "CIRCLE"),
                  new TypedValue(-4, "or>") };

              SelectionFilter flt = new SelectionFilter(tv);

              PromptSelectionResult res = ed.GetSelection(flt);

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

              SelectionSet sset = res.Value;

              if (sset.Count == 0) return;

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

                  Curve curv = ent as Curve;

                  if (curv != null)

                      total += curv.Area;
              }
              ed.WriteMessage("\nTotal Area:\t{0:f3}\n", total);
          }
      }

49
Blocks / Show block tooltip
« on: October 28, 2012, 09:22:47 PM »
To display block info, please, try to hover mouse right on block,
then tooltip message woul be displayed
Tested on A2010 only

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

namespace ToolTips
{
    public class BlockToolTip
    {
        public class Drawing
        {

            Document doc;
            Editor ed;

            public Drawing()
            {
                doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
                ed = doc.Editor;
            }



            [CommandMethod("WWS")]
            public void StartToolTip()
            {
                ed.WriteMessage("\n---   To remove handler type: WWE   ---\n");
                ed.PointMonitor += new PointMonitorEventHandler(ed_PointMonitor);
            }


            void ed_PointMonitor(object sender, PointMonitorEventArgs e)
            {
                Editor ed = (Editor)sender;
                try
                {
                    FullSubentityPath[] paths = e.Context.GetPickedEntities();
                    string attdata = "";
                    Transaction tr = doc.TransactionManager.StartTransaction();
                    using (tr)
                    {
                        foreach (FullSubentityPath path in paths)
                        {
                            ObjectId[] ids = path.GetObjectIds();
                            if (ids.Length > 0)
                            {
                                ObjectId id = ids[0];
                                DBObject obj = tr.GetObject(id, OpenMode.ForRead);
                                if (obj != null)
                                {
                                    BlockReference bref = obj as BlockReference;
                                    if (bref != null)
                                    {
                                        BlockTableRecord bdef = (BlockTableRecord)tr.GetObject(bref.BlockTableRecord, OpenMode.ForRead);
                                        if (!bdef.HasAttributeDefinitions) return;
                                        attdata = GetAttributesData(tr, bref);
                                    }
                                }
                            }
                        }
                        tr.Commit();
                    }
                    if (attdata != "")
                        e.AppendToolTipText(attdata);
                }
                catch (System.Exception ex)
                {
                    Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(ex.Message + "\n" + ex.StackTrace);
                }
            }
            string GetAttributesData(Transaction tr, BlockReference bref)
            {
                int mix = 24;
                int left;
                StringBuilder sb = new StringBuilder();
                left = "Block:".Length;
                sb.AppendLine(String.Format("{0}{1}\n", "Block:".PadRight(mix - 6, ' '), bref.Name));
                var info = (from ObjectId id in bref.AttributeCollection
                            let attref = (AttributeReference)tr.GetObject(id, OpenMode.ForRead, false)
                            select new { key = attref.Tag, value = attref.TextString }).ToArray();
                foreach (var item in info)
                {
                    left = item.key.Length;
                    sb.AppendLine(String.Format("{0}{1}", item.key.PadRight(mix - left, ' '), item.value));
                }
                return sb.ToString();
            }

            [CommandMethod("wwe")]
            public void EndToolTip()
            {
                ed.TurnForcedPickOn();
                ed.PointMonitor -= ed_PointMonitor;
            }
        }
    }
}

50
Blocks / Count blocks by attribute value
« on: August 16, 2012, 10:07:25 PM »
Code: [Select]
        // using System.Linq;
        #region "Selection block by attribute tag"

        //      get the real block name.        //     
        public static string EffectiveName(Transaction tr, BlockReference bref)
        {
            BlockTableRecord btr = null;
            if ((bref.IsDynamicBlock)
                | (bref.Name.StartsWith("*U", StringComparison.InvariantCultureIgnoreCase)))
            {
                btr = tr.GetObject(bref.DynamicBlockTableRecord, OpenMode.ForRead) as BlockTableRecord;
            }
            else
            {
                btr = tr.GetObject(bref.BlockTableRecord, OpenMode.ForRead) as BlockTableRecord;
            }
            return btr.Name;
        }
        [CommandMethod("SelectByAttributeValue", "byval", CommandFlags.Modal)]
        public void GetSelectionByAtt()
        {

            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Database db = doc.Database;

            Editor ed = doc.Editor;

            string m_str = string.Empty;

            PromptStringOptions psto = new PromptStringOptions("\nEnter the tag to find (case-nonsensitive): ");
            // to disable the blank space in user input
            psto.AllowSpaces = false;

            PromptResult pstr = ed.GetString(psto);

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

            m_str = pstr.StringResult.ToUpper();

            List<object[]> blockdata = new List<object[]>();

            PromptSelectionOptions pso = new PromptSelectionOptions();

            pso.MessageForRemoval = "\nFailed to select a blocks!";

            pso.MessageForAdding = "\nPlease select a blocks: ";

            // build filter to select all attributed blocks
            SelectionFilter filter =
                new SelectionFilter(
                new TypedValue[] { new TypedValue(0, "insert"),
                    new TypedValue(66, 1) }
                    );

            // perform block selection
            PromptSelectionResult sres = ed.GetSelection(pso, filter);// might be SelectAll instead

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

                SelectionSet sset = sres.Value;

                using (Transaction tr = db.TransactionManager.StartTransaction())
                {

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

                        BlockReference bref = ent as BlockReference;

                        AttributeCollection attribs = bref.AttributeCollection;

                        foreach (ObjectId attid in attribs)
                        {
                            AttributeReference attref = tr.GetObject(attid, OpenMode.ForRead, false) as AttributeReference;

                            if (attref.Tag == m_str)
                            {

                                object[] datum = new object[] { EffectiveName(tr, bref), attref.Tag, attref.TextString };
                                // add block  info to the list
                                blockdata.Add(datum);

                            }
                        }
                    }
                    // display total result
                    //foreach (object[] item in blockdata)
                    //    ed.WriteMessage("\n{0}\t{1}\t{2}", item[0], item[1],item[2]);
                    var grps = from blk in blockdata
    group blk by new
    {
        Name =blk.ElementAt(0), Tag =blk.ElementAt(1),AttValue=blk.ElementAt(2)
    }
    into grp
    select new
    {
        BlockName=grp.First().ElementAt(0),
        Tag=grp.First().ElementAt(1),
        AttValue=grp.First().ElementAt(2),
        Count= grp.Count()
    };

                    // display subtotals
                    foreach (var grp in grps)
                    {
                        ed.WriteMessage("\n[ Block Name: {0} |Tag: {1} | Value: {2} | Count: {3} ]\n",
                            grp.BlockName,
                            grp.Tag,
                            grp.AttValue,
                            grp.Count
        );
                    }
                    tr.Commit();

                }
            }
            catch (System.Exception ex)
            {
                Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(ex.Message + "\n" + ex.StackTrace);
            }
            finally
            {
            }
        }
        #endregion

~'J'~

51
Blocks / Count blocks by attribute tag
« on: August 16, 2012, 09:34:43 PM »
Code: [Select]
       // using System.Linq;
        #region "Selection block by attribute tag"

        //      get the real block name.        //     
        public static string EffectiveName(Transaction tr, BlockReference bref)
        {
            BlockTableRecord btr = null;
            if ((bref.IsDynamicBlock)
                | (bref.Name.StartsWith("*U", StringComparison.InvariantCultureIgnoreCase)))
            {
                btr = tr.GetObject(bref.DynamicBlockTableRecord, OpenMode.ForRead) as BlockTableRecord;
            }
            else
            {
                btr = tr.GetObject(bref.BlockTableRecord, OpenMode.ForRead) as BlockTableRecord;
            }
            return btr.Name;
        }
        [CommandMethod("SelectByAttribute","byatt", CommandFlags.Modal)]
        public void GetSelectionByAtt()
        {
   
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Database db = doc.Database;

            Editor ed = doc.Editor;

            string m_str = string.Empty;

            PromptStringOptions psto= new PromptStringOptions("\nEnter the tag to find (case-nonsensitive): ");
            // to disable the blank space in user input
            psto.AllowSpaces=false;

            PromptResult pstr= ed.GetString(psto);

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

            m_str= pstr.StringResult.ToUpper();

            List<object[]> blockdata = new List<object[]>();

            PromptSelectionOptions pso = new PromptSelectionOptions();

            pso.MessageForRemoval = "\nFailed to select a blocks!";

            pso.MessageForAdding = "\nPlease select a blocks: ";

            // build filter to select all attributed blocks
            SelectionFilter filter =
                new SelectionFilter(
                new TypedValue[] { new TypedValue(0, "insert"),
                    new TypedValue(66, 1) }
                    );

            // perform block selection
            PromptSelectionResult sres = ed.GetSelection(pso, filter);// might be SelectAll instead

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

            SelectionSet sset = sres.Value;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {

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

                BlockReference bref = ent as BlockReference;

                AttributeCollection attribs = bref.AttributeCollection;

                foreach (  ObjectId attid in attribs)
                {
                    AttributeReference attref= tr.GetObject(attid, OpenMode.ForRead,false) as AttributeReference;

                if (attref.Tag==m_str)
                {
                   
                    object[] datum = new object[]{EffectiveName(tr, bref), attref.Tag,attref.TextString};
                            // add block  info to the list
                            blockdata.Add(datum);
           
                }
                    }
                }
             // display total result
            //foreach (object[] item in blockdata)
            //    ed.WriteMessage("\n{0}\t{1}\t{2}", item[0], item[1],item[2]);

                // group items by name and attribute tag
            var grps = from s in blockdata
                       group s by s[0]  into grp
                       select new
                       {
                           BlockName = grp.Key,
                           Tag = grp.First().ElementAt(1),
                           AttValue = grp.First().ElementAt(2),
                           Count= grp.Count()
                       };
            // display subtotals
            foreach (var grp in grps)
            {
                ed.WriteMessage("\n[ Block Name: {0} |Tag: {1} | Value: {2} | Count: {3} ]\n",
                    grp.BlockName,
                    grp.Tag,
                    grp.AttValue,
                    grp.Count
);
            }
            tr.Commit();

            }           
            }       
            catch (System.Exception ex)
            {
                Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(ex.Message + "\n" + ex.StackTrace);
            }
            finally
            {
            }
        }
        #endregion

~'J'~

52
Text / Add prefix and suffix to the text or mtext
« on: August 14, 2012, 04:16:56 PM »
Code: [Select]
        #region "Add prefix and suffix to the text or mtext multiply"
        [CommandMethod("PSUF")]
        public static void UpdateMultipleTexts()
        {

            Database db = HostApplicationServices.WorkingDatabase;

            Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;

            Transaction tr = db.TransactionManager.StartTransaction();

            string pref = GetstringDflt(ed, "Enter a Prefix: ", "A-");

            string suff = GetstringDflt(ed, "Enter a Suffix: ", "-B");

            using (tr)
            {

                try
                {
                    Entity ent;

                    PromptEntityResult per;

                    ObjectId id;

                    do
                    {
                        PromptEntityOptions peo = new PromptEntityOptions("\nSelect Text >>");
                        peo.SetRejectMessage("\nMust be selected a Text or Mtext only!");

                        peo.AddAllowedClass(typeof(DBText),false);

                        peo.AddAllowedClass(typeof(MText),false);

                        per = ed.GetEntity(peo);

                        if (per.Status != PromptStatus.OK)
                        {
                            break;
                        }
                        id = per.ObjectId;

                        ent = id.GetObject(OpenMode.ForRead) as Entity;

                        ed.WriteMessage("\nObject Selected:\t{0}", ent.GetRXClass().DxfName);

                        if ((!(ent is DBText)) && (!(ent is MText)))
                        {
                            ed.WriteMessage("\nNot a Text or MText");
                            continue;
                        }
                        DBText txt= ent as DBText;
                        if (txt!= null)
                        {
                            txt.UpgradeOpen();
                            string text = txt.TextString;
                            txt.TextString = pref + text+ suff;
                            txt.DowngradeOpen();
                        }

                        MText mtxt = ent as MText;
                        if (mtxt != null)
                        {
                            mtxt.UpgradeOpen();
                            string text = mtxt.Contents;
                            mtxt.Contents = pref + text + suff;
                            mtxt.DowngradeOpen();
                        }
                     
                        db.TransactionManager.QueueForGraphicsFlush();
                    }
                    while (per.Status == PromptStatus.OK);
                    tr.Commit();
                }

                catch (Autodesk.AutoCAD.Runtime.Exception ex)
                {

                    ed.WriteMessage("\n" + ex.StackTrace + "\n" + ex.Message);
                }

            }
        }
        #region "Helpers"
        public static string GetstringDflt(Editor ed, string msg, string dflt)
        {
            string answer = string.Empty;

            PromptStringOptions pso = new PromptStringOptions("\n" + msg);

            if (dflt != string.Empty)
            {
                pso.DefaultValue = dflt;
            }
            pso.AllowSpaces = true;

            PromptResult pr = ed.GetString(pso);

            if (pr.Status == PromptStatus.OK)
            {
                answer = pr.StringResult;
            }
            return answer;
        }
        #endregion

        #endregion

~'J'~

53
3D entities / Create 3D solid by extruding a polyline
« on: August 08, 2012, 09:52:08 PM »
     
Code: [Select]
     // based on C++ code by Virupaksha Aithal from this page:
      //http://adndevblog.typepad.com/autocad/2012/08/create-3d-solid-by-extruding-a-polyline.html
       [CommandMethod("extt")]
        public void CreateExtrude()
        {
            Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("delobj", 1);

            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Database db = doc.Database;

            Editor ed = doc.Editor;

            PromptSelectionOptions pso = new PromptSelectionOptions();

            pso.SingleOnly = true;

            pso.SinglePickInSpace = true;

            pso.MessageForAdding = "\nPlease select a polyline: ";

            pso.MessageForRemoval = "Failed to select a polyline";

            pso.PrepareOptionalDetails = true;

            SelectionFilter filter =
                new SelectionFilter(
                new TypedValue[] { new TypedValue(0, "lwpolyline"),new TypedValue(70, 1) });

            //select the polyline
            PromptSelectionResult sres = ed.GetSelection(pso,filter);

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

            using (Transaction tr = doc.TransactionManager.StartTransaction())
            {
                //get the boundary curves of the polyline

                ObjectId idPoly = sres.Value[0].ObjectId;

                Entity pEntity = tr.GetObject(idPoly, OpenMode.ForRead) as Entity;

                Polyline pPoly = pEntity as Polyline; ;

                if (pPoly == null) return;

                DBObjectCollection lines = new DBObjectCollection();

                pPoly.Explode(lines);

                // Create a region from the set of lines.

                DBObjectCollection regions = new DBObjectCollection();

                regions = Region.CreateFromCurves(lines);

                if (regions.Count == 0)
                {
                    ed.WriteMessage("\nFailed to create region\n");
                    return;
                }

                Region pRegion = (Region)regions[0];

                // Extrude the region to create a solid.

                Solid3d pSolid = new Solid3d();

                pSolid.RecordHistory = true;

                pSolid.Extrude(pRegion, 10.0, 0.0);
           
                ObjectId savedExtrusionId = ObjectId.Null;

                ObjectId modelId;

                modelId = SymbolUtilityServices.GetBlockModelSpaceId(db);

                BlockTableRecord btr = tr.GetObject(modelId, OpenMode.ForWrite) as BlockTableRecord;

                savedExtrusionId = btr.AppendEntity(pSolid);

                tr.AddNewlyCreatedDBObject(pSolid,true);
         
                if (!pPoly.IsWriteEnabled) pPoly.UpgradeOpen();

                pPoly.Erase();
           
                tr.Commit();
            }

        }

~'J'~

54
Blocks / Remove any item from old block, then create new one instead
« on: August 08, 2012, 11:34:00 AM »
Code: [Select]
            public class BlockUtils
    {
        public ObjectIdCollection ids = new ObjectIdCollection();

        public  void curdb_ObjectAppended(object sender, ObjectEventArgs e)
        {

            //add the object id

            ids.Add(e.DBObject.ObjectId);

        }
       
        [CommandMethod("reins")]
        public void ReinsertBlock()
        {

            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Database db = doc.Database;

            Editor ed = doc.Editor;

            try
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {

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

                    BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead, false, true);

                    PromptStringOptions psto = new PromptStringOptions("\nEnter the new block name: ");

                    psto.AllowSpaces = true;

                    PromptResult stres;

                    stres = ed.GetString(psto);

                    if (stres.Status != PromptStatus.OK)

                        return;

                    try
                    {
                        // Validate the provided block name
                        SymbolUtilityServices.ValidateSymbolName(stres.StringResult, false);
                    }
                    catch
                    {
                        ed.WriteMessage("\n\"{0}\"n is an invalid name, try another one.", stres.StringResult);

                        return;
                    }

                    string blockname = stres.StringResult;

                    if (bt.Has(blockname))
                    {
                        Autodesk.AutoCAD.Runtime.ErrorStatus es = ErrorStatus.DuplicateRecordName;

                        ed.WriteMessage("\n{0}\n{1}\n", es.ToString(), "Block already exist, try another name");

                        return;
                    }

                    PromptEntityOptions peo = new PromptEntityOptions("\nSelect block: ");

                    peo.SetRejectMessage("\nYou have to select BlockReference only!");

                    peo.AllowNone = false;

                    peo.AllowObjectOnLockedLayer = true;

                    peo.AddAllowedClass(typeof(BlockReference), false);

                    PromptEntityResult per = ed.GetEntity(peo);

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

                    ObjectId objId = per.ObjectId;

                    if (!objId.ObjectClass.IsDerivedFrom(RXClass.GetClass(typeof(BlockReference))))
                    {

                        ed.WriteMessage( "\nYou didn't select a BlockReference, please try again...\n");

                        return;

                    }

                    DBObject blkobj = (DBObject)tr.GetObject(objId, OpenMode.ForRead, false);

                    BlockReference bref = blkobj as BlockReference;

                    if (bref == null) return;

                    BlockTableRecord btrec = null;

                    btrec = tr.GetObject(bref.BlockTableRecord, OpenMode.ForRead) as BlockTableRecord;

                    DBObjectCollection explobjs = new DBObjectCollection();

                    ids.Clear();
                    // Add event
                    db.ObjectAppended += new ObjectEventHandler(curdb_ObjectAppended);

                    bref.ExplodeToOwnerSpace();

                    // Remove event

                    db.ObjectAppended -= new ObjectEventHandler(curdb_ObjectAppended);

                    ObjectIdCollection newids = new ObjectIdCollection();
             
                    // Create BlockTableRecord
                    Matrix3d ucs2wcs = ed.CurrentUserCoordinateSystem;
                    Matrix3d wcs2ucs = ucs2wcs.Inverse();

                    // Add BlockTableRecord to Database
                    BlockTableRecord newbtr = new BlockTableRecord();

                    newbtr.Origin = btrec.Origin;
                    newbtr.Name = blockname;
                    newbtr.Units = bref.BlockUnit;
                    newbtr.Annotative = btrec.Annotative;
                    bt.UpgradeOpen();

                    ObjectId newblkid = bt.Add(newbtr);
                    tr.AddNewlyCreatedDBObject(newbtr, true);
                    // Pick displacement point, use pan and zoom to find an empty area for copy of the block
                    PromptPointOptions ppo = new PromptPointOptions("\nPick a displacement point: ");
                    ppo.BasePoint = bref.Position;
                    ppo.UseBasePoint = true;
                    ppo.UseDashedLine = true;
                    PromptPointResult pres = ed.GetPoint(ppo);
                    if (pres.Status != PromptStatus.OK) return;
                    Point3d movept = pres.Value;

                    //create vector for displacement
                    Vector3d vectrans = new Vector3d();
                    vectrans = movept.GetAsVector().Subtract(bref.Position.GetAsVector());
                    Matrix3d mat = Matrix3d.Displacement(vectrans);
                    foreach (ObjectId id in ids)
                    {
                        Entity ent = tr.GetObject(id, OpenMode.ForWrite) as Entity;
                        ent.TransformBy(mat);
                        tr.TransactionManager.QueueForGraphicsFlush();
                    }

                    PromptEntityOptions pxo = new PromptEntityOptions("\nSelect entity to remove from block: ");

                    pxo.AllowNone = false;

                    pxo.AllowObjectOnLockedLayer = true;

                    PromptEntityResult pxr = ed.GetEntity(pxo);

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

                    ObjectId exId = pxr.ObjectId;
                 
                    ids.Remove(exId);
                 
                    Entity exnt = (Entity)tr.GetObject(exId, OpenMode.ForWrite);

                    exnt.Erase();

                    exnt.Dispose();

                    newbtr.Origin = movept;

                    newbtr.AssumeOwnershipOf(ids);
                   
               
                  tr.TransactionManager.QueueForGraphicsFlush();
                   
                    if (btrec.HasAttributeDefinitions)
                    {
                        // Transform objects now in block from WCS to UCS
                        // and collect attributes
                        System.Collections.Generic.List<AttributeDefinition> attdefs =
                            new System.Collections.Generic.List<AttributeDefinition>();
                        foreach (ObjectId oid in newbtr)
                        {
                            Entity ent = (Entity)tr.GetObject(oid, OpenMode.ForWrite);
                            ent.TransformBy(wcs2ucs);
                            AttributeDefinition ad = ent as AttributeDefinition;
                            if (ad != null && !ad.Constant) attdefs.Add(ad);
                        }

                        // Create BlockReference
                        using (BlockReference newbref = new BlockReference(Point3d.Origin, bt[blockname]))
                        {
                              newbref.TransformBy(ucs2wcs * Matrix3d.Displacement(movept.GetAsVector()));
                         
                            ObjectContextCollection occ = db.ObjectContextManager.GetContextCollection("ACDB_ANNOTATIONSCALES");
                            if (occ.HasContext(db.Cannoscale.Name))
                                Autodesk.AutoCAD.Internal.ObjectContexts.AddContext(
                                    newbref, occ.GetContext(db.Cannoscale.Name));
                            // Add BlockReference to current space                           
                            m_ctab.AppendEntity(newbref);
                            tr.AddNewlyCreatedDBObject(newbref, true);

                            // Add attributes to BlockReference, if any
                            foreach (AttributeDefinition ad in attdefs)
                                using (AttributeReference attref = new AttributeReference())
                                {
                                    attref.SetAttributeFromBlock(ad, newbref.BlockTransform);
                                    if (ad.IsMTextAttributeDefinition)
                                        attref.UpdateMTextAttribute();
                                    attref.AdjustAlignment(db);
                                    newbref.AttributeCollection.AppendAttribute(attref);
                                    tr.AddNewlyCreatedDBObject(attref, true);
                                }
                        }
                    }
               
                    doc.TransactionManager.FlushGraphics();
                    tr.TransactionManager.QueueForGraphicsFlush();
                    tr.Commit();
                }
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage
                    (ex.Message + "\n" + ex.StackTrace);
            }
            finally
            {
            }
        }
    }

~'J'~

55
Layouts and printing / Delete layout without transaction
« on: August 05, 2012, 11:47:41 AM »
Code: [Select]
        [CommandMethod("dellt")]
        public void DelLayout()
        {
           // put desired layout name:
            string laytName = "D-Size Layout";// may have any layout name belongs to current drawing

            LayoutManager laytmgr = LayoutManager.Current;
            try
            {
                laytmgr.DeleteLayout(laytName);

                Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.Regen();
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage
                    (ex.Message + "\n" + ex.StackTrace);

            }
     
        }

~'J'~

56
Blocks / Move all attributes to the new positions
« on: August 05, 2012, 07:05:58 AM »
Code: [Select]
        // move attributes to the new positions
        // run command ATTSYNC manually to display result
        // right after the command is finished
        [CommandMethod("DAR")]

        static public void MoveAttributeReferences()
        {

            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Database db = doc.Database;

            Editor ed = doc.Editor;

            // Select a block reference

            PromptEntityOptions peo = new PromptEntityOptions("\nSelect a block reference:");

            peo.SetRejectMessage("\nMust be block reference...");

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

            PromptEntityResult per = ed.GetEntity(peo);

            if (per.Status != PromptStatus.OK)

                return;

            // Select attribute reference

            PromptNestedEntityOptions pno = new PromptNestedEntityOptions("\nSelect an attribute ");

            PromptNestedEntityResult nres = ed.GetNestedEntity(pno);

            if (nres.Status != PromptStatus.OK)
            {
                ed.WriteMessage("\nAttribute nentsel failed");

                return;
            }
            Point3d spickPt = nres.PickedPoint;

            ed.WriteMessage("\nPicked point is {0}", spickPt);

            ObjectId sselId = nres.ObjectId;

            List<ObjectId> enIds = new List<ObjectId>(nres.GetContainers());

            // Reverse the "containers" list

            // Now append the selected entity

            enIds.Add(sselId);

            enIds.Reverse();

            // Retrieve the sub-entity path for this entity

            SubentityId subent = new SubentityId(SubentityType.Null, 0);

            FullSubentityPath path = new FullSubentityPath(enIds.ToArray(), subent);

            // Open the outermost container, relying on the open

            // transaction...


            Transaction tr = db.TransactionManager.StartTransaction();

            using (tr)
            {

                // This time we just open the block reference

                BlockReference br = (BlockReference)tr.GetObject(per.ObjectId, OpenMode.ForRead);

                // If the block reference has attribute references...

                if (br.AttributeCollection.Count == 0) return;

                BlockTableRecord owner;

                owner = (BlockTableRecord)tr.GetObject(br.BlockTableRecord, OpenMode.ForRead);
                if (br.IsDynamicBlock)
                {
                    owner = (BlockTableRecord)tr.GetObject(br.DynamicBlockTableRecord, OpenMode.ForRead);
                }
                owner.UpgradeOpen();


                Entity attent = tr.GetObject(enIds[0], OpenMode.ForRead, false) as Entity;

                AttributeReference attref = attent as AttributeReference;

                Point3d pt = attref.Position;

                PromptPointOptions ppo = new PromptPointOptions("\nSpecify the new attribute position: ");

                ppo.BasePoint=pt;

                ppo.UseBasePoint = true;

                ppo.UseDashedLine = true;

                PromptPointResult pres = ed.GetPoint(ppo);

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

                Point3d dp = pres.Value;

                Vector3d vec = pt.GetVectorTo(dp);

                Matrix3d mat = Matrix3d.Displacement(vec);

                foreach (ObjectId id in owner)
                {
                    if (id.ObjectClass.IsDerivedFrom(RXClass.GetClass(typeof(AttributeDefinition))))
                    {
                        AttributeDefinition attdef = (AttributeDefinition)tr.GetObject(id, OpenMode.ForRead);

                        attdef.UpgradeOpen();
                         // move attribute
                        attdef.TransformBy(mat);

                        attdef.DowngradeOpen();

                        //attdef.Erase();// debug only, commented

                    }
                }
         
                owner.DowngradeOpen();

                tr.Commit();

            }

        }

~'J'~

57
Polylines / Copy polyline segment
« on: July 30, 2012, 07:20:52 PM »
 C#
Code: [Select]
    [CommandMethod("copyseg")]
        public void copySegment()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            Database db = doc.Database;
            PromptEntityOptions peo = new PromptEntityOptions("\nSelect the segment to copy: ");
            peo.SetRejectMessage("\nYou have to select polyline only!");
            peo.AllowNone = false;
            peo.AllowObjectOnLockedLayer = false;
            peo.AddAllowedClass(typeof(Polyline), true);
            PromptEntityResult per = ed.GetEntity(peo);
            if (per.Status == PromptStatus.OK)
            {
 
                ObjectId objId = per.ObjectId;
                try
                {
                    using (Transaction tr = db.TransactionManager.StartTransaction())
                    {
                        Polyline pline = tr.GetObject(objId, OpenMode.ForRead, false) as Polyline;
                        if (pline != null)
                        {
                            BlockTableRecord btr = tr.GetObject(db.CurrentSpaceId,OpenMode.ForWrite, false) as BlockTableRecord;
                            Point3d pickPt = pline.GetClosestPointTo((Point3d)per.PickedPoint, false);
                            double param = pline.GetParameterAtPoint(pickPt);
                            int index = (int)param;
                          double swid=  pline.GetStartWidthAt(index);
                          double ewid = pline.GetEndWidthAt(index);

                          SegmentType stype=  pline.GetSegmentType(index);
                          if (stype == SegmentType.Line)
                          {
                             LineSegment2d lineseg= pline.GetLineSegment2dAt(index);
                              Polyline spoly = new Polyline();
                              Point2d sp = lineseg.StartPoint;
                              Point2d ep = lineseg.EndPoint;
                              spoly.AddVertexAt(0, sp, 0, swid, ewid);
                              spoly.AddVertexAt(1, ep,0,swid,ewid);
                              spoly.ColorIndex = 1;
                              btr.AppendEntity(spoly);
                              tr.AddNewlyCreatedDBObject(spoly, true);

                          }
                          if (stype == SegmentType.Arc)
                          {
                              CircularArc2d arcseg = pline.GetArcSegment2dAt(index);
                              Polyline spoly = new Polyline();
                              Point2d sp = arcseg.StartPoint;
                              Point2d ep = arcseg.EndPoint;
                              double boo = pline.GetBulgeAt(index);
                              spoly.AddVertexAt(0, sp, boo, swid, ewid);
                              spoly.AddVertexAt(1, ep, boo, swid, ewid);
                              spoly.ColorIndex = 2;
                              btr.AppendEntity(spoly);
                              tr.AddNewlyCreatedDBObject(spoly, true);

                          }
                        }
                        tr.Commit();
                    }
                }
                catch (System.Exception ex)
                {
   
                    ed.WriteMessage("\nError: {0}\nTrace: {1}" , ex.Message , ex.StackTrace);
                }
            }
        }


VB.NET
Code: [Select]
      <CommandMethod("copyseg")> _
        Public Sub copySegment()
            Dim doc As Document = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument
            Dim ed As Editor = doc.Editor
            Dim db As Database = doc.Database
            Dim peo As New PromptEntityOptions(vbLf & "Select the segment to copy: ")
            peo.SetRejectMessage(vbLf & "You have to select polyline only!")
            peo.AllowNone = False
            peo.AllowObjectOnLockedLayer = False
            peo.AddAllowedClass(GetType(Polyline), True)
            Dim per As PromptEntityResult = ed.GetEntity(peo)
            If per.Status = PromptStatus.OK Then

                Dim objId As ObjectId = per.ObjectId
                Try
                    Using tr As Transaction = db.TransactionManager.StartTransaction()
                        Dim pline As Polyline = TryCast(tr.GetObject(objId, OpenMode.ForRead, False), Polyline)
                        If pline IsNot Nothing Then
                            Dim btr As BlockTableRecord = TryCast(tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite, False), BlockTableRecord)
                            Dim pickPt As Point3d = pline.GetClosestPointTo(per.PickedPoint, False)
                            Dim param As Double = pline.GetParameterAtPoint(pickPt)
                            Dim index As Integer = CInt(Math.Truncate(param))
                            Dim swid As Double = pline.GetStartWidthAt(index)
                            Dim ewid As Double = pline.GetEndWidthAt(index)

                            Dim stype As SegmentType = pline.GetSegmentType(index)
                            If stype = SegmentType.Line Then
                                Dim lineseg As LineSegment2d = pline.GetLineSegment2dAt(index)
                                Dim spoly As New Polyline()
                                Dim sp As Point2d = lineseg.StartPoint
                                Dim ep As Point2d = lineseg.EndPoint
                                spoly.AddVertexAt(0, sp, 0, swid, ewid)
                                spoly.AddVertexAt(1, ep, 0, swid, ewid)
                                spoly.ColorIndex = 1
                                btr.AppendEntity(spoly)
                                tr.AddNewlyCreatedDBObject(spoly, True)
                            End If

                            If stype = SegmentType.Arc Then
                                Dim arcseg As CircularArc2d = pline.GetArcSegment2dAt(index)
                                Dim spoly As New Polyline()
                                Dim sp As Point2d = arcseg.StartPoint
                                Dim ep As Point2d = arcseg.EndPoint
                                Dim boo As Double = pline.GetBulgeAt(index)
                                spoly.AddVertexAt(0, sp, boo, swid, ewid)
                                spoly.AddVertexAt(1, ep, boo, swid, ewid)
                                spoly.ColorIndex = 2
                                btr.AppendEntity(spoly)
                                tr.AddNewlyCreatedDBObject(spoly, True)
                            End If

                        End If
                        tr.Commit()
                    End Using
                Catch ex As System.Exception

                    ed.WriteMessage(vbLf & "Error: {0}" & vbLf & "Trace: {1}", ex.Message, ex.StackTrace)
                End Try
            End If
        End Sub

59
Dimensions / Reset dimension values
« on: July 23, 2012, 02:31:22 PM »
Code: [Select]
    // tested on AutoCAD 2010
       [CommandMethod("ResetDimValues", "rdv", CommandFlags.Modal | CommandFlags.Redraw)]
        public void ResetDims()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            Database db = doc.Database;

            TypedValue[] values = new TypedValue[] { new TypedValue(0, "DIMENSION") };
            SelectionFilter filter = new SelectionFilter(values);
            PromptSelectionOptions opts = new PromptSelectionOptions();

            opts.MessageForRemoval = "\nMust be a type of Dimension!";
            opts.MessageForAdding = "\nSelect dimensions to reset : ";
            opts.PrepareOptionalDetails = false;
            opts.SingleOnly = false;
            opts.SinglePickInSpace = false;
            opts.AllowDuplicates = true;
            PromptSelectionResult result = ed.GetSelection(opts, filter);
            if (result.Status != PromptStatus.OK) return;
            try
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    SelectionSet sset = result.Value;
                    foreach (SelectedObject selobj in sset)
                    {
                        DBObject obj = tr.GetObject(selobj.ObjectId, OpenMode.ForWrite, false) as DBObject;
                        Dimension dim = obj as Dimension;
                        if (dim != null)
                        {
                            dim.DimensionText = "<>";
                        }
                    }
                    tr.Commit();
                }
            }
            catch (System.Exception ex)
            {
                ed.WriteMessage("\nProblem updating  dimensions.\n");
                ed.WriteMessage(ex.Message);
            }
        }

~'J'~

60
Text / Copy text to Leader
« on: July 23, 2012, 09:58:02 AM »
Code: [Select]
   // tested on AutoCAD 2010
       [CommandMethod("CopyTextToLeader", "ttl", CommandFlags.Redraw)]
        public void TextToMleader()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Editor ed = doc.Editor;

            Database db = doc.Database;
            // save current DIMBLK variable
            string dblk = Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("DIMBLK").ToString();
            try
            {
                PromptEntityOptions peo =
                 new PromptEntityOptions("\nSelect Text / MText: ");
                peo.SetRejectMessage("\nMust be select type of Text or MText.");
                peo.AddAllowedClass(typeof(DBText), false);
                peo.AddAllowedClass(typeof(MText), false);
                PromptEntityResult per = ed.GetEntity(peo);
                if (per.Status != PromptStatus.OK) return;
                ObjectId txtId = per.ObjectId;
                PromptPointOptions opt = new PromptPointOptions("\nSpecify leader arrowhead location: ");
                PromptPointResult res = ed.GetPoint(opt);

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

                Point3d pt = res.Value;

                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;
                    ObjectId blkid = ObjectId.Null;
                    DBObject obj = (DBObject)tr.GetObject(txtId, OpenMode.ForWrite) as DBObject;
                    ed.WriteMessage("\nType\t{0}\n", obj.GetRXClass().DxfName);
                    DBText txtobj = null;
                    MText mtxtobj = null;
                    Point3d tp = new Point3d();
                    if (obj.GetRXClass().DxfName == "TEXT")
                    {
                        txtobj = obj as DBText;
                        if (txtobj == null) return;
                        tp = txtobj.Position;
                    }
                    if (obj.GetRXClass().DxfName == "MTEXT")
                    {
                        mtxtobj = obj as MText;
                        if (mtxtobj == null) return;
                        tp = mtxtobj.Location;
                    }

                   Leader leader = new Leader();
                   // Create the MText annotation
                   MText copymtx = new MText();
                   if (mtxtobj != null)
                   {
                       copymtx = mtxtobj.Clone() as MText;
                   }
                   if (txtobj != null)
                   {
                       copymtx = new MText();
                       copymtx.Location = txtobj.Position;
                       copymtx.Contents = txtobj.TextString;
                   }

                   // Add the new object to current space and the transaction
                   btr.AppendEntity(copymtx);
                   tr.AddNewlyCreatedDBObject(copymtx, true);

                   
                   if (txtobj != null)
                   {
                       leader.TextStyleId = txtobj.TextStyleId;
                   }
                   if (mtxtobj != null)
                   {
                       leader.TextStyleId = mtxtobj.TextStyleId;
                   }

                    // set arrow head block to DOT
                    if (!bt.Has("_DOT"))
                    {
                        Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("DIMBLK", "_DOT");

                    }
                    leader.HasArrowHead = true;
                    leader.Dimldrblk = bt["_DOT"];
                    leader.Dimasz = db.Dimtxt * 0.2;
                    leader.AppendVertex(pt);
                    leader.AppendVertex(tp);

                    btr.AppendEntity(leader);
                    tr.AddNewlyCreatedDBObject(leader, true);
                    // attach the annotation after the leader object is added
                    leader.Annotation = copymtx.ObjectId;
                    // evaluate leader
                    leader.EvaluateLeader();
                    // erase prototypes
                    if (mtxtobj != null) mtxtobj.Erase();
                    if (txtobj != null) txtobj.Erase();

                    tr.Commit();
                }
            }
            catch (System.Exception ex)
            {
                ed.WriteMessage("\nError: {0}\nTrace: {1}", ex.Message, ex.StackTrace);
            }
            finally
            {
                // reset DIMBLK
                if (dblk != "")
                {
                    Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("DIMBLK", dblk);
                }
                else
                {
                    Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("DIMBLK", ".");
                }
            }
        }

~'J'~

Pages: 1 2 3 [4] 5 6 7