Two-time AutoCAD development with C #

Source: Internet
Author: User
Tags net command

as we all know, the main tools used to develop AutoCAD for two times are: Objectarx,vba,vlisp. But their advantages and disadvantages are obvious: Objectarx powerful, high programming efficiency, but its disadvantage is that programmers must master VC + +, and the language is very difficult to learn; VBA and Vlisp are easy to get started with, but they seem powerless to develop large programs. Is there a language that can combine their merits and try to avoid their shortcomings? The answer is yes, that is Microsoft's new 21st Century programming language C #. For a detailed introduction to C #, you can refer to the relevant articles.
C # is communicating with AutoCAD through the AutoCAD ActiveX Bridge. AutoCAD ActiveX enables users to programmatically manipulate AutoCAD from inside or outside of AutoCAD. It does this by displaying AutoCAD objects to the "outside world". Once these objects are displayed, many different programming languages and environments can access them. For AutoCAD ActiveX scenarios, you can refer to the help that comes with AutoCAD.
Oh, say so much boring, or let us through a concrete example to illustrate how to use C # for AutoCAD two times development bar. Before introducing the example, let's talk about the configuration:
(1) Visual Studio. NET (2003 and 2002 Yes, I'm using 2002)

(2) AutoCAD2000 or later (I use 2004)
This is a simple example of using a form created by C # to start AutoCAD and draw a line. Here are the specific steps for programming:
(1) Build a C # Windows application through Visual Studio. Net.
(2) In Solution Explorer, right-click the References tab, select Add Reference from the pop-up menu, and in the Add Reference dialog box, select the AutoCAD 2004 Type Library in the drop-down list box under the COM tab Item (note: Different versions of the CAD number are different), click on the right of the "select" button, and then click the "OK" button below.
(3) Add two text boxes and a button to the C # form, respectively, to enter the coordinates of the start point and end point of the line and draw a straight line in CAD. Here is the main explanation for the added code.
(a) join at the beginning of the program: using autocad;//import AutoCAD reference space
(b) In the Variable Declarations section of the form: private acadapplication a;//declaring AutoCAD objects
(c) in the form's constructor section, add: A=new acadapplicationclass ();//Create AutoCAD Object
a.visible=true;//making AutoCAD visible
(d) In the message handler function of the button, add:
double[] startpoint=new double[3];//Declare line start coordinates
double[] endpoint=new double[3];//declaration line end coordinates
string[] Str=textbox1.text.split (', ');//Take out the line start coordinates enter the value of the text box, the input mode of the text box is "x, Y, z"
for (int i=0;i<3;i++)
startpoint[i]=convert.todouble (Str[i]);//convert str array to double type
str=textbox2.text.split (', ');//Remove the line end coordinate enter the value of the text box
for (int i=0;i<3;i++)
endpoint[i]=convert.todouble (Str[i]);
A.activedocument.modelspace.addline (startpoint,endpoint);//Draw a line in AutoCAD
a.application.update ();//update display
OK, easy, you can try compiling. For the use of some of the above statements, I will give you a detailed introduction in the next lecture.

Hello everyone, today I continue to introduce to you the two development of AutoCAD using C #. In this lecture, we mainly introduce the problems in the previous example.

in the last example, I used the AutoCAD 2004 Type Library to communicate between C # and AutoCAD, but there are two fatal drawbacks to this approach. The first drawback is that C # restarts AutoCAD every time the program is debugged, and if the number of debugs is very high (such as tracking errors and debugging), then programming is inefficient because it takes a long time to start a cad. The second disadvantage is more deadly than the first one. Because. NET itself, there are some bugs in the Interop.AutoCAD.dll file (that is, the communication between C # and AutoCAD is implemented by it), so although sometimes your code is completely correct, the C # compiler throws an inexplicable error. Isn't that a dead end? I used to have a stage because these two deadly things almost gave up C # and want to change learning Objectarx, hehe, but still lucky, I occasionally read a foreigner in the online article, he specifically introduced the two problems of the solution. Here are the two issues to solve.

First look at the second problem, follow the steps below:

1. Use visual Studio casually. NET to build a C # application, then follow the settings in the previous article to add the AutoCAD 2004 Type Library, then do not add any code to compile your program.

2. In Visual Studio. NET command-line tool with Ildasm.exe (this tool can be used in visual Studio. NET installation CD), compile the Interop.AutoCAD.dll file (the file in the Binrelease folder of the project that you generated in step 1) into the intermediate language interop. Autocad.il. Note the compilation of the project that was established in step 1 is set to release mode.

Ildasm.exe/source Interop.autocad.dll/output=interop. Autocad.il

notice again: Put the Ildasm.exe,interop.autocad.dll in the same directory.

3. Open Interop in Notepad. autocad.il file, and then look for the statement that ends with "sinkhelper" and begins with ". Class private auto ANSI sealed _DACAD", change the private statement to public, and then save the interop. autocad.il file.

4. Use Ilasm.exe to compile the interop. autocad.il file into a Interop.AutoCAD.dll file, which is also in visual Studio. NET command-line tool.

Ilasm.exe/resource=interop.autocad.res/dll Interop.autocad.il/output=interop. AutoCAD.dll

The Interop.AutoCAD.res file was generated in step 1.

5. Obviously you don't want to add interop every time you write an application by using the method described in the previous article. AutoCAD.dll, that's too much trouble. You can use the following method to have the program automatically join the file: Find the C:Program filesmicrosoft.net Primary Interop Assemblies folder, and then put the generated

Copy the Interop.AutoCAD.dll file in.

OK, the second problem is solved, next look at the first one.

in VBA, the programmer can use the GetObject function to get the currently active AutoCAD object, but in C #, but not, for this function I almost the MSDN to turn over, and then go to all kinds of C # forum to ask you master, the results have not been solved, hehe, probably domestic use C # Less people. Or in the foreigner's forum to see an article is to talk about this issue to solve the problem. Use the following statement to get the currently active AutoCAD object:

(acadapplication) marshal.getactiveobject ("autocad.application.16")

(for CAD2000 and CAD2002, change 16)

of course, the above statement must be opened in the case of AutoCAD to use, or there will be an error, for AutoCAD is not open, you can use the method of the previous article to handle. The complete source program for AutoCAD and C # is as follows:

using System;

using AutoCAD;

using System.Runtime.InteropServices;

namespace Acadexample

{

Public class Autocadconnector:idisposable

{

private acadapplication _application;

private bool _initialized;

private bool _disposed;

Public autocadconnector ()

{

Try

{

//Upon creation, attempt to retrieve running instance

_application = (acadapplication) marshal.getactiveobject ("autocad.application.16");

}

Catch

{

Try

{

//Create An instance and set flag to indicate this

_application = new Acadapplicationclass ();

_initialized = true;

}

Catch

{

throw;

}

}

}

//If The user doesn ' t call Dispose, the

//garbage collector'll upon destruction

~autocadconnector ()

{

Dispose (false);

}



Public acadapplication Application

{

Get

{

//Return Our internal instance of AutoCAD

return _application;

}

}



//This is the user-callable version of Dispose.

//It calls our internal version and removes the

//object from the garbage collector ' s queue.

Public void Dispose ()

{

Dispose (true);

GC. SuppressFinalize (this);

}



//This version of the Dispose gets called by our

//destructor.

protected virtual void Dispose (bool disposing)

{

//If We created our AutoCAD instance

//Quit method to avoid leaking memory.

if (!this._disposed && _initialized)

_application. Quit ();



_disposed = true;

}

}

}

Using Visual Studio.NET to compile the above program into a class library, you can use it in a later program, and the following example illustrates its usage. (First include the Acadexample class library in the project)

using System;

using Acadexample;

using AutoCAD;

namespace ConsoleApplication6

{

class Class1

{

[STAThread]

static void Main (string[] args)

{

using (autocadconnector connector = new Autocadconnector ())

{

Console.WriteLine (connector. Application.ActiveDocument.Name);

}

console.readline ();

}

}

}

This example shows the title of the current document in AutoCAD in the C # window.

The main content of this lecture is to introduce the AutoCAD object model, which should be ultra-simple if you understand the VBA development AutoCAD.
objects are the primary building blocks of the AutoCAD ActiveX interface, and each displayed object represents exactly one AutoCAD component. The main objects of the AutoCAD ActiveX interface are:
• Graphic objects such as lines, arcs, text, and callouts.
• Style settings objects such as line style and dimension styles
• Organizational objects such as layers, groups, and blocks
• Graphical display objects such as views and viewports.
• Graphics, AutoCAD applications themselves are objects
the root object of all objects is the AutoCAD application itself, which is represented by the Acadapplication class. Getting the currently running Acadapplication object can be obtained using the method described in the previous section. The Acadapplication object is composed of four sub-objects, namely:

? A Acadpreferences object that enables you to access and set the relevant options in the Options dialog box
? A Acaddocuments object that represents the AutoCAD drawing
? A Acadmenubar object that represents the main AutoCAD menu bar (note that it is not acadmenubars because the application has only one main menu bar)
? A Acadmenugroups object that represents the AutoCAD menu and toolbar
The general composition of the AutoCAD ActiveX interface object model is described above, with the following emphasis on the Acaddocuments object, because most of the programming is related to it. First you see that it is a plural form, so it is a collection of all the drawings of AutoCAD that are currently open, which is called the collection object (hehe, as if talking nonsense). Collection objects have some more important methods and characteristics. The most important is that the count attribute is used to get the number of objects in the collection (zero-based), and the Item method is used to get any object in the collection. I will describe them in the following example. The singular form of acaddocuments, Acaddocument, represents an AutoCAD drawing that is currently open. The Acaddocument object consists of several main objects:
? Acadmodelspace Collection and Acadpaperspace collection, providing access to graphical objects (lines, circles, etc.)
? Acadlayers, Acadlinetypes, and acadtextstyles provide access to non-graphical objects (layers, linetypes, text styles, and so on)
? The Acadplot object provides access to settings in the Print dialog box and provides a variety of ways to print graphics for the application process
? Acadutility object provides user input and conversion functions
Graphical object creation uses the Add method, such as creating a circle, using the Add method instead of the Addcircle method, rather than the creation of a graphical object.
Here is a simple example to illustrate what is described above. This example creates a new layer in AutoCAD and then draws a red circle and a green line in the layer. This is the source code of the program: (Please first put the interop generated in the previous lecture.) AutoCAD.dll and AutoCADExample.dll files are included in the project)
using System;
using Acadexample;
using AutoCAD;

namespace Circleline
{
///


/// Class1 's summary description.
/// 
class Class1
{
///
/// The main entry point of the application.
/// 
[STAThread]
static void Main (string[] args)
{
//
//TODO: Add code here to launch the application
//
using (Autocadconnector connector=new autocadconnector ())//connecting AutoCAD
{
acaddocument Adocument=connector. Application.activedocument;
//Get current AutoCAD active drawing object
double[] center=new double[3]{20,20,0};//Set Center
Double radius=20;//set the radius of the circle
double[] Startpoint=new double[3]{0,0,0};//Set the starting point of the line
double[] Endpoint=new double[3]{40,40,0};//Set the end point of the line
acadlayer newlayer=adocument.layers.add ("Circleline");
//Create a new layer named Circleline
adocument.activelayer=newlayer;//Set the Circleline layer to the current layer
acadcircle circle=adocument.modelspace.addcircle (Center,radius);//Join the Circle
acadline Line=adocument.modelspace.addline (startpoint,endpoint);//Join a line
circle.color=acad_color.acred;//turn the circle into red
line.color=acad_color.acgreen;//turn the line into green
connector. Application.update ();//update display
for (int i=0;i Console.WriteLine ("This is the {0} object: {1}", I+1,adocument.modelspace.item (i));//traverse the current drawing

}
console.readline ();
}
}
}
All right, here we go today.

Two-time AutoCAD development with C #

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.