Click here to Skip to main content
15,881,455 members
Articles / Programming Languages / C#

AutoCAD 2D Drawing using C# with AutoCAD COM API

Rate me:
Please Sign up or sign in to vote.
2.89/5 (12 votes)
29 Feb 2016CPOL7 min read 82.2K   4.5K   15   10
Automating the drawing process in AutoCAD using programming to improve the productivity of the design engineers.

Introduction

This article is about 2D Drawing Automation in Autocad using C#. It gives step-by-step instructions to start with Autocad automation for Beginners.

Background

Prerequisites

1. C# Programming basics

2. AutoCAD drawing basics.

Tools Required

1. Visual Studio Express

2. Autocad

What is Autocad Automation?

Image 1

Autocad is a software for creating 2D and 3D drawings. Autocad Automation means that, creating drawings automatically in Autocad by using programming. We can draw very big drawings with in a seconds by programming. Autocad provides interoperability with other applications, by using Autocad object model, we can create drawings in Autocad. The above diagram shows the idea behind the Autocad Automation. A custom C# application creates drawing in the Autocad by calling the commands available in the Autocad.

In this example, We will create a simple drawing in Autocad by a C# Application by using Autocad COM API. Before proceeding further, we need to know the following things,

1. How Autocad Automation is working?

2. What is Autocad object model?

3. How to Connect our application with active instance of Autocad?

How Autocad Automation is working?

Have a look at the following diagram, which shows the actual working mechanism of Autocad Automation.

Image 2

Actually what happes? Autocad orgranizes everything as object (OOP), circle, line, rectangle, square, ellipse and all are considered as objects in Autocad. Each object in Autocad has its own properties and functions. Autocad exposing these objects to the world through Autocad COM API, by using this API in our programming, we can play with the objects of Autocad. So, manipulating the Autocad objects via Autocad COM API is the basic idea behind the Autocad Automation.

Consider the example from the above diagram, The collection of Autocad objects and its organization together known as Autocad object model. This model contains the details about all Autocad object's properties and functions. These objects are available in the Autocad COM API. This object model is like a pool of Autocad objects, we can use those objects to create drawing in Autocad. The diagram shows some of the properties and functions of the Circle object present in the Autocad COM API, By calling the AddCircle method from C# application, the circle will be created in Autocad. By setting the Radius and CenterPoint properties we can manipulate the created circle.

Note: AddCircle is not a method of Autocad Circle object, it is a member of Autocad ModelSpace object. I put the AddCircle method here just for understanding.

What is Autocad object Model?

Now we know the importance of Autocad object model, Autocad object model is a collection of Autocad objects like Line, Circle, Polyline, Dimension, etc., It defines properties, methods, and events of Autocad objects. It also defines the organization and structure of Autocad objects.

The following diagram represents the hierarchy of the Autocad object model.

Image 3

Ref img 1: Autodesk Object Model (ActiveX) by Autodesk Knowledge Network is licensed under (CC BY-NC-SA 3.0)

From the above diagram, we need to know the following important things,

Application (Global) - It represents Autocad Application. It has a property ActiveDocument which represents the current working document opened in Autocad.

Documents - Collection of documents opened in Autocad including ActiveDocument.

Document - Single Autocad document.

Modelspace - Workspace or Drawing Canvas in Autocad.

Look at the following diagram, it just the visualization of the above things.

Image 4

From this diagram we can understand the following,

Image 5

The Autocad application contains, collection of documents opened in the application, and this documents collection has the ActiveDocument (Current working document in Autocad). Each Autocad document has ModelSpace (modelling space or work area or drawing canvas). If we need to create a circle in the modelspace of the active document, we have to traverse from Autocad -> Documents -> Active Document -> Modelspace, and call the corresponding function, here function for creating a circle in modelspace is, AddCircle. Like this, we can create different shapes and drawings by calling appropriate functions.

Okay, We got an idea about the working mechanism of Autocad Automation applications. Now lets see about the connection between our application and Autocad. A Connection is required between our application and Autocad. Here the connection refers the object reference of the running Autocad application. By using this object reference we can traverse through the Autocad object tree and can do manipulations with it.

How to Connect our application with active instance of Autocad?

How we can connect our c# application with Autocad?, Before creating drawings by using c# application, we need to establish a connection between our application and active instance of Autocad. This is done by COM interoperability. We have to add COM interop assemblies of Autocad into our project as a reference before creating the connection. So where Autocad COM interop assemblies are located? It always located in the following folder of the windows os.

C:\Program Files\Common Files\Autodesk Shared - this folder contains the Autocad COM assemblies.

1. acax19enu.tlb

2. axdb19enu.tlb

These files are the COM interop assemblies of Autocad, Just add these two files into our project. Here 19 is the version number of Autocad. It may differ for different Autocad versions.

Lets take a look at the following code,

C#
// Getting active AutoCAD instance by Marshalling by passing Programmatic ID as a string, AutoCAD.Application is the Programmatic ID for AutoCAD.
AcadApplication AcadApp = (AcadApplication)Marshal.GetActiveObject("AutoCAD.Application.19");
// Now AcadApp has the reference to the running AutoCAD instance, AcadApp object acts as a port for accessing active instance of AutoCAD.

The above code, gets the object reference for the running instance of Autocad. From the above code,

AcadApplication - refers the Autocad Application class - it represents the Autocad Application.

GetActiveObject - Gets the running instance of the specified application.

Marshal - class in System.Runtime.InteropServices namespace, it provides the functionalities related to Interoperability.

"AutoCAD.Application.19" - Application program ID for Autocad in the operating system, 19 represents the version of Autocad.

By using the above code, we will get the reference of active Autocad instance. After getting the connection, we can create the drawings by invoking the function members of ModelSpace object. Okay, now lets take a sample drawing and see the steps to create this drawing in Autocad by programming.

Sample Drawing

Consider the follwoing drawing as an example, lets see the steps to create this drawing using C#.

Sample Drawing without Dimension

Sample Drawing without Dimension

Sample Drawing with Dimension

Sample Drawing with Dimension

 

 

 

 

 

Step 1:

Create a Windows Forms (C#) project in Visual Studio. Name the project like AutoCADApp or whatever name you want.

Step 2:

Add reference to Autocad COM Dlls,

1. Autocad Type Library (acax19enu.tlb). (Here 19 is the version, it varies depending on Autocad version)

2. Autocad / ObjectDBX Common Type Library (axdb19enu.tlb). (Here 19 is the version, it varies depending on Autocad version)

Step 3:

Drag control to Main form like the below image,

Main Form Design

And create events for buttons.

Step 4: Creating Circle

Before creating the circle, lets see about AcadCircle in the Autocad object model,

AcadCircle
It represents the circle in the autocad. It has the following properties,

  • Area              - Gets the Area of the circle created.
  • Center Point  - Gets or Sets 3 Dimensional Center Point of the circle.
  • Diameter       -  Diamter of the circle.
  • Radius           - Radius of the circle.

AddCircle Function

    Syntax: AddCircle ( CenterPoint, Radius )

    -- CenterPoint - 3 Dimensional double array

    -- Radius - double value represents the radius

By using the above details, lets write code for creating circle in click event of Creat Circle button,

Declaring global variables to hold the reference of cirle and AutoCAD to be created.

C#
// Creating object reference to hold the reference of the circle to be created.
private AcadCircle Circle = default(AcadCircle);

// Creating object reference to hold the reference of running AutoCAD instance.
private AcadApplication AcadApp = default(AcadApplication);

"Create Cirlce" Button Click event.

C#
private void btnCircle_Click(object sender, EventArgs e)
{
  // Getting running AutoCAD instance by Marshalling by passing Programmatic ID as a string, AutoCAD.Application is the Programmatic ID for AutoCAD.
  AcadApp = (AcadApplication)Marshal.GetActiveObject("AutoCAD.Application");

  // Now AcadApp has the reference to the running AutoCAD instance, AcadApp object acts as a port for accessing running instance of AutoCAD.

  // Syntax for creating circle in AutoCAD
  // AcadApp.ActiveDocument.ModelSpace.AddCircle(CenterOfCircle, RadiusOfCircle);
  //
  // AcadApp        - Reference to the running instance of AutoCAD.
  // ActiveDocument - Represents the current working drawing in AutoCAD.
  // ModelSpace     - Work Area in the current drawing.
  // AddCricle      - Method, which adds a circle to the modelspace of the current drawing using the CenterPoint and Radius.
  // CenterOfCircle - 3 Dimensional double array variable holds the center point of the circle in the X, Y and Z axis.
  // RadiusOfCircle - Double variable holds the radius of circle.

  // Definfing the center point for the circle, in this example, we are using origin(0,0,0) as the center of circle.
  double[] CenterOfCircle = new double[3];
  CenterOfCircle[0] = 0;
  CenterOfCircle[1] = 0;
  CenterOfCircle[2] = 0;

  // Defining radius of circle from the user input.
  double RadiusOfCircle = Convert.ToDouble(txtRadius.Text.Trim());

  // Adding Circle to the modelspace and getting reference to the circle created.
  Circle = AcadApp.ActiveDocument.ModelSpace.AddCircle(CenterOfCircle, RadiusOfCircle);
}

Step 4: Adding Caption to Circle

Before creating the caption, lets know about AcadText object.

AcadText Object
It represents string value. It has the following properties,

  • Height             - Gets or Sets height of the text created.
  • InsertionPoint  - Gets or Sets the position of AcadText in 3 Dimensional double array.
  • TextString        - Gets or Sets the content of the AcadText object.

AddText Function

    Syntax: AddText ( TextString, InsertionPoint, Height )

    -- InsertionPoint - 3 Dimensional double array representing the position of AcadText.

    -- TextString - represents the content of the AcadText.

    -- Height - represents height of the AcadText.

By using the above details, lets write code for adding caption in click event of Add Caption button,

"Add Caption" Button Click event.

C#
private void btnCaption_Click(object sender, EventArgs e)
{
  // Caption - AcadText object to hold the reference of the AcadText 
  AcadText Caption = default(AcadText);

  // Syntax for creating Text in AutoCAD
  // AcadApp.ActiveDocument.ModelSpace.AddText(TextString, InsertionPoint, Height);
  // 
  // AcadApp        - Reference to the running instance of AutoCAD.
  // ActiveDocument - Represents the current working drawing in AutoCAD.
  // ModelSpace     - Work Area in the current drawing.
  // AddText        - Method, which adds a Text to the modelspace of the current drawing using the TextString, InsertionPoint and Height.
  // TextString     - string, which represents the text to be written.
  // InsertionPoint - 3 Dimensional double array variable holds the insertion point of the circle in the X, Y and Z axis.
  // Height         - Double variable holds the height of text.

  // Text to be written just below the circle as a caption.
  string TextString = "CIRCLE";

  // Definfing the insertion point for the circle, in this example, we are going to place the text just below the circle.
  double[] InsertionPoint = new double[3];

  // Getting Centerpoint of circle we have created earlier to define the insertion point for the Caption.
  double[] CenterOfCircle = (double[])Circle.Center;

  InsertionPoint[0] = CenterOfCircle[0] - Circle.Radius / 2;
  InsertionPoint[1] = CenterOfCircle[1] - (Circle.Radius + 50);
  InsertionPoint[2] = 0;

  // Defining height of the text
  double Height = 20;
            
  // Adding text to the modelspace and getting reference to the text created.
  Caption = AcadApp.ActiveDocument.ModelSpace.AddText(TextString, InsertionPoint, Height);

  // Changing the text color
  Caption.color = ACAD_COLOR.acGreen;
}

Step 5: Adding Radial Dimension

There are many method available to add dimension to the AutoCAD objects, Incase of circle, we have to add radial dimension, for that we are going to use the following function from Autocad object model,

AddDimRadial

Syntax: AddDimRadial ( Center, ChordPoint, LeaderLength )

"Add Dimension" Button Click event.

C#
private void btnDimension_Click(object sender, EventArgs e)
{
  // Dimension - AcadDimRadial object to hold the reference of the Radial Dimension of the circle
  AcadDimRadial Dimension = default(AcadDimRadial);

  // Syntax for creating Radial Dimension
  // AcadApp.ActiveDocument.ModelSpace.AddDimRadial(Center, ChordPoint, LeaderLength);
  // 
  // AcadApp        - Reference to the running instance of AutoCAD.
  // ActiveDocument - Represents the current working drawing in AutoCAD.
  // ModelSpace     - Work Area in the current drawing.
  // AddDimRadial   - Method, which adds Radial Dimension to the circle.
  // Center         - 3 Dimensional double array variable holds the center point of the circle in the X, Y and Z axis.
  // ChordPoint     - 3 Dimensional double array variable holds the Chord point of the circle in the X, Y and Z axis.
  // LeaderLength   - Double variable holds the length of the leader line.

  // Assigning Center point of the circle to the center point of radial dimension.
  double[] Center = Circle.Center;

  // Assigning Center Point of circle to ChordPoint
  double[] ChordPoint = Circle.Center;

  // Sets Leader line length
  double LeaderLength = 150;

  Dimension = AcadApp.ActiveDocument.ModelSpace.AddDimRadial(Center, ChordPoint, LeaderLength);

  // Sets the leader line caption
  Dimension.TextOverride = "R" + Circle.Radius.ToString();

  // Sets leader line caption color
  Dimension.TextColor = ACAD_COLOR.acCyan;

  // Sets leader line color
  Dimension.DimensionLineColor = ACAD_COLOR.acMagenta;

  // Sets leader line arrow head size
  Dimension.ArrowheadSize = 15;

  // Sets height of the caption of leader line
  Dimension.TextHeight = 15;
}

Conclusion

According to the Autocad object model, each and every Autocad object has its own Properties and Methods. By using these Methods, we can automate our drawing process by programming.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) IVY Software Development Services
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionModelSpace in C# Winform Pin
Nguyễn Tấn Lộc29-Nov-17 23:01
Nguyễn Tấn Lộc29-Nov-17 23:01 
AnswerRe: ModelSpace in C# Winform Pin
VR Karthikeyan30-Nov-17 18:23
professionalVR Karthikeyan30-Nov-17 18:23 
Questionthanks for the post Pin
Member 1179891222-Mar-17 17:49
Member 1179891222-Mar-17 17:49 
AnswerRe: thanks for the post Pin
VR Karthikeyan29-Mar-17 21:28
professionalVR Karthikeyan29-Mar-17 21:28 
SuggestionMissing attribution for image Pin
Jochen Arndt25-Feb-16 1:41
professionalJochen Arndt25-Feb-16 1:41 
PraiseRe: Missing attribution for image Pin
VR Karthikeyan25-Feb-16 1:49
professionalVR Karthikeyan25-Feb-16 1:49 
GeneralPlagiarised Pin
Richard Deeming25-Feb-16 1:55
mveRichard Deeming25-Feb-16 1:55 
GeneralRe: Plagiarised Pin
VR Karthikeyan29-Mar-17 21:25
professionalVR Karthikeyan29-Mar-17 21:25 
SuggestionGood, but... Pin
Alasdair Craig18-Feb-16 4:10
Alasdair Craig18-Feb-16 4:10 
PraiseRe: Good, but... Pin
VR Karthikeyan18-Feb-16 17:29
professionalVR Karthikeyan18-Feb-16 17:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.