BIM World
A Professional BIM Learning Platform


Basic Examples for Getting Started with CAD Custom Development

Here are some simple examples of CAD secondary development:

  1. Hello World
  2. Draw a circle
  3. Draw a straight line
  4. Get all object IDs on a specific layer
  5. Get the IDs of all objects on the current layer
  6. Retrieve all current layer names
  7. Add a new layer
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Windows;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Colors;
using Autodesk.AutoCAD.EditorInput;
using System.Collections;
using AcadApp = Autodesk.AutoCAD.ApplicationServices.Application;
using System.Reflection;

namespace CADDevelopment
{
    public class Class1
    {
        /// <summary>
        /// Prints "Hello World" in the AutoCAD editor
        /// </summary>
        [CommandMethod("HelloWorld")]
        public void HelloWorld()
        {
            Editor ed = AcadApp.DocumentManager.MdiActiveDocument.Editor;
            ed.WriteMessage("Hello World222");
        }

        /// <summary>
        /// Draws a circle in the model space
        /// </summary>
        [CommandMethod("test")]
        public void CreateCircle()
        {
            // Declare the circle object
            Circle circle;

            // To add a circle, we need to access model space through BlockTable and BlockTableRecord
            BlockTableRecord btr;
            BlockTable bt;

            // Use a Transaction to manage database operations
            Transaction trans;

            // Start a transaction
            trans = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction();

            // Create a circle at point (10,10,0) with radius 2 and normal vector along Z axis
            circle = new Circle(new Point3d(10, 10, 0), Vector3d.ZAxis, 2);

            // Get the block table for read access
            bt = (BlockTable)trans.GetObject(HostApplicationServices.WorkingDatabase.BlockTableId, OpenMode.ForRead);

            // Open the current space for write access to add the circle
            btr = (BlockTableRecord)trans.GetObject(HostApplicationServices.WorkingDatabase.CurrentSpaceId, OpenMode.ForWrite);

            // Append the circle entity and notify the transaction
            btr.AppendEntity(circle);
            trans.AddNewlyCreatedDBObject(circle, true);

            // Commit and dispose the transaction
            trans.Commit();
            trans.Dispose();
        }

        /// <summary>
        /// Select a point and display its coordinates; then select two points and display their distance
        /// </summary>
        [CommandMethod("selectPoint")]
        public void SelectPoint()
        {
            Editor ed = AcadApp.DocumentManager.MdiActiveDocument.Editor;

            // Prompt user to select a point
            PromptPointOptions prPointOptions = new PromptPointOptions("Select a point");
            PromptPointResult prPointRes = ed.GetPoint(prPointOptions);

            if (prPointRes.Status != PromptStatus.OK)
            {
                ed.WriteMessage("Error");
                return;
            }
            ed.WriteMessage("You selected point: " + prPointRes.Value.ToString());

            // Prompt user to select two points to find distance
            PromptDistanceOptions prDistOptions = new PromptDistanceOptions("Find distance, select first point:");
            PromptDoubleResult prDistRes = ed.GetDistance(prDistOptions);

            if (prDistRes.Status != PromptStatus.OK)
            {
                ed.WriteMessage("Error");
                return;
            }
            ed.WriteMessage("The distance is: " + prDistRes.Value.ToString());
        }

        [CommandMethod("CreateDivision")]
        public void CreateDivision()
        {
            Database db = HostApplicationServices.WorkingDatabase;
            Transaction trans = db.TransactionManager.StartTransaction();
            try
            {
                // Get the Named Objects Dictionary for write access
                DBDictionary NOD = (DBDictionary)trans.GetObject(db.NamedObjectsDictionaryId, OpenMode.ForWrite);

                DBDictionary acmeDict;

                try
                {
                    // Try to get the "ACME_DIVISION" dictionary
                    acmeDict = (DBDictionary)trans.GetObject(NOD.GetAt("ACME_DIVISION"), OpenMode.ForRead);
                }
                catch
                {
                    // If not found, create it and add to NOD
                    acmeDict = new DBDictionary();
                    NOD.SetAt("ACME_DIVISION", acmeDict);
                    trans.AddNewlyCreatedDBObject(acmeDict, true);
                }

                trans.Commit();
            }
            finally
            {
                trans.Dispose();
            }
        }

        /// <summary>
        /// Draws a straight line between two points
        /// </summary>
        [CommandMethod("FirstLine")]
        public static void FirstLine()
        {
            Database db = HostApplicationServices.WorkingDatabase;

            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                BlockTable acBlkTbl = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;

                // Open the model space block table record for write
                BlockTableRecord acBlkTblRec = trans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

                Point3d startPoint = new Point3d(0, 100, 0);
                Point3d endPoint = new Point3d(100, 100, 0);

                // Create a new line object
                Line line = new Line(startPoint, endPoint);

                // Add the line to the block table record and to the transaction
                acBlkTblRec.AppendEntity(line);
                trans.AddNewlyCreatedDBObject(line, true);

                // Commit the transaction to save changes
                trans.Commit();
            }
        }

        #region Get all object IDs on a specific layer
        /// <summary>
        /// Retrieves all object IDs on the specified layer
        /// </summary>
        /// <param name="name">Layer name</param>
        /// <returns>Collection of ObjectIds</returns>
        public ObjectIdCollection GetObjectIdsAtLayer(string name)
        {
            ObjectIdCollection ids = new ObjectIdCollection();
            PromptSelectionResult ProSset = null;

            TypedValue[] filList = new TypedValue[1] { new TypedValue((int)DxfCode.LayerName, name) };
            SelectionFilter sfilter = new SelectionFilter(filList);

            Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            ProSset = ed.SelectAll(sfilter);

            if (ProSset.Status == PromptStatus.OK)
            {
                SelectionSet sst = ProSset.Value;
                ObjectId[] oids = sst.GetObjectIds();

                foreach (ObjectId oid in oids)
                {
                    ids.Add(oid);
                }
            }
            return ids;
        }
        #endregion

        /// <summary>
        /// Retrieve IDs of all geometry on the current layer
        /// </summary>
        [CommandMethod("GetAllId")]
        public void GetAllId()
        {
            Editor ed = AcadApp.DocumentManager.MdiActiveDocument.Editor;

            ObjectIdCollection ids = GetObjectIdsAtLayer("0");
            string str = "";
            Database db = HostApplicationServices.WorkingDatabase;

            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                BlockTable acBlkTbl = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                BlockTableRecord acBlkTblRec = trans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

                foreach (ObjectId item in ids)
                {
                    Entity entity = (Entity)item.GetObject(OpenMode.ForRead, false, false);
                    if (entity.GetRXClass().Name == "AcDbText")
                    {
                        DBText dbtext = entity as DBText;
                        str += dbtext.TextString + 'n';
                    }
                }

                ed.WriteMessage(str);
                trans.Commit();
            }
        }

        #region Retrieve all current layer names
        /// <summary>
        /// Retrieves all layer names currently in the drawing
        /// </summary>
        /// <returns>A list of layer names</returns>
        [CommandMethod("GetAllLayer")]
        public ArrayList GetLayerName()
        {
            ArrayList layers = new ArrayList();

            using (Database db = HostApplicationServices.WorkingDatabase)
            {
                using (Transaction trans = db.TransactionManager.StartTransaction())
                {
                    using (LayerTable lt = (LayerTable)trans.GetObject(db.LayerTableId, OpenMode.ForRead))
                    {
                        foreach (ObjectId id in lt)
                        {
                            LayerTableRecord ltr = (LayerTableRecord)trans.GetObject(id, OpenMode.ForRead);
                            layers.Add(ltr.Name);
                        }
                    }
                    trans.Commit();
                }
            }
            return layers;
        }
        #endregion

        #region Add a new layer
        /// <summary>
        /// Adds a new layer or modifies an existing one
        /// </summary>
        /// <param name="layName">Name of the layer</param>
        /// <param name="layColor">Color index of the layer</param>
        private ObjectId AddLayer(string layName, short layColor)
        {
            ObjectId oidReturn = new ObjectId();

            using (Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument())
            {
                Database database = HostApplicationServices.WorkingDatabase;
                Editor editor = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;

                using (Transaction transaction = database.TransactionManager.StartTransaction())
                {
                    try
                    {
                        ObjectId id;
                        LayerTable table = transaction.GetObject(database.LayerTableId, OpenMode.ForWrite) as LayerTable;
                        LayerTableRecord record = new LayerTableRecord();

                        if (table.Has(layName))
                        {
                            id = table.Id;
                            record = transaction.GetObject(id, OpenMode.ForWrite) as LayerTableRecord;
                            record.IsOff = false;
                            record.IsLocked = false;

                            if (id != database.Clayer)
                            {
                                record.IsFrozen = false;
                            }
                        }
                        else
                        {
                            record.Name = layName;
                            id = table.Add(record);
                            transaction.AddNewlyCreatedDBObject(record, true);
                        }

                        record.Color = Autodesk.AutoCAD.Colors.Color.FromColorIndex(ColorMethod.ByColor, layColor);
                        database.Clayer = id;
                        oidReturn = id;

                        transaction.Commit();
                    }
                    catch (Autodesk.AutoCAD.Runtime.Exception exception)
                    {
                        editor.WriteMessage("Error in AddLayer(): " + exception.Message);
                    }
                }
            }
            return oidReturn;
        }
        #endregion
    }
}
xuebim
Follow the latest BIM developments in the architecture industry, explore innovative building technologies, and discover cutting-edge industry insights.
← Scan with WeChat
Like(0) 打赏
BIM WORLD » Basic Examples for Getting Started with CAD Custom Development

Comment Get first!

Must log in before commenting!

 

BIM World, A Professional BIM Learning Platform

Stay updated on the latest architecture trends and share new building technologies.

Contact UsAbout Us

觉得文章有用就打赏一下小编吧

非常感谢你的打赏,我们将继续提供更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫

微信扫一扫

Account Login

By signing in, you agree toUser Agreement

Sign Up