
Creating Plugins for AutoCAD Using the .NET API (Part 1 - First Steps)
- From the sandbox
- Tutorial
Hello, Habr!
I decided to talk about my experience with AutoCAD. Maybe this will help someone - well, or at least it will seem interesting.
It all started quite simply: once again experiencing an acute shortage of money, I decided that it was time to start looking for them somewhere. And so, after a couple of weeks of searching on Freelansim , a developer’s vacancy was discovered to create a program that interacts with AutoCAD.
I have to say right away: I have never had a chance to communicate with AutoCAD until that day. However, the announcement contained the phrase “No work experience required,” which filled my soul with hope. I contacted the person who posted the vacancy and received a test task.
For testing, it was proposed to create a couple of objects in the drawing, as well as display the text. For several days I searched for information about the API and tried to make friends with an unusual program. In the end, the figures were drawn, the text was displayed, and the test task was sent for verification. And a few days later I suddenly found out that I was accepted! Miracles, and only.
In the following paragraphs - my impressions, bruises and bumps, thoughts and advice (possibly harmful). The development was carried out under AutoCAD 2010, the correct Visual Studio 2013 Express was used as an IDE. The development language is C #.
Everything is clear here. Download from the official Autodesk website , set, 30 days enjoy a great tool. Then find out the purchase priceand hang yourself . For developers, there is a special ADN program , according to which you can get development licenses for Autodesk products. The cost of the basic version of the subscription, as indicated on the site , is from $ 700 per year.
The last three or four versions of the libraries can be downloaded for free here after registration. You will have to look for earlier ones - say, here . Just in case, I’ll duplicate the list right here - it’s not so long:
Personally, I at one time was very interested in the issue of backward compatibility of ObjectARX. Once a customer asked: “What versions of AutoCAD can the program work with?”, And I had to spend a fair amount of time looking for an answer. In general, the answer is: “ Autodesk has been backward compatible for three years .” Which versions are compatible with each other, you can see under the spoiler above.
So far, I have not encountered the task of recompiling the program with other libraries. I think this is good: the prospect of creating a separate version of the product for other releases of AutoCAD is not at all happy.
Great IDE! Nothing more to say about her. There are tons of download links - for example, here .
You can, of course, use earlier versions. I started work on the project in MS Visual Studio 2010, but then I decided to switch to a more modern release.
I didn’t have as much programming experience - I’m used to solving simple tasks for which the .NET platform tools were enough for my eyes. And my first acquaintance with AutoCAD programming was not very simple. An unpleasant surprise was that the classes for working with AutoCAD:
As a result, I gathered information from Object ARX help files (I have them installed in a folder named C: \ ObjectARX 2010 \ docs ), as well as from numerous forums, blogs and AutoCAD developer communities. Frankly speaking, the latter helped more than the first. :)
At the end of this article is a list of resources where you can ask questions and, if you're lucky, get answers to them.
The first steps are quite clearly described here . English speakers can also try coming here . True, in the materials on the last link the emphasis is on Visual Basic, plus you will need to install the “AutoCAD .NET Wizard” - a project template for creating plugins for AutoCAD. Knowledgeable people say that this template greatly simplifies life; I never used it, so modestly keep silent.
I will briefly duplicate the main stages:
If the plugin is intended for the old version of AutoCAD, then it is advisable to immediately set the .NET version in the project properties that we will use. For example, AutoCAD 2010 cannot load plugins created using the .NET Framework 4, so I specify the .NET Framework 3.5 as the version used.
When downgrading the version of the .NET Framework used in a project, error messages may appear. In my case, Visual Studio swears at the lack of the “Microsoft.CSharp” assembly - it just needs to be excluded from the References.
At this point, it is worthwhile to dwell a little more. AutoCAD .NET API includes a fairly large number of classes that are spaced in different namespaces. In turn, these namespaces are spaced across several containers (in other words, DLL files).
These dll files are located in a folder named inc- <architecture_name> . So, in my case, I add links to libraries from the C: \ ObjectARX 2010 \ inc-win32 folder .
My first acquaintance with the API was in feverish attempts to compile at least one of the examples generously scattered across the Web. And whatis typical of λλ , they stubbornly did not want to compile, swearing at unknown namespaces and classes. In an attempt to build my first project, with grief, I included almost all the DLL files that came with ObjectARX. The bad way is that you don’t have to.
An important point : be sure to prohibit copying AutoCAD .NET API libraries to the assembly directory when building a project! To do this, find the parameter in the properties of each added link
Everything is very simple. First, we specify the necessary namespaces. We will need two.
The first namespace (
The second namespace (
Thus, in total, you need to add three links:

UPD. 04/09/2018. An important addition from lasteran : In new versions (presumably starting from AutoCAD 2013), the class
Then we declare the class
Finally, we declare a function
To "turn" the created method into an AutoCAD command, the attribute is used
After assembling this project, we will get a ready-to-use plugin.
You need to start AutoCAD and execute the "NETLOAD" command:

Then, in the window that opens, specify the path to the plugin file:

After that, the plugin will be loaded into AutoCAD. We should see the first message:

If a critical error occurred while loading the plugin, it will be displayed in the AutoCAD console:

Messages are usually understandable - they will help to figure out if the case is not very clinical. :)
Now that the plugin is loaded, we can execute our test command:

... and see the result:

It works. Now you can close AutoCAD.
The procedure for starting the debugging plugin is very well outlined in this Tepliuk post .
Well - for the first time is enough. It remains to provide the promised links. In post Namolem and post n00buK already given a large amount of sources; I’ll duplicate some of them here.
On this my article is finished. If it is recognized as suitable - I will write a few more simple notes about what I came across, somehow:
Thanks for attention!
I decided to talk about my experience with AutoCAD. Maybe this will help someone - well, or at least it will seem interesting.
public static string disclaimer = "Автор не является профессиональным разработчиком и не обладает глубокими знаниями AutoCAD. Этот пост – просто небольшой рассказ о начальном этапе создания плагина.";
Background
It all started quite simply: once again experiencing an acute shortage of money, I decided that it was time to start looking for them somewhere. And so, after a couple of weeks of searching on Freelansim , a developer’s vacancy was discovered to create a program that interacts with AutoCAD.
I have to say right away: I have never had a chance to communicate with AutoCAD until that day. However, the announcement contained the phrase “No work experience required,” which filled my soul with hope. I contacted the person who posted the vacancy and received a test task.
For testing, it was proposed to create a couple of objects in the drawing, as well as display the text. For several days I searched for information about the API and tried to make friends with an unusual program. In the end, the figures were drawn, the text was displayed, and the test task was sent for verification. And a few days later I suddenly found out that I was accepted! Miracles, and only.
In the following paragraphs - my impressions, bruises and bumps, thoughts and advice (possibly harmful). The development was carried out under AutoCAD 2010, the correct Visual Studio 2013 Express was used as an IDE. The development language is C #.
1. Preparation of necessary tools
1.1. Actually AutoCAD
Everything is clear here. Download from the official Autodesk website , set, 30 days enjoy a great tool. Then find out the purchase price
1.2. ObjectARX SDK - a set of libraries necessary for working with AutoCAD
The last three or four versions of the libraries can be downloaded for free here after registration. You will have to look for earlier ones - say, here . Just in case, I’ll duplicate the list right here - it’s not so long:
download links for the ObjectARX SDK for versions of AutoCAD 2000 - 2011
Personally, I at one time was very interested in the issue of backward compatibility of ObjectARX. Once a customer asked: “What versions of AutoCAD can the program work with?”, And I had to spend a fair amount of time looking for an answer. In general, the answer is: “ Autodesk has been backward compatible for three years .” Which versions are compatible with each other, you can see under the spoiler above.
So far, I have not encountered the task of recompiling the program with other libraries. I think this is good: the prospect of creating a separate version of the product for other releases of AutoCAD is not at all happy.
1.3. MS Visual Studio 2013 Express
Great IDE! Nothing more to say about her. There are tons of download links - for example, here .
You can, of course, use earlier versions. I started work on the project in MS Visual Studio 2010, but then I decided to switch to a more modern release.
1.4. Search engine, perseverance, common sense
I didn’t have as much programming experience - I’m used to solving simple tasks for which the .NET platform tools were enough for my eyes. And my first acquaintance with AutoCAD programming was not very simple. An unpleasant surprise was that the classes for working with AutoCAD:
- There are no familiar tooltips about class, property, or method assignment.
- no detailed help.
As a result, I gathered information from Object ARX help files (I have them installed in a folder named C: \ ObjectARX 2010 \ docs ), as well as from numerous forums, blogs and AutoCAD developer communities. Frankly speaking, the latter helped more than the first. :)
At the end of this article is a list of resources where you can ask questions and, if you're lucky, get answers to them.
2. Creating a library project
The first steps are quite clearly described here . English speakers can also try coming here . True, in the materials on the last link the emphasis is on Visual Basic, plus you will need to install the “AutoCAD .NET Wizard” - a project template for creating plugins for AutoCAD. Knowledgeable people say that this template greatly simplifies life; I never used it, so modestly keep silent.
I will briefly duplicate the main stages:
2.1. Create a Class Library project
If the plugin is intended for the old version of AutoCAD, then it is advisable to immediately set the .NET version in the project properties that we will use. For example, AutoCAD 2010 cannot load plugins created using the .NET Framework 4, so I specify the .NET Framework 3.5 as the version used.
When downgrading the version of the .NET Framework used in a project, error messages may appear. In my case, Visual Studio swears at the lack of the “Microsoft.CSharp” assembly - it just needs to be excluded from the References.
2.2. Add links to the necessary AutoCAD .NET API libraries
At this point, it is worthwhile to dwell a little more. AutoCAD .NET API includes a fairly large number of classes that are spaced in different namespaces. In turn, these namespaces are spaced across several containers (in other words, DLL files).
These dll files are located in a folder named inc- <architecture_name> . So, in my case, I add links to libraries from the C: \ ObjectARX 2010 \ inc-win32 folder .
NB:
I have a 32-bit OS installed at home, a 64-bit one at the customer. So far, serious compatibility issues have not arisen. But one day I nevertheless ran into the fact that my function returned
Int32
, and that of the customer - Int64
. The linker was VERY upset. You need to keep this feature in mind.My first acquaintance with the API was in feverish attempts to compile at least one of the examples generously scattered across the Web. And what
So how should it be?
Well, this is not a question for me. I can only say that at the beginning of the examples there is usually an enumeration of the used namespaces - say, like this:
What begins with the word “Autodesk” is the namespacedroid we are looking for. Now it remains to find the containers that contain them. I could not find an exhaustive list of comparisons, so everything was checked by the method of scientific poking. If there is a more correct way, it would be interesting to know it ...
In the meantime, here is a list of DLL files that I use in the project and the namespaces contained in them:
Container “AcMgd” (file “AcMgd.dll”) :
Container "AcDbMgd" (file "AcDbMgd.dll") :
Container "AdWindows" (file "AdWindows.dll") :
“AcCui” container (AcCui.dll file) :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using Autodesk.AutoCAD.Runtime;
using Autodesk.Windows;
What begins with the word “Autodesk” is the namespace
In the meantime, here is a list of DLL files that I use in the project and the namespaces contained in them:
Container “AcMgd” (file “AcMgd.dll”) :
- Autodesk.AutoCAD.ApplicationServices
- Autodesk.AutoCAD.EditorInput
- Autodesk.AutoCAD.GraphicsSystem
- Autodesk.AutoCAD.Internal
- Autodesk.AutoCAD.Internal.Calculator
- Autodesk.AutoCAD.Internal.DatabaseServices
- Autodesk.AutoCAD.Internal.Forms
- Autodesk.AutoCAD.Internal.PreviousInput
- Autodesk.AutoCAD.Internal.PropertyInspector
- Autodesk.AutoCAD.Internal.Reactors
- Autodesk.AutoCAD.Internal.Windows
- Autodesk.AutoCAD.PlottingServices
- Autodesk.AutoCAD.Publishing
- Autodesk.AutoCAD.Runtime
- Autodesk.AutoCAD.Windows
- Autodesk.AutoCAD.Windows.Data
- Autodesk.AutoCAD.Windows.ToolPalette
Container "AcDbMgd" (file "AcDbMgd.dll") :
- Autodesk.AutoCAD.Colors
- Autodesk.AutoCAD.ComponentModel
- Autodesk.AutoCAD.DatabaseServices
- Autodesk.AutoCAD.DatabaseServices.Filters
- Autodesk.AutoCAD.Geometry
- Autodesk.AutoCAD.GraphicsInterface
- Autodesk.AutoCAD.GraphicsSystem
- Autodesk.AutoCAD.LayerManager
- Autodesk.AutoCAD.Runtime
Container "AdWindows" (file "AdWindows.dll") :
- Autodesk.Internal.InfoCenter
- Autodesk.Internal.Windows
- Autodesk.Internal.Windows.ToolBars
- Autodesk.Private.InfoCenter
- Autodesk.Private.SubAwareService
- Autodesk.Private.WebSearchService
- Autodesk.Private.Windows
- Autodesk.Private.Windows.ToolBars
- Autodesk.Private.WsCommCntrLib
- Autodesk.Windows
- Autodesk.Windows.Common.Utilities
- Autodesk.Windows.ToolBars
“AcCui” container (AcCui.dll file) :
- Autodesk.AutoCAD.Customization
NB:
the names of many AutoCAD .NET API classes coincide with the names of standard .NET classes, which is not very convenient. For example, if you refer to a class in code
Now, anywhere in this file, you can
It makes sense to crank up such an operation with the most commonly used classes. Be sure to do this, the code will be more compact and understandable.The cynicism of this advice is that by the time you finally understand which classes you use most often, something will be very lazy to change.
Application
, then Visual Studio swears at the ambiguity of this definition: a class with that name is in both the namespace System.Windows
and the namespace Autodesk.AutoCAD.ApplicationServices
. In order not to write the full name each time, you can add a line to the beginning of the fileusing acadApp = Autodesk.AutoCAD.ApplicationServices.Application;
Now, anywhere in this file, you can
Autodesk.AutoCAD.ApplicationServices.Application
write instead acadApp
. It makes sense to crank up such an operation with the most commonly used classes. Be sure to do this, the code will be more compact and understandable.
An important point : be sure to prohibit copying AutoCAD .NET API libraries to the assembly directory when building a project! To do this, find the parameter in the properties of each added link
CopyLocal
and set it to False
.2.3. Write plugin code
using System.Windows.Forms;
using Autodesk.AutoCAD.Runtime;
namespace MyAutoCADDll
{
public class Commands : IExtensionApplication
{
// функция инициализации (выполняется при загрузке плагина)
public void Initialize()
{
MessageBox.Show("Hello!");
}
// функция, выполняемая при выгрузке плагина
public void Terminate()
{
MessageBox.Show("Goodbye!");
}
// эта функция будет вызываться при выполнении в AutoCAD команды «TestCommand»
[CommandMethod("TestCommand")]
public void MyCommand()
{
MessageBox.Show("Habr!");
}
}
}
Everything is very simple. First, we specify the necessary namespaces. We will need two.
The first namespace (
System.Windows.Forms
) stores the description of the class MessageBox
with which we will display messages. To make it available, you must add a link to the .NET assembly of the same name. The second namespace (
Autodesk.AutoCAD.Runtime
) defines an interface IExtensionApplication
and an attribute CommandMethod
. Moreover, the description IExtensionApplication
is in the AcDBMgd.dll file , and the description CommandMethod
is in the AcMgd.dll file , so you will have to add links to both of these libraries. Thus, in total, you need to add three links:

UPD. 04/09/2018. An important addition from lasteran : In new versions (presumably starting from AutoCAD 2013), the class
CommandMethod
is not in AcDBMgd.dll , but in AcCoreMgd.dll , so you will have to add a link to this library as well. Keep this in mind when working with the new version! Then we declare the class
Commands
. He will be the “starting point” of the plugin. Our class is inherited from the interface IExtensionApplication
, so methods Initialize
and can be implemented in it Terminate
. The first of them is automatically executed when the plugin is loaded, the second - when unloaded.NB:
Finally, we declare a function
MyCommand
that will implement the AutoCAD command. She must not accept anything at the entrance and return nothing at the exit (I don’t know where this belief came from, but it is). Inside this function, you can do whatever you want (within reason, of course), and it is possible to work with both the AutoCAD .NET API and standard .NET classes. For example, you can create a regular Windows form with input fields, display it on the screen with ShowModal()
, and then, based on the data entered by the user, make changes to the drawing opened in AutoCAD. To "turn" the created method into an AutoCAD command, the attribute is used
CommandMethod
. In brackets after it, the name of the created command is indicated, which can be used directly in the AutoCAD environment. After assembling this project, we will get a ready-to-use plugin.
2.4. Download created plugin
You need to start AutoCAD and execute the "NETLOAD" command:

Then, in the window that opens, specify the path to the plugin file:

After that, the plugin will be loaded into AutoCAD. We should see the first message:

If a critical error occurred while loading the plugin, it will be displayed in the AutoCAD console:

Messages are usually understandable - they will help to figure out if the case is not very clinical. :)
NB:
if the plugin could not load due to an error, then before testing the next (fixed) version, you need to close and restart AutoCAD. Otherwise, he may refuse to download the plugin, even if there are no errors in the code.
Now that the plugin is loaded, we can execute our test command:

... and see the result:

It works. Now you can close AutoCAD.
But what about ...
Yes - an attentive reader, of course, will notice that for some reason when AutoCAD closes, we won’t see the “Goodbye” message. As mentioned above, far from everything can be done inside the “Terminate” function. But with its help it’s quite possible, for example, to create a file when AutoCAD is closed.
2.5. Debug plugin (if necessary)
The procedure for starting the debugging plugin is very well outlined in this Tepliuk post .
The final
Well - for the first time is enough. It remains to provide the promised links. In post Namolem and post n00buK already given a large amount of sources; I’ll duplicate some of them here.
- http://adn-cis.org/forum/ (rus) - Autodesk CIS Community Forum. One of the best Russian-language resources among all that I met in 2013-2014. I myself come there for advice, when it’s completely hot, and there hasn’t been a chance yet to help me. Although, of course, I try not to abuse too much.
- http://forums.autodesk.com/t5/russkoe-soobshchestvo/bd-p/392 (rus) - official Autodesk forums - section of the Russian community. You can ask questions.
- http://forums.autodesk.com/t5/net/bd-p/152 (англ.) – официальные форумы Autodesk – раздел, посвященный .NET API. Тоже можно задать вопрос – правда, его могут и проигнорировать.
- http://through-the-interface.typepad.com (англ.) – блог, который ведет Kean Walmsley, один из ведущих экспертов в разработке под AutoCAD. Ценнейший ресурс. Можно попробовать что-нибудь спросить у самого хозяина блога – и даже получить ответ, если тот будет в настроении. Впрочем, неинтересные (и простые) вопросы Kean часто игнорирует – или же предлагает вопрошающему поискать решение на официальном форуме
(см. рис. 1). - http://adndevblog.typepad.com (англ.) – коллективный блог разработчиков из ADN. Порой бывает полезен.
- http://www.theswamp.org/index.php (English) is another forum with many examples and solutions.
On this my article is finished. If it is recognized as suitable - I will write a few more simple notes about what I came across, somehow:
- work with tape (Ribbon) ;
- work with layers;
- work with dynamic blocks;
- user input implementation;
- interaction of the plugin with an external application.
Thanks for attention!