📜 ⬆️ ⬇️

Creating plug-ins for AutoCAD using the .NET API (part 1 - first steps)

Hello, Habr!

I decided to talk about my experience with AutoCAD. Maybe this will help someone - or at least it will seem interesting.

public static string disclaimer = "          AutoCAD.   –        ."; 

')

Prehistory


It all started quite simply: once again, having felt an acute shortage of money, I decided that it was time to start looking for them somewhere. And after a couple of weeks of searching for “ Freelance ”, a vacancy was discovered for a developer to create a program that interacts with AutoCAD.

I’ll say right away: I haven’t been able to communicate with AutoCAD until that day. However, the ad contained the phrase “Experience is not required,” which filled my soul with hope. I contacted the person who posted the job and received a test task.

For the sample, it was proposed to create a couple of objects on the drawing, as well as to 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 had been 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 the IDE. Development language - C #.

1. Preparation of the necessary tools


1.1. AutoCAD proper

It's all clear. Download from the official site of Autodesk, set, enjoy 30 days a wonderful tool. Then find out the purchase price and hang . For developers, there is a special ADN program that allows you to obtain developer licenses for Autodesk products. The cost of the basic version of the subscription, as indicated on the site , ranges from $ 700 per year.

1.2. ObjectARX SDK - a set of libraries needed to work with AutoCAD

The last three or four versions of libraries can be downloaded for free here after registration. We'll have to look for earlier ones - let's say here . Just in case, I’ll duplicate the list right here - it’s not that long:

ObjectARX SDK download links for AutoCAD 2000 - 2011
SDK version and download linkCompatibility with AutoCAD Versions
20112011, 2012
20102010, 2011, 2012
20092009
2008 x862008, 2009 x86
2008 x642008, 2009 x64
20072007, 2008, 2009 x86
20062006
20052005, 2006
20042004, 2005, 2006
20022002
2000i2000i, 2002
20002000, 2000i, 2002
R14R14

Personally, I once was very interested in the issue of ObjectARX backward compatibility. Once the customer asked: “And with which versions of AutoCAD will the program be able to work?”, And I had to spend a fair amount of time looking for an answer. Overall, the answer is: " Autodesk has been backward compatible for three years ." Which versions are compatible with each other, you can look under the spoiler above.

So far, I have not encountered the task of recompiling a 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

Gorgeous IDE! There is nothing more to say about her. There are a lot of links to download - for example, here .

You can, of course, use earlier versions. I started working on a project in MS Visual Studio 2010, but then decided to switch to a more modern release.

1.4. Search engine, perseverance, common sense

I didn’t have such a great programming experience - I was used to solving simple problems for which the means of the .NET platform itself was enough. And my first acquaintance with programming under AutoCAD was not very simple. An unpleasant surprise was that the classes for working with AutoCAD:

As a result, I got the information from the Object ARX help files (they are installed in a folder called C: \ ObjectARX 2010 \ docs ), as well as from numerous forums, blogs and AutoCAD developer communities. Frankly, the last helped more than the first. :)

At the end of this article is a list of resources where you can ask questions and, if lucky, get answers to them.

2. Creating a library project


The first steps are quite clearly described here . Those who speak English can also try to come here . True, the materials on the last link focus on Visual Basic, plus you will need to install the “AutoCAD. NET Wizard” - a project template for creating plug-ins for AutoCAD. Knowledgeable people say that this pattern greatly simplifies life; I have never used it, so I will say nothing modestly.

Briefly I will duplicate the main stages:

2.1. Create a project "Class Library" ("Class Library")

If the plug-in is intended for the old version of AutoCAD, then it is advisable to immediately set in the project properties the version of .NET that we will use. For example, AutoCAD 2010 cannot load plugins created using .NET Framework 4, so I specify .NET Framework 3.5 as the version used.

If you downgrade the version of the .NET Framework used in the project, error messages may appear. In my case, Visual Studio swears at the absence of the “Microsoft.CSharp” assembly - it just needs to be excluded from the references (References).

2.2. Add links to the necessary libraries AutoCAD .NET API

At this point it is worth a little more detail. The AutoCAD .NET API includes a fairly large number of classes that are spaced apart across different namespaces. In turn, these namespaces are separated into 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 in my home, the customer has a 64-bit one. So far there have been no serious compatibility issues. But one day I still ran into the fact that my function returned Int32 , and the customer had Int64 . The linker was VERY upset. You need to have this feature in mind.

My first acquaintance with the API consisted of feverish attempts to compile at least one of the examples generously scattered across the web. And what 's characteristic is that, they stubbornly did not want to compile, cursing into unknown namespaces and classes. In an attempt to assemble my first project, I, with grief, included in it almost all the DLL files that came with ObjectARX. Bad way - do not do this.

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 namespaces used - say, this:

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using Autodesk.AutoCAD.Runtime; using Autodesk.Windows; 

What starts with the word “Autodesk” is the namespace droid 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 typing. If there is a better way, it would be interesting to know him ...

For now, here’s a list of the DLL files that I use in the project and the namespaces they contain:

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

Container "AcCui" (AcCui.dll file) :
  • Autodesk.AutoCAD.Customization

Nb:
The names of many AutoCAD .NET API classes coincide with the names of the standard .NET classes, which is not very convenient. For example, if you refer to the Application class in code, Visual Studio curses the ambiguity of this definition: a class with this name is in both the System.Windows and the Autodesk.AutoCAD.ApplicationServices namespace. In order not to write the full name each time, you can add a line to the beginning of the file.

 using acadApp = Autodesk.AutoCAD.ApplicationServices.Application; 

Now you can write acadApp instead of Autodesk.AutoCAD.ApplicationServices.Application anywhere in this file.

It makes sense to crank up such an operation with the most frequently used classes. Do it without fail, the code will be smaller and clearer. The cynicism of this advice lies in the fact that by the time you finally understand which classes you have most often used, something will be too lazy to change.


An important point : be sure to prohibit copying the AutoCAD .NET API libraries to the build directory when building the project! To do this, find the parameter CopyLocal in the properties of each added link 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 MessageBox class, with which we will display messages. To make it available, you need to add a link to the .NET assembly of the same name.

The second namespace ( Autodesk.AutoCAD.Runtime ) defines the IExtensionApplication interface and the CommandMethod attribute. And the description of IExtensionApplication is in the AcDBMgd.dll file, and the description of CommandMethod is in the AcMgd.dll file, so you will have to add links to both of these libraries.

Thus, all you need to add three links:





UPD. 09.04.2018 An important addition from lasteran : In newer versions (presumably from AutoCAD 2013), the CommandMethod class is not contained in AcDBMgd.dll , but in AcCoreMgd.dll , so you will have to add a link to this library too. Keep this in mind if you are working with a new version!

Then we declare the Commands class. That he will be the "starting point" of the plugin. Our class inherits from the IExtensionApplication interface, so it can be implemented with the Initialize and Terminate methods. The first one is automatically executed when the plug-in is loaded, the second one is unloaded.

Nb:
AutoCAD does not provide the developer with the opportunity to unload the plugin after it has been loaded. Therefore, the actual Terminate method will be called only in one case - when you close AutoCAD itself.

You can read more about the methods Initialize and Terminate here (rus) and there (English).

Finally, we announce the MyCommand function, which will implement the AutoCAD command. She must take nothing at the entrance and return nothing at the exit (I don’t know where I got this conviction, but it exists). Inside this function, you can do whatever you want (within reason, of course), and you can work with both the AutoCAD .NET API and the standard .NET classes. For example, you can create a regular Windows form with input fields, display it on the screen using ShowModal() , and then, based on the data entered by the user, make changes to the drawing opened in AutoCAD.

To “transform” the created method into an AutoCAD command, the CommandMethod attribute is CommandMethod . After the brackets, the name of the command to be created is indicated after it, which can be used directly in the AutoCAD environment.

After assembling this project, we will have a plug-in ready for use.

2.4. Download the created plugin

You need to start AutoCAD and execute the “NETLOAD” command:




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




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




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



The messages are usually understandable - they will help you to understand if the case is not very clinical. :)

Nb:
if the plug-in could not load due to an error, then before testing the next (corrected) version, close and restart AutoCAD. Otherwise, it may refuse to load the plugin, even if there are no errors in the code anymore.

Now that the plugin is loaded, you can run our test command:




... and see the result:



Works. Now you can close AutoCAD.

But what about ...
Yes - an attentive reader, of course, will notice that when AutoCAD is closed, for some reason we will not see the “Goodbye” message. As mentioned above, not all can be done inside the “Terminate” function. But with its help it is quite possible, for example, to create a file when you close AutoCAD.

2.5. Debug plugin (if necessary)

The procedure for running the plugin for debugging is very well written in this post Tepliuk .

The final


Well, for the first time is enough. It remains to bring the promised links. In the post Namolem and post n00buK already given a large amount of sources; I will duplicate some of them here.

  1. http://adn-cis.org/forum/ (rus) - Forum of the Autodesk Programmers Community in the CIS . One of the best Russian-speaking resources among all I met in 2013-2014. I myself go there for advice when I am very hot, and so far there has not been a chance for me to be helped. Although I, of course, try not to particularly abuse.
  2. http://forums.autodesk.com/t5/russkoe-soobshchestvo/bd-p/392 (rus) - official forums Autodesk - section of the Russian community. You can ask questions.
  3. http://forums.autodesk.com/t5/net/bd-p/152 (eng.) - official forums Autodesk - a section dedicated to the .NET API. You can also ask a question - true, it can be ignored.
  4. http://through-the-interface.typepad.com (English) is a blog maintained by Kean Walmsley , one of the leading experts in AutoCAD development. The most valuable resource. You can try to ask something from the blog host himself - and even get an answer if he is in the mood. However, Kean often ignores uninteresting (and simple) questions - or invites the questioner to look for a solution in the official forum (see Figure 1) .
  5. http://adndevblog.typepad.com (English) - a collective blog of developers from the ADN . Sometimes it is useful.
  6. http://www.theswamp.org/index.php (Eng.) - another forum with many examples and solutions.

On this my article is over. If they recognize her as fit, I will write a few more simple notes about what I’ve encountered, such as:

Thanks for attention!

Source: https://habr.com/ru/post/235723/


All Articles