Secondary development of AutoCAD using C #

zhaozj2021-02-12  176

Secondary development of AutoCAD using C # (1)

Oh, put it in front of the article on the table in front of you.

Secondary development of AutoCAD using C # (1)

It is well known that the main tools for the second development of AutoCAD are: ObjectARX, VBA, VLISP. However, their advantages and disadvantages are obvious: ObjectARX is powerful, high programming efficiency, but its disadvantage is that the programmer must master VC , and this language is very difficult; VBA and VLISP are simple and easy to play, but they have a large-scale The program seems to be in powerless. Is there any language that can be used to combine their advantages and try to avoid their shortcomings? The answer is yes, that is, Microsoft's new 21-World programming language C #. For details on C #, you can refer to the relevant article. C # is communicating between the AUTOCAD ACTIVEX bridge and AutoCAD. AutoCAD ActiveX enables users to operate AutoCAD from the inside or outside of AutoCAD. It is this by displaying the AutoCAD object to the "external world". Once these objects are displayed, many different programming languages ​​and environments can access them. With regard to AutoCAD ActiveX, you can refer to the help of AutoCAD. Oh, say so much boring, or let us explain how to use C # for secondary development with C # through a concrete example. Let's talk about the configuration before the presentation: (1) Visual Studio .NET (2003 and 2002 can, I am using 2002)

(2) AutoCAD2000 or above (I use 2004) This example is very simple, it is to start autocad and draw a straight line through a form created by C #. The following is a specific step of programming: (1) establish a C # Windows application via Visual Studio .NET. (2) Right-click the "Reference" tab in "Solution Explorer", select "Add Reference" in the pop-up menu, select the drop-down list box under the "COM" tab in the Add Reference dialog "AutoCAD 2004 Type Library" item (Note: Different versions of CAD numbers), click the "Select" button on the right, and finally click the "OK" button below. (3) Adding two text boxes and a button in the C # form, which are used to enter the straight start point, the coordinates of the end point, and draw straight lines in CAD. The following main explanation of the added code. (A) In the beginning of the program: Using AutoCAD; // Import AutoCAD References Space (B) Add: Private AcadApplication A; // Declaration AutoCAD Object (c) Add to : A = new acadApplicationclass (); // Create AutoCAD object a.visible = true; // Enables AutoCAD visible (D) to join: double [] startpoint = new double [3]; // declaration Straight start point coordinate Double [] endpoint = new double [3]; // Declaration line endpoint coordinate string [] str = textbox1.text.split (',');

/ / Remove the value of the straight start coordinate input 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 the STR array into Double Str = TextBox2.text.split ('); // Remove the value of the line endpoint input text box for FOR (INT i = 0; i <3; i ) endpoint [i] = convert.todouble (STR [i]); a.activedocument.modelspace.addline (startpoint, endpoint); // Painted straight line A.Application.Update () in AutoCAD; // Update display, simple Let's try it. With regard to the usage of some statements above, I will introduce in the next lecture. Secondary development of AutoCAD using C # (2)

Secondary development of AutoCAD using C # (2)

C # talent bird

Hello everyone, today I continue to introduce you to the second development of AutoCAD using C #. In this lecture, it mainly introduces the problems existing in the previous talk.

In the previous example, I used the AutoCAD 2004 Type library to communicate between C # and AutoCAD, but this method has two fatal disadvantages. The first disadvantage is that the C # must restart AutoCAD every time the debugger, if the number of times the debugging is large (such as tracking error and then debugging), then the programming efficiency is very low, because starting a CAD still takes a longer time . The second disadvantage is more decent with respect to the first disadvantage. Due to the problem of .NET itself, the interop.autocad.dll file (that is, the communication between C # and AutoCAD) has some bugs, so although your code is completely correct, the C # compiler is still throwing An inexplicable mistake. Isn't that end? I once had a stage because these two hit Dongdong gave up C # and wanted to change the ObjectARX, huh, but still luck, I occasionally read an article written by foreigners in the Internet, he specially introduced The solution for these two issues. Below to solve these two problems.

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

1. Just use Visual Studio .NET to create a C # application, follow the setup in the previous article to join AutoCAD 2004 Type Library, then do not join any code, compile your program.

2. Use ILDASM.EXE in the Visual Studio .NET command line tool (this tool can be found in the Visual Studio .NET installation CD) put the interop.autocad.dll file (this file BIN / RELEASE Compiled into an intermediate language interop. AutoCAD.IL in the folder. Note: The compilation setting of the item established in step 1 is release mode.

ILDASM.EXE / SOURCE Interop.autocad.dll / Output = Interop. AutoCAD.IL

Also pay attention: put ildasm.exe, interop.autocad.dll in the same directory.

3. Open the interop. Autocad.il file in Notepad, then look for the end of "SinkHelper" and start the statement of ".class private auto ANSI SeaCad", change the private in the statement to public, then save Interop. AutoCad.il file. 4. Compile Interop.autocad.dll files using ILASM.EXE, which is also made under Visual Studio .NET command line tools.

ILASM.EXE /RESOURCE = Interop.autocad.res / dll interop.autocad.il / output = interop. AutoCAD.DLL

The interop.autocad.RES file is generated in step 1.

5. Obviously, you don't want to join Interop. AutoCad.dll through the method described in the previous article every time you write an application, it is too much trouble. You can use the following method to let the program automatically join the file: Find the C: / Program Files / Microsoft.Net / Primary Interop Assemoft.Net / Primary Interop assembly folder, then generated above

Interop.autocad.dll file copies.

Ok, the second question is solved, and then look at the first one.

In VBA, the programmer can use the getObject function to get the current active autocad object, but in C #, don't, for this function I almost parallel MSDN, then go to the various C # Forum to ask everyone, the result is not Get solved, huh, huh, maybe use C # people in China. It is still seen in the foreigner forum that is the article that speaks this problem is solved. Use the following statement to get the current actoCAD object:

(Acadapplication) Marshal.getActiveObject ("AutoCad.Application.16")

(For CAD2000 and CAD2002, 16 is changed to 15)

Of course, the above statement must be used in the case of AutoCAD, otherwise an error will occur. For the case where AutoCAD is not open, the method of the previous article can be used. Complete connection of AutoCAD and C # as follows:

Using system;

Using AutoCAD;

Using system.Runtime.InteropServices;

Namespace Academplexample

{

Public Class AutoCadconnector: IDisposable

{

PRIVATE ACADAPPLICATION_Application;

Private bool_initialize;

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 Will Upon Destruction

~ AutoCadConnector ()

{

Dispose (false);

}

Public AcadApplication Application

{

get

{

// Return Our IntersAl 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 Dispose Gets Called By Our

// deStructor.

Protected Virtual Void Dispose (BOOL Disposing)

{

// if we create Our AutoCAD Instance, Call ITS

// quit method to avoid leaking memory.

IF (! this._disposed && _initialize)

_application.quit ();

_disposed = true;

}

}

}

Use Visual Studio.net to compile the above program into a class library, you can use it in the later program, the following example illustrates its usage. (First include the Academple 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 is the title of the current document in AutoCAD in the C # window.

Use ObjectDBX technology in C # Never open information to get information in graphics

Use ObjectDBX technology in C # Never open information to get information in graphics

Can I get information about the drawing from the unmoping graphic? Answer is affirmative. The specific implementation method will be described below.

Claim:

n uses C # programming

n Read I wrote "Second Development of AutoCAD using C #"

Start:

N new construction C # console programs in Visual Studio.net

n Add the following class library in the reference tab:

l interop.autocad.dll

l acadexample.dll

l ObjectDBX16 (right-click "Reference" tab in "Solution Explorer", select Add References in the pop-up menu, select in the Add Reference dialog box in the drop-down list box under "COM" tab "AutoCAD / ObjectDbx Common 16.0 Type Library" item)

Then type the following code:

1: using system; 2: using autocad;

3: using dbx = axdblib;

4: using acadexample;

5:

6: Namespace ConsoleApplication1

7: {

8: ///

9: /// Summary Description for Class1.

10: ///

11: Class Class1

12: {

13: ///

14: /// The main entry point for the application.

15: ///

16: [Stathread]

17: static void main (string [] args)

18: {

19: Using (AutoCadconnector Connector = New AutoCadConnector ())

20: {

21: String progid = "Objectdbx.axdbdocument.16"

// Note that this is the writing of AutoCAD2004,

// If AutoCAD2002 and AutoCAD2000i are "objectdbx.axdbdocument.1"

22: acadapplication acadapp = connector.Application;

23: dbx.axdbdocument dbxdoc;

24: dbxdoc = (dbx.axdbdocument) acadapp.getInterfaceObject (progID);

25: dbxdoc.open (@ "f: /test.dwg");

26: Foreach (dbx.acadentity Entity In dbxdoc.modelspace)

27: {

28: IF (entity.entityname == "acdbblockreference")

/ / Judgment whether the entity is a block reference

29: {

30: dbx.acadblockreference BLKREF;

31: BLKREF = (dbx.acadblockreference) Entity;

// will be a block reference entity forced to block reference type

32: Object [] atts = (Object []) BLKREF.GETATTRIBUTES ();

// Get the properties in block reference (for object type)

33: for (int i = 0; i

34: {

35: dbx.acadattributereference att;

36: ATT = (dbx.acadattributereference) Atts [i]; // Convert block reference attribute (object type) to block reference attribute type

37: console.writeline ("tag: {0} / TValue: {1} / n",

38: att.tagstring,

39: att.textString; // Display block reference attributes TAG and TEXT value

40:}

41:}

42:}

43: console.readline ();

44:}

45:}

46:}

47:}

The first one should pay attention to the third line, using an alias. Because AutoCAD and ObjectDBX namespace have many identical class names, you have to use a full name, but you can't use a short-write form, but ObjectDBX is more troublesome, so use alias DBX to make the input is convenient.

The code in front of the program, you can refer to the article I wrote "Secondary Development of AutoCAD" with C # ". Let's see row 21, the program defines a string ProgID, as a parameter of the function GetInterfaceObject of the 24th sentence, the function is used to generate an AXDBDocument object. But note that the type returned by the GetInterfaceObject function is Object, so you have to turn it into the AXDBDocument class with forced conversion. Then, on the 25th line, the AXDBDocument object generated by the 24 line is "Open" one .dwg file (actually not open), you need to pay attention to the path of this file must be correct. This file is the file where the block information we have to get.

Since ObjectDBX has no selection set, only the block information (26-28 rows) is obtained by the model space of the traversal file.

The description of the remaining statement I have written in the comment of the program.

You can find that ObjectDBX works in C # is similar to VBA, but only necessary types of conversions.

转载请注明原文地址:https://www.9cbs.com/read-7220.html

New Post(0)