Sie sind auf Seite 1von 11

AutoCAD® .

NET Basics, Part I

AutoCAD® .NET Basics, Part I


Stephen Preston – Autodesk Inc

DE111-2 Wondering what all the hype is around .NET? We’ll give you the basic information you
need to get up to speed on writing your own .NET applications based on the AutoCAD .NET API. In this class,
you’ll learn about the.NET Framework and what is means for programmers; how to write your first AutoCAD
.NET add-in; the simple user interaction required, including point selection and keyword entry; a discussion of
the DWG database structure; how to add CAD entities to the DWG database; and how to traverse the entities
already in the DWG.

About the Speaker:


Stephen has been a member of the Autodesk Developer Technical Services Team since 2000, first as a
support engineer and then as manager of the EMEA (Europe, Middle East, and Africa) Team. In those roles,
his responsibilities included support for the AutoCAD APIs, including ObjectARX and AutoCAD .NET, as well
as AutoCAD OEM and RealDWG technologies. Currently, he manages the Developer Technical Services
Team in the Americas and serves as Workgroup Lead, working closely with the AutoCAD engineering team
on future improvements in the AutoCAD APIs. Stephen started his career as a scientist, and has a PhD in
Atomic and Laser Physics from the University of Oxford.
AutoCAD® .NET Basics, Part I

 
AutoCAD® .NET Basics, Part I

AutoCAD .NET Basics, Part I 
What this seminar is (and what it isn’t) 
AutoCAD .NET Basics is an introduction to the AutoCAD .NET API. The seminar is in two parts,
continuing in

DE115-2 – AutoCAD .NET Basics, Part II

Because this seminar spans two sessions, the handout for DE115-2 will be a continuation of
these notes.

These two seminars are intended to form a ‘foundation’ for the other .NET seminars being
delivered by the Autodesk Developer Network team. These are:

DE205-2 – AutoCAD® .NET Show and Tell

DE201-2 – AutoCAD® .NET: Tell Me About It!

DE211-2 – The Best of Both Worlds: .NET and LISP Can Coexist

This is not a beginner’s class on programming. The seminar assumes that you have a basic
understanding of simple programming concepts, and that you are familiar with AutoCAD.
Experience of programming in the .NET environment is not required, but is a ‘nice to have’. The
same applies for an understanding of Object Oriented programming concepts. It is assumed
that you have never before used the AutoCAD .NET API 1 .

That said, even if you’ve never programmed before, this series of seminars will show you what’s
possible with AutoCAD .NET. Knowing what’s possible is the first step in learning how to make it
so.

A very brief history of the AutoCAD.NET API 
The first version of the AutoCAD .NET API (often called ObjectARX .NET) was released with
AutoCAD 2005. Before then, use of the .NET Framework with AutoCAD was restricted to
automating AutoCAD from an external .NET application through COM Interop. Using COM
Interop is really just using .NET as a glorified VB6 application, and is very different from a native
.NET API.

The AutoCAD 2005 .NET API was a preview version. It did include the classes required to
access the DWG Database and all the objects in that Database, but the ‘editor’ (or non-DWG-
related) API was very limited - only allowing the creation of very simple commands.

1
A note to beginners – ‘API’ means ‘Application Programming Interface’. That’s the set of functions that
AutoCAD exposes that you can use in your application to make AutoCAD do what you want.
AutoCAD® .NET Basics, Part I

AutoCAD 2006 saw the release of our first full .NET API, and there were a few architectural
changes to allow greater flexibility. The main change was the introduction of Transactions as the
primary means of modifying the DWG Database. (The 2005 API relied on the Open/Close
model). The 2006 API release completed the DWG Database access functionality (adding a few
classes for AutoCAD entities that were missing from the 2005 release), and adding lots of
‘Editor’ functionality (such as InputPointMonitors, SelectionSets, advanced command line
interaction, to name but a few) and a comprehensive Event model.

Since the AutoCAD 2006 release, the .NET API architecture has remained unchanged.
Changes since then have been in adding new APIs corresponding to new product features. In
fact, some AutoCAD APIs (the CUI API, for example) are only available as .NET APIs.
However, the 2007 API did take advantage of AutoCAD 2007 being a ‘binary incompatible’
release to move from .NET Framework 1.1 to .NET Framework 2. As the API now uses features
introduced in Framework 2, it is no longer possible to develop AutoCAD .NET applications using
an IDE that relies on older .NET Frameworks.

A Hello World tutorial 
As you’re really keen to learn the AutoCAD .NET API, you’ll have picked up this handout when
you arrived at AU, and you’re now sitting in your hotel room with your laptop ready to fire up
Visual Studio 2005 2 to get ahead of the game before the seminar. So go on then – double-click
that squirly icon and fire it up. You know you want to!

If you’ve ever been subjected to a ‘learn to program’ tutorial before, you’ll know that every
beginner’s tutorial in the world starts with a ‘Hello World’ project. Who are we to break with
decades of tradition? …

Once Visual Studio has started, you need to create a new project. Go to the File menu and
select New->Project….

2
By the way, you don’t have to buy Visual Studio to write your AutoCAD .NET add-ins. There are a
number of free development environments available. For example, you can use Visual Studio Express,
but you have to tweak it a little to get it to work – see Kean Walmsley’s blog posting for details
(http://through-the-interface.typepad.com/through_the_interface/2006/07/debugging_using.html).
AutoCAD® .NET Basics, Part I

Unsurprisingly, this displays the New Project dialog.

We’re going to create a small VB.NET project. The steps are pretty much the same for C#; it’s
just the C# syntax around the AutoCAD API calls that differs. We’ll show a C# project in the
seminar.

Click on the Visual Basic Project type and select the Class Library Template. Then give the
project a name. You can call it anything you like, but (being a slave to tradition) I’m going to call
it ‘HelloWorld’.

When you’ve done that, click OK.

Now open the Solution Explorer window (the View->Solution Explorer menu item) if it’s not
already open; double click on My Project; and select the References tab.
AutoCAD® .NET Basics, Part I

Click the Add button, select the Browse tab; navigate to C:\Program Files\AutoCAD 2008 (or
wherever your AutoCAD is installed), and search for *mgd.dll (i.e. type *mgd.dll in the File name
textbox and click OK).

This will display all the files in that folder ending with ‘mgd.dll’.

Now select acmgd.dll and acdbmgd.dll by Ctrl-clicking on them both; then click OK. These are
the two DLLs that expose the AutoCAD .NET API.

acmgd.dll exposes all the Editor functionality (SelectionSets, Commands and Keywords,
Prompts and Dialogs, etc.);

acdbmgd.dll exposes all the Database access functionality (the DWG Database itself,
Lines, Circles, MText, etc.).
AutoCAD® .NET Basics, Part I

Back on the My Project screen References tab, double-click on acdbmgd.dll to display its
Properties, and set Copy Local to False. (This is to ensure your .NET add-in loads the copy of
acdbmgd.dll stored in the AutoCAD folder and doesn’t try to make and load a local copy. You
probably guessed that from the property name).

Then do the same for acmgd.dll.

Now we want to write our code. Double-click on ‘Class1.vb in the Solution Explorer window.
This is where you write your add-in code. Edit the template code as follows:

Imports Autodesk.AutoCAD.Runtime
Imports Autodesk.AutoCAD.ApplicationServices
Imports Autodesk.AutoCAD.DatabaseServices

Public Class Class1

<CommandMethod("HelloWorld")> _
Public Sub MyMethod()
Application.ShowAlertDialog("Hello World from VB.NET!")
End Sub

End Class

The Imports statements allow you to use classes from the namespaces you import without
having to type out the full namespace. You don’t strictly need them, but the code becomes hard
to read otherwise. For example,

Application.ShowAlertDialog("Hello World from VB.NET!")


AutoCAD® .NET Basics, Part I

becomes

Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("Hello
World from VB.NET!")

There are several other Autodesk.AutoCAD namespaces, but these are the three you’ll need in
just about every AutoCAD add-in you write. (In this example, DatabaseServices is not strictly
necessary).

<CommandMethod("HelloWorld")> is an attribute. This is telling AutoCAD to run the


subroutine MyMethod when the user types HELLOWORLD on the command line. The rest of
the code is self-explanatory.

That’s all the code we need. But before we can test our first AutoCAD add-in we have to set one
more project setting. Double-click again on My Project in the Solution Explorer; select the
Debug tab; set the Start Action to Start external program; and enter the location of the AutoCAD
executable – the default location is C:\Program Files\AutoCAD 2008\acad.exe. This is telling
Visual Studio that you’re going to load your DLL into the AutoCAD process space to debug it.

Now we’re ready to run our add-in. Hit F5 to start debugging, and AutoCAD will launch. Type
NETLOAD on the command line and hit ENTER. In the NETLOAD file select dialog, navigate to
the location of your compiled .NET assembly DLL. This should be in location shown below,
unless you changed your default project settings.
AutoCAD® .NET Basics, Part I

The assembly DLL is called HelloWorld.dll. Double-click on it to load it.

Now type HELLOWORLD at the command line, and AutoCAD will display this dialog.

Congratulations! You’ve just created your first custom command using AutoCAD .NET.

But let’s not stop just yet. Switch back to Visual Studio and hit Shift+F5 to stop the debugging
session, open up Class1.vb by double-clicking on it in the Solution Explorer, and replace all the
code in that document with this:

Imports Autodesk.AutoCAD.Runtime
Imports Autodesk.AutoCAD.ApplicationServices
Imports Autodesk.AutoCAD.DatabaseServices

Public Class Class1

<CommandMethod("HelloWorld")> _
Public Sub MyMethod()

' Some variable definitions


Dim DB As Database
Dim BT As BlockTable
Dim MS As BlockTableRecord

' Start a transaction to edit the DWG database


Using trans As Transaction =
Application.DocumentManager.MdiActiveDocument.TransactionManager.StartT
ransaction()

' Open ModelSpace BlockTableRecord ready to add entity


DB = Application.DocumentManager.MdiActiveDocument.Database
BT = trans.GetObject(DB.BlockTableId, OpenMode.ForRead)
MS = trans.GetObject(BT(BlockTableRecord.ModelSpace),
OpenMode.ForWrite)
AutoCAD® .NET Basics, Part I

' Create a new MText entity and set its text


Dim txt As MText = New MText
txt.Contents = "Hello World from VB.NET"

' Add the MText to ModelSpace


MS.AppendEntity(txt)

' Add the Mtext to the transaction


trans.AddNewlyCreatedDBObject(txt, True)

' Commit transaction so changes persist in the DWG


Database.
trans.Commit()

End Using

End Sub

End Class

Now hit F5 again; NETLOAD the HelloWorld.dll; and invoke the HELLOWORLD command
again. ZOOM EXTENTS and you should see this:

Give yourself a big hug – you’ve just created your first drawing using VB.NET.

The comments in the code and the function calls we make to add the MText to ModelSpace
should give you an inkling of how the DWG Database is structured. Understanding this is key to
understanding how to use the AutoCAD .NET API. That’s something we’ll be discussing in
depth in the seminar. And that’s all for now. Read on in the handout for DE115-2 – AutoCAD
.NET Basics, Part II, where we’ll analyze the code we used here, and take a whistlestop tour of
the DWG Database format and the AutoCAD .NET Object Model.
AutoCAD® .NET Basics, Part I

Further reading 
Here are a few places you can go to for more information on the AutoCAD .NET API:

• www.autodesk.com/developautocad - for a general overview of the AutoCAD APIs and


publicly available resources.

• www.autodesk.com/apitraining - if you’re interested in attending classroom training


delivered by the Autodesk Developer Network team.

• www.autodesk.com/joinadn - to find out how becoming a member of the Autodesk


Developer Network can help your application development efforts, including our
members-only knowledgebase and unlimited technical support.

• www.objectarx.com – to download the ObjectARX SDK. This includes AutoCAD .NET


API documentation and samples.

• blogs.autodesk.com/through-the-interface – Kean Walmsley’s blog focusing primarily on


AutoCAD .NET. Kean is senior manager of the global Autodesk Developer Technical
Services team.

• discussion.autodesk.com/forum.jspa?forumID=152 – the Autodesk public discussion


group for the AutoCAD .NET API.

Acknowledgements 
Thank you to everyone in the Autodesk Developer Technical Services team (past and present)
for their contributions to the training material and SDK samples on which AutoCAD .NET Basics
is based.

Das könnte Ihnen auch gefallen