Bird
Raised Fist0
SolidworksHow-ToBeginner · 4 min read

How to Use AutoCAD API: Syntax, Example, and Tips

To use the AutoCAD API, you typically write code in C# or VB.NET that interacts with AutoCAD objects via the Autodesk.AutoCAD.ApplicationServices and Autodesk.AutoCAD.DatabaseServices namespaces. You start by creating a command method, accessing the current document and database, then manipulating drawing elements programmatically.
📐

Syntax

The basic syntax to create a command in AutoCAD API involves defining a public method with the CommandMethod attribute. Inside this method, you access the current document and database, then use transactions to modify drawing objects safely.

  • CommandMethod: Marks the method as an AutoCAD command.
  • Document: Represents the active drawing.
  • Database: Holds the drawing data.
  • Transaction: Ensures safe changes to the drawing.
csharp
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;

public class Commands
{
    [CommandMethod("MyCommand")]
    public void MyCommand()
    {
        Document doc = Application.DocumentManager.MdiActiveDocument;
        Database db = doc.Database;
        Editor ed = doc.Editor;

        using (Transaction tr = db.TransactionManager.StartTransaction())
        {
            // Access and modify drawing objects here

            tr.Commit();
        }
    }
}
💻

Example

This example shows how to create a simple line in the current drawing using the AutoCAD API. It demonstrates opening the block table, starting a transaction, creating a line object, adding it to the model space, and committing the transaction.

csharp
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.EditorInput;

public class Commands
{
    [CommandMethod("DrawLine")]
    public void DrawLine()
    {
        Document doc = Application.DocumentManager.MdiActiveDocument;
        Database db = doc.Database;
        Editor ed = doc.Editor;

        using (Transaction tr = db.TransactionManager.StartTransaction())
        {
            BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
            BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);

            Line line = new Line(new Point3d(0, 0, 0), new Point3d(100, 100, 0));
            btr.AppendEntity(line);
            tr.AddNewlyCreatedDBObject(line, true);

            tr.Commit();
        }

        ed.WriteMessage("\nLine created from (0,0,0) to (100,100,0).");
    }
}
Output
Line created from (0,0,0) to (100,100,0).
⚠️

Common Pitfalls

Common mistakes when using the AutoCAD API include:

  • Not starting or committing a transaction, which prevents changes from saving.
  • Accessing objects without proper open mode (read vs write), causing exceptions.
  • Forgetting to add new objects to the block table record and transaction.
  • Running commands outside AutoCAD environment or without proper references.

Always ensure you use using blocks for transactions and open objects with correct permissions.

csharp
/* Wrong way: Missing transaction commit and adding entity */
using (Transaction tr = db.TransactionManager.StartTransaction())
{
    BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);

    Line line = new Line(new Point3d(0, 0, 0), new Point3d(50, 50, 0));
    // Missing btr.AppendEntity(line);
    // Missing tr.AddNewlyCreatedDBObject(line, true);

    // Missing tr.Commit();
}

/* Right way: */
using (Transaction tr = db.TransactionManager.StartTransaction())
{
    BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);

    Line line = new Line(new Point3d(0, 0, 0), new Point3d(50, 50, 0));
    btr.AppendEntity(line);
    tr.AddNewlyCreatedDBObject(line, true);

    tr.Commit();
}
📊

Quick Reference

Here is a quick reference for common AutoCAD API classes and methods:

Class/MethodPurpose
Application.DocumentManager.MdiActiveDocumentAccess current drawing document
DatabaseRepresents the drawing database
TransactionManager.StartTransaction()Start a transaction to edit drawing safely
BlockTableAccess block definitions like ModelSpace
BlockTableRecordContainer for drawing entities
BlockTableRecord.AppendEntity()Add new entity to drawing
Transaction.Commit()Save changes made in transaction
✅

Key Takeaways

Always use transactions to safely modify AutoCAD drawings.
Mark your methods with CommandMethod attribute to create AutoCAD commands.
Open objects with correct read/write permissions to avoid errors.
Add new entities to the block table record and transaction before committing.
Test your commands inside AutoCAD to see immediate results.