Recent Posts

Pages: 1 ... 7 8 [9] 10
81
Visual Studio environment / Re: Search window doesn't stay put
« Last post by Javedsameena on January 18, 2013, 09:21:01 AM »
I was suggested this forum by my cousin. I’m not sure whether this post is written by him as no one else know such detailed about my difficulty. You are incredible! Thanks!
82
Dimensions / Get the geometry from a dimension entity
« Last post by fixo on January 17, 2013, 11:04:00 PM »
Code: [Select]
        // Get the geometry from a dimension entity
        // translated on C# from article by  Augusto Goncalves:
        // http://adndevblog.typepad.com/autocad/2013/01/get-the-geometry-from-a-dimension-entity.html
        [CommandMethod("dgeom", CommandFlags.UsePickSet)]
        public void GetDimensionLinesData()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Editor ed = doc.Editor;

            Database db = doc.Database;

            Transaction tr = doc.TransactionManager.StartOpenCloseTransaction();

            using (tr)
            {

                Dimension diment = null;

                PromptEntityOptions peo = new PromptEntityOptions("\nSelect a Dimension>>");
                peo.SetRejectMessage("\nSelect Dimension only >>");
                peo.AddAllowedClass(typeof(Dimension), false);
                PromptEntityResult res;
                res = ed.GetEntity(peo);
                if (res.Status != PromptStatus.OK)
                    return;
                Entity ent = (Entity)tr.GetObject(res.ObjectId, OpenMode.ForRead);
                if (ent == null)
                    return;
                diment = (Dimension)ent as Dimension;
                if (diment == null)
                {
                    ed.WriteMessage("\nError: selected entity is not a Dimension");
                    return;
                }
                //get current space
                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                //get dimension block definition
                BlockTableRecord dimbtr = tr.GetObject(diment.DimBlockId, OpenMode.ForRead) as BlockTableRecord;
                MessageBox.Show(dimbtr.Name);
                BlockTableRecordEnumerator iter = dimbtr.GetEnumerator();
                Entity obj;
                // Iterate every entity stored in the
                // block definition of the dimension.
                while (iter.MoveNext())
                {
                   
                    obj = tr.GetObject((ObjectId)iter.Current, OpenMode.ForRead) as Entity;

                    Line ln = obj as Line;

                    if (ln != null)
                    {

                        // Get the start and end point. 

                        Point3d sp, ep;

                        sp = ln.StartPoint;
                        ep = ln.EndPoint;


                        //     // Transform the start and end point.   

                        //     // Get the transformation matrix.   

                        Matrix3d mat = new Matrix3d();

                        // Get the axis of the dimension entity.

                        Vector3d zAxis = diment.Normal;

                        Vector3d xAxis = zAxis.GetPerpendicularVector();

                        Vector3d yAxis = zAxis.CrossProduct(xAxis);

                        // Build the transformation matrix.   
                       
                        mat = Matrix3d.AlignCoordinateSystem(Point3d.Origin, new Vector3d(1.0, 0.0, 0.0),

                          new Vector3d(0.0, 1.0, 0.0),

                          new Vector3d(0.0, 0.0, 1.0),

                          Point3d.Origin,

                          xAxis, yAxis, zAxis);
                     

                        // To test this matrix create a new line   

                        // using the start and endpoint of the line

                        // from the block definition, and transform   

                        // the line using the calculated transformation matrix.     

                        Line newln = new Line(sp, ep);

                        newln.TransformBy(mat);

                        Point3d nptStart, nptEnd;

                        nptStart = newln.StartPoint;

                        nptEnd = newln.EndPoint;

                        newln.ColorIndex = 4;

                        // Append the new line to the model space and close it.   

                        // The new line should be at the location     

                        // of the dimension entity.     

                       
                        btr.AppendEntity(newln);
                        tr.AddNewlyCreatedDBObject(newln, true);
               
                    }

                    tr.Commit();

                }
            }
        }
83
Blocks / How to edit block parameters from a windows form (c#)?
« Last post by JohannesRP on January 17, 2013, 04:13:34 PM »
Hi, i try to change several dynamic blocks using my own application. I have a com connection with AuotCAD 2013 and i can run through all block definitions.
When i run through the block def. in AutoCad i can identify the one i want to change the parameters. But how to continue? How can i set the "heightLeft" to another value?

Code: [Select]
private void bt_openTemplate_Click(object sender, EventArgs e)
        {
            AcadApplication acadApp = null;
            AcadBlocks acadblock = null;
           
            try
            {
                object obj = Marshal.GetActiveObject("AutoCAD.Application.19");
               
                if (obj != null)
                {
                    acadApp = obj as AcadApplication;
                    acadblock = acadApp.ActiveDocument.Blocks;

                    string name = "";

                    foreach (AcadBlock  b in acadblock)
                    {
                        name = name + " :: " + b.Name;

                        if (b.Name == "WT")
                        {
                           
// HELP!!!
// Here i need to change the properties of the block with name "WT"
                           
                        }
                    }
                    tb.Text = name;
                }
                else
                {
                    MessageBox.Show("AutoCAD is not open or version is not right.");
                }
            }
            catch
            {
                MessageBox.Show("AutoCAD is not open or version is not right.");
            }
        }
    }


The main idea is to change several blocks at the same time by changing only one value in my application.

regards
Johannes
84
Blocks / How to place blocks in a rectangular area evenly
« Last post by fixo on January 15, 2013, 09:43:33 PM »
This one is written on C# only
Please, change block name and sizes to your suit
85
Polylines / Create 3d polyline from points
« Last post by fixo on January 12, 2013, 11:03:35 PM »
Code: [Select]
        [CommandMethod("c3p")]
        static public void Create3dPolyline()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;

         Transaction tr = db.TransactionManager.StartTransaction();

            using (tr)
            {
                // Get blocktable and modelspace (for write)
                BlockTable bt =  (BlockTable)tr.GetObject(   db.BlockTableId, OpenMode.ForRead,  false);

                BlockTableRecord btr =(BlockTableRecord)tr.GetObject( bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite, false );
               
                // Create a 3D polyline with 6 segments (closed)
                Point3d[] pts = new Point3d[]
                        { new Point3d(0,0,0),
                          new Point3d(60,0,0),
                         new Point3d(60,0,60),
                         new Point3d(60,60,60),
                         new Point3d(0,60,60),
                         new Point3d(0,0,60)
                        };
                Point3dCollection points = new Point3dCollection(pts);

                Polyline3d poly = new Polyline3d();
                // First add polyline to model space and transaction
                btr.AppendEntity(poly);

                tr.AddNewlyCreatedDBObject(poly, true);
                // Then add all vertices to polyline from point collection
                foreach (Point3d pt in points)
                {
                    // Now create the vertices

                    PolylineVertex3d vex3d = new PolylineVertex3d(pt);

                    // And add them to the 3dpoly (this adds them to the db also)

                    poly.AppendVertex(vex3d);

                    tr.AddNewlyCreatedDBObject(vex3d, true);
                   
                }
                // Make polyline closed
                poly.Closed = true;
                // Change color
                poly.ColorIndex = 14;
                // Commit transaction
                tr.Commit();

            }
        }
86
Selection sets / A reliable way to select the entities with ed.Getentity method
« Last post by fixo on January 11, 2013, 06:31:39 AM »
 
Code: [Select]
              public static ErrorStatus fixoGetEntity(Transaction tr, Editor ed, RXClass rx, string msg, out ObjectId id)
        {
            ErrorStatus es;
            Entity ent;
            id = ObjectId.Null;
            PromptEntityOptions peo = new PromptEntityOptions(msg);
            peo.SetRejectMessage("\nYou're missing, try again >>");
            peo.AddAllowedClass(typeof(Entity), false);
            PromptEntityResult res;
            res = ed.GetEntity(peo);
            if (res.Status != PromptStatus.OK)
                es = ErrorStatus.PointNotOnEntity;
            id = res.ObjectId;
            if (id == ObjectId.Null)
                es = ErrorStatus.NullObjectId;
            ent = tr.GetObject(id, OpenMode.ForRead, false) as Entity;
            if (ent.GetRXClass() != rx)
            {
                ed.WriteMessage("\n{0}Must be a \"{0}\" type of only!",rx.DxfName);
                es = ErrorStatus.NotThatKindOfClass;
            }
            if (ent == null)
                es = ErrorStatus.NotAnEntity;
            else es = ErrorStatus.OK;
            return es;
        }
         

        // Use function above this way
        [CommandMethod("tef")]
        public static void testSelectFunction()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            Database db = doc.Database;
            ObjectId id = ObjectId.Null;
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
               if (fixoGetEntity(tr, ed, RXClass.GetClass(typeof(MText)), "\nSelect MTEXT to edit", out id) == ErrorStatus.OK)
                {
                    ed.WriteMessage("\nObjectId: {0}\n", id);
                    ed.WriteMessage("\nEntity Name: {0}\n", id.ObjectClass.DxfName);
                    // get entity by direct cast
                    Entity ent = (Entity)tr.GetObject(id, OpenMode.ForWrite);
                    ent.ColorIndex = 121;// do whatever you need with entity here
                    tr.Commit();
                }
            }
        }
87
Polylines / Getting the Midpoint of each Polyline Segment
« Last post by fixo on January 10, 2013, 03:08:32 PM »
        Getting the Midpoint of each Polyline Segment
        based on article by Fenton Webb here:
        http://adndevblog.typepad.com/autocad/2013/01/getting-the-midpoint-of-each-polyline-segment-using-objectarx.html
Code: [Select]
        [CommandMethod("smp")] //OK  //
        public void ShowMidPointOnEachSegment()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Editor ed = doc.Editor;

            Database db = HostApplicationServices.WorkingDatabase;
            Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("pdmode", (short)34);
            Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("pdsize", (double)5.0);
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                 BlockTableRecord btr = tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;
             
                    Entity ename;

                    PromptEntityResult retval = ed.GetEntity("\nSelect LW polyline: ");

                    if (retval.Status != PromptStatus.OK)

                        return;

                    Curve curv;

                    ObjectId id;

                    id = retval.ObjectId;

                    ename = tr.GetObject(id, OpenMode.ForWrite) as Entity;

                    curv = ename as Polyline;
                    if (curv == null)
                    {
                        ed.WriteMessage("\nSelected entity is not a LW polyline");
                        return;
                    }
                    if (!curv.IsWriteEnabled)
                        curv.UpgradeOpen();

                    double startParam, endParam;

                    // get the start param, usually it starts at 0 or 1

                    startParam = curv.StartParam;

                    ed.WriteMessage("\nStartParam is: {0:f3}\n", startParam);

                    // get the end param, for a polyline it's the total number of

                    // vertex's -1

                    endParam = curv.EndParam;

                    ed.WriteMessage("\nEndParam is: {0:f3}\n", endParam);

                    // now loop the parameters, adding 1.0 each iteration

                    for (double i = startParam; i < endParam; ++i)
                    {

                        Point3d pt;

                        pt = curv.GetPointAtParameter(i + 0.5);
                        // create points to display result
                        DBPoint dp = new DBPoint(pt);
                        dp.ColorIndex = 1;
                        btr.AppendEntity(dp);

                        tr.AddNewlyCreatedDBObject(dp, true);

                        ed.WriteMessage("\nMid Point: {0:f3},{1:f3},{2:f3}\n", pt[0], pt[1], pt[2]);

                    }
                    tr.Commit();
                }
            }
88
Polylines / Create region from connected arcs and lines
« Last post by fixo on January 10, 2013, 08:23:44 AM »
Code: [Select]
        //Create region from connected arcs and lines
        [CommandMethod("craw")]
        public static void CreateRegionFromConnected()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Editor ed = doc.Editor;

            Database db = doc.Database;

            DBObjectCollection objs = new DBObjectCollection();

            DBObjectCollection regcoll = new DBObjectCollection();

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

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

                TypedValue[] tvs = new TypedValue[] { new TypedValue(0, "line,arc") };

                Point3dCollection points = new Point3dCollection();

                SelectionFilter sf = new SelectionFilter(tvs);

                PromptSelectionResult sres = ed.GetSelection(sf);

                if (sres.Status != PromptStatus.OK)
                {
                    ed.WriteMessage("\nInvalid selection!");

                    return;
                }

                foreach (SelectedObject selobj in sres.Value)
                {
                    DBObject obj = tr.GetObject(selobj.ObjectId, OpenMode.ForWrite, false) as DBObject;

                    objs.Add(obj);

                }

                regcoll = Region.CreateFromCurves(objs);

                Region reg = regcoll[0] as Region;

                btr.AppendEntity(reg);

                tr.AddNewlyCreatedDBObject(reg, true);
                // you might be want to remove the parent objects here,
                // because of DELOBJ variable did not effect :
                //foreach (DBObject obj in objs)
                //    obj.Erase();  // uncomment this code block if needs

                tr.Commit();
            }
        }
89
Blocks / How to insert multiline attributes
« Last post by fixo on January 09, 2013, 08:07:58 PM »

Code: [Select]
        // based on code example from article by by Gopinath Taget here:
        //  http://adndevblog.typepad.com/autocad/2013/01/how-to-mimic-the-autocad-insert-command-in-arx-without-acedcommand-call.html

        [CommandMethod("testInsertCommand", "doi", CommandFlags.UsePickSet | CommandFlags.Redraw)]
        public static void DoInsert()
        {

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

            Editor ed = doc.Editor;

            Database db = doc.Database;
            // set your block name here
            string blockName = "UserName";

            ObjectId blockId;
            // dictionary to store pairs of tag-string
            Dictionary<string, string> dict = new Dictionary<string, string>();
            //populate dictionary with exact values to your block
            string[,] pairs = new string[,] { { "TAG1", "VALUE 1" },
            { "TAG2", "VALUE 2" },
            { "TAG3", "VALUE 3" },
            { "TAG4",
          "Some text in the default colour...\\P" +
          "{\\C1;Something red}\\P" +
          "{\\C2;Something yellow}\\P" +
          "{\\C3;And} {\\C4;something cyan}" } };

            for (int i=0;i<=pairs.GetUpperBound(0);i++)
                dict.Add(pairs[i,0], pairs[i,1]);
            //------------------------------------------------------------
            //  debug only:
            //  foreach (KeyValuePair<string, string> kvp in dict)
            //    ed.WriteMessage("\n{0}\t{1}\n", kvp.Key, kvp.Value);
            //------------------------------------------------------------

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
                if (!bt.Has(blockName)) return;
                blockId = bt[blockName];
               
                PromptPointOptions ppo = new PromptPointOptions("\nPlease specify insertion point of block: ");
                PromptPointResult ppr = ed.GetPoint(ppo);
                if (ppr.Status != PromptStatus.OK) return;
                Point3d basePoint = ppr.Value;
                AddBlockWithAttributes(db, dict, blockId, basePoint);         
                tr.Commit();
                ed.UpdateScreen();
            }

        }


        //Here is the code for addBlockWithAttributes:

        // NOTE: You will have to update the code to properly set the

        // attribute values. The code below sets the value of each

        // attribute from dictionary.

        static public void AddBlockWithAttributes(Database db, Dictionary<string, string> dict, ObjectId blockId, Point3d basePoint)
        {
            try
            {
                Transaction tr = db.TransactionManager.StartTransaction();

                using (tr)
                {
                    //----- Step 1: Allocate a block reference object

                    BlockReference bref = new BlockReference(basePoint, blockId);

                    //----- Step 2: Set up the block reference to the newly

                    //----- created block definition

                    // pBlkRef.BlockTableRecord =blockId ;

                    //---- Give it the current UCS normal.

                    bref.Rotation = 0.0;

                    bref.Normal = new Vector3d(0.0, 0.0, 1.0);

                    //----- Step 3: Open current database's Model Space

                    //----- blockTableRecord

                    BlockTable bt;

                    BlockTableRecord btr;

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

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

                    //----- Append the block reference to the model space

                    //----- block table record

                    ObjectId newEntId;

                    newEntId = btr.AppendEntity(bref);

                    tr.AddNewlyCreatedDBObject(bref, true);

                    //----- Step 4: Open the block definition for read

                    BlockTableRecord blkDef;

                    blkDef = (BlockTableRecord)tr.GetObject(blockId, OpenMode.ForRead);

                    Entity ent;

                    AttributeDefinition attDef;

                    AttributeCollection attColl = bref.AttributeCollection;

                    foreach (ObjectId id in blkDef)
                    {
                        // Commented, you can use 'foreach' instead:
                        // BlockTableRecordEnumerator ienum = blkDef.GetEnumerator();
                        //while (ienum.MoveNext())
                        //{

                        //----- Get the next entity

                        // ent = (Entity)tr.GetObject(ienum.Current, OpenMode.ForRead);// commented
                        ent = (Entity)tr.GetObject(id, OpenMode.ForRead);
                        //----- Make sure the entity is an attribute definition

                        //----- and not a constant

                        attDef = ent as AttributeDefinition;

                        if (attDef != null && !attDef.Constant)
                        {

                            //----- We have a non-constant attribute definition

                            //----- so build an attribute entity

                            AttributeReference attRef = new AttributeReference();

                          //  attRef.SetAttributeFromBlock(attDef, bref.BlockTransform);

                            attRef.SetPropertiesFrom(attDef);

                            attRef.Visible = attDef.Visible;

                            //----- Translate attribute by block reference.

                            //----- To be really correct, entire block

                            //----- reference transform should be applied here.

                            basePoint = attDef.Position;

                            basePoint += bref.Position.GetAsVector();

                            attRef.Position = basePoint;

                            attRef.Height = attDef.Height;

                            attRef.Rotation = attDef.Rotation;

                            attRef.Tag = attDef.Tag;

                            attRef.FieldLength = attDef.FieldLength;

                            //----- Database Column value should be displayed

                            //----- INSERT would prompt for this...

                            //------ Update attribute value from dictionary by tag
                            if (attDef.IsMTextAttributeDefinition)
                            {
                                attRef.IsMTextAttribute = true;
                             
                                attRef.TextString = dict[attDef.Tag.ToUpper()];
                                attRef.ForceAnnoAllVisible = true;
                                attRef.UpdateMTextAttribute();
                               
                            }
                            else
                            {
                                attRef.TextString = dict[attDef.Tag.ToUpper()];
                            }
                            //----- Set Alignments

                            attRef.HorizontalMode = attDef.HorizontalMode;

                            attRef.VerticalMode = attDef.VerticalMode;

                            attRef.AdjustAlignment(db);
                            //----- Insert the attribute in the DWG

                            attColl.AppendAttribute(attRef);


                        }
                    }

                    bref.RecordGraphicsModified(true);//    optional
                   
                    tr.Commit();
                }
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                // MessageBox.Show(string.Format("Error: {0}\nTrace: {1}", ex.Message, ex.StackTrace));
                Console.WriteLine(string.Format("Error: {0}\nTrace: {1}", ex.Message, ex.StackTrace));
            }
            finally { }
        }
90
Math and Geometry / Create arc by 3 points
« Last post by fixo on January 08, 2013, 07:43:41 PM »
Code: [Select]
        [CommandMethod("CreateArcBy3Points", "cra3p", CommandFlags.Modal | CommandFlags.UsePickSet | CommandFlags.Redraw)]
        public void CreateArcByThreePoints()
        {
            short osm = (short)Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("osmode");
            Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("osmode", 0);
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Editor ed = doc.Editor;

            Database db = doc.Database;

            // get the points

            Point3d p1, p2, p3;
            PromptPointOptions ppo = new PromptPointOptions("\nFirst point: ");
            PromptPointResult ppr = ed.GetPoint(ppo);
            if (ppr.Status != PromptStatus.OK) return;
            p1 = ppr.Value;

            ppo = new PromptPointOptions("\nSecond point: ");
            ppr = ed.GetPoint(ppo);
            if (ppr.Status != PromptStatus.OK) return;
            p2 = ppr.Value;

            ppo = new PromptPointOptions("\nThird point: ");
            ppr = ed.GetPoint(ppo);
            if (ppr.Status != PromptStatus.OK) return;
            p3 = ppr.Value;

            // create a CircularArc3d
           
            CircularArc3d carc = new CircularArc3d(p1, p2, p3);

            Arc arc = null;

            // now convert the CircularArc3d to an Arc
            Point3d cpt = carc.Center;
            Vector3d normal = carc.Normal;
            Vector3d refVec = carc.ReferenceVector;
            Plane plan = new Plane(cpt, normal);
            double ang = refVec.AngleOnPlane(plan);
            arc = new Arc(cpt, normal, carc.Radius, carc.StartAngle + ang, carc.EndAngle + ang);

            arc.SetDatabaseDefaults();
 
            // dispose CircularArc3d
            carc.Dispose();


            // get the current database

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                try
                {
                    // get the current space
                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                    // append arc to space
                    btr.AppendEntity(arc);
                    // add arc to transaction
                    tr.AddNewlyCreatedDBObject(arc, true);
                    tr.Commit();
                }
                catch (Autodesk.AutoCAD.Runtime.Exception ex)
                {
                    ed.WriteMessage(ex.Message + "\n" + ex.StackTrace);
                }
                finally
                {
                    //do nothing (optional)
                    Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("osmode", osm);
                }
            }

        }
Pages: 1 ... 7 8 [9] 10