0% found this document useful (0 votes)
14K views

Creating A Command in AutoCAD With C#

This document provides steps to create a simple command in AutoCAD using C#. It discusses starting a Visual Studio project, adding references to AutoCAD libraries, setting up debugging in AutoCAD, and adding code for a basic command class and method.

Uploaded by

ask_ien
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14K views

Creating A Command in AutoCAD With C#

This document provides steps to create a simple command in AutoCAD using C#. It discusses starting a Visual Studio project, adding references to AutoCAD libraries, setting up debugging in AutoCAD, and adding code for a basic command class and method.

Uploaded by

ask_ien
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Creating a Command in AutoCAD with C#

James E. Johnson Synergis Software

CP2774-L This hands-on lab will show you how to create a new project in Microsoft Visual Studio
and do setup for an AutoCAD plug-in. You will learn how to add code to create a simple command and
add a splash screen or other initialization code. After that, we will create a command that uses a dialog
to display a user selection.

Learning Objectives
At the end of this class, you will be able to:
Start and set up a Visual Studio project as an AutoCAD plug-in
Create custom commands to be used within AutoCAD
Create and use dialogs with custom AutoCAD commands
Create initialization code for command-line prompts, splash screens, or other initial settings that are
required on loading

About the Speaker


James has worked with CAD products for more than 25 years, involved in many positions from
being a CAD drafter to writing automation applications. In his current position, he is doing CAD
integration for Adept document management system. In previous positions, he has used
Autodesk RealDWG to write custom automation to create AutoCAD drawings of industrial
kitchen equipment, and has worked at Autodesk resellers in software development groups
doing custom applications for Inventor and AutoCAD. He has taught AutoCAD and VBA
classes while working for resellers, and was a CAD instructor at two different community
colleges.

Email: [email protected]
Creating a Command in AutoCAD with C#

Getting Started with .NET and AutoCAD plugin development


To get started developing AutoCAD plugins you will need to have a version of Microsoft Visual
Studio installed. You can use the free versions of Visual Studio Express either VB.Net or C#
depending on the language you prefer. You will need to download and install the ObjectARX
SDK and should have a copy of AutoCAD installed for debugging...

Would also suggest downloading and installing the autocad_2013_dotnet_wizards.zip at :


http://usa.autodesk.com/adsk/servlet/index?id=1911627&siteID=123112, these wizards create
startup projects that assist in starting a new project with startup code, references and debugging
setup...

The first part of this Lab. will illustrate creating an AutoCAD plugin without using a template.

Start and set up a Visual Studio project as an AutoCAD plugin

The first thing we will do is to create a very simple plugin without using the AutoCAD wizard project.

1. Start Visual Studio

Use the Start menu and scroll to


Microsoft Visual Studio 2010.

Then select Microsoft Studio


2010...

Or on the desktop double click the shortcut icon for Microsoft


Visual Studio 2010...

2
Creating a Command in AutoCAD with C#

2. In Visual Studio select the file menu, and then select New, then select Project...

3. In the New Project dialog select Class Library under Visual C# Language...

3
Creating a Command in AutoCAD with C#

4. At the Bottom of the New Project dialog enter the name of the project..

Use the Browse button on right side to


browse to a folder for saving the project...

Then select OK button on right side...

We have an empty Class Library


project started (now to turn it into an AutoCAD plugin)...

The project is started with an empty


class file named Class1 with a
Class1 defined and has basic .NET
required references.

4
Creating a Command in AutoCAD with C#

5. Under the Visual


Studio menu Project
select the projects
properties

Select the Project menu


then select the project
properties menu item.

The Properties page is


where we will add the
AutoCAD .NET library
references and set up the
plugin for debugging in
AutoCAD.

The properties page can also be


opened with a mouse Right-Click on
the project in the Solution explorer...

5
Creating a Command in AutoCAD with C#

6. The next several steps will be to convert this project into an AutoCAD plugin.
The first requirement is to add references to the required AutoCAD DLLs .

Select the Project Menu,


then select
AddReference...

Or in the Solution Explorer, Or on References,


Right-Click on the project. Right-Click, select the
select Add Reference... Add Reference...

That opens the Add Reference


Dialog...

In this dialog select browse tab and


browse to the folder :

C:\ObjectARX 2013\inc...

In that folder we will select 3 files:


AcCoreMgd.dll, AcDbMgd.dll and
AcMGD.dll...

To Select all 3 files, Hold the Control


button and select the files with the
mouse.

Then select OK to add


references to these files to
the project...

6
Creating a Command in AutoCAD with C#

7. After adding the References to AcCoreMgd.dll, AcDbMgd.dll and AcMgd.dll we


need to adjust the setting for the DLLs to be copied local to False...

To select the three References we added hold


down the Shift key and select the references
with mouse Left-Click...

When the AutoCAD References are added they


are set to be copied local with the project, this
needs to be changed to False...

In the Properties Dialog Window with all


three of the new references selected, select
the drop down int the Copy Local property
and change it to False

8. Setup For Debugging...

On the properties page Select Start External Select the ... button
select the Debug Tab... Program... to browse to the
location of the
AutoCAD executable
file acad.exe...

7
Creating a Command in AutoCAD with C#

9. The next step is to add Using statements to add references to the namespaces
we will be using...

Open the Class1.cs file created with the


project and add the Imports statements for
the Autodesk namespaces that will be
used...

Use Visual Studio IntelliSense to


assist in entering the namespaces...

10. Add a CommandClassAttibute definition...

Adding the
CommandClassAttribute
definition is considered
Optional...

ObjectARX help says this about this...

This custom attribute class is used to mark a type as the application's command class.
An application may designate one, and only one, type as its command class. AutoCAD
looks for an application's command methods on the type that bears this attribute.

8
Creating a Command in AutoCAD with C#

11. Add the Command...

To add the Command you use the CommandMethod Attribute and at minimum specify the commands
global name. The following method will contain the code to process.

Use the CommandMethod with a


global name to add a command.

There are additional options we will use


later...

12. Save the Project

Use Save All to save the project and


all files...

The next step is to build, A build will


also save the project...

9
Creating a Command in AutoCAD with C#

13. The project needs to be built... .....From the Build Menu


Select Build Solution or use the
Function key F6

OR:

In the Solution Explorer. Right -click


on the project to show the context
menu...

.....Select Build

After Build:

Build succeeded should


appear in lower left corner...

If an error occurs then Build failed will be


displayed with the errors in the Error List
window...

10
Creating a Command in AutoCAD with C#

14. Configuration...

For debugging
the configuration
should be set to
Debug...

Change to Release
for deploying...

Check Project
property settings after
setting configuration
to Release...

Setting the Platform to Any CPU will allow your project to run on both 32 and 64 bit
systems...

11
Creating a Command in AutoCAD with C#

15. Test the command, Start a Session of AutoCAD for debug...

Or Click Toolbar button: Select Start Debugging or use the


function key F5 ...

Since we set the start external program


under the Debug tab in project properties
to the acad.exe file, this will start a
session of AutoCAD...

16. At AutoCAD Command line type the Command Netload

Browse to the Compiled DLL for the


project and click the Open button...

12
Creating a Command in AutoCAD with C#

17. Issue the command (our example is MyCommand)

This simple command only


displays an Alert box in AutoCAD...

18. To Debug...

Add a Breakpoint by Clicking in the


column to the left of the Line of code
to break on...

Then in AutoCAD run the command


again..

13
Creating a Command in AutoCAD with C#

Start a Visual Studio project as an AutoCAD plugin using the Wizard...

1. Start Visual Studio...

2. Select File menu pull down...

3. Select New Project...

4. Under Visual Basic select Autodesk, then Select the AutoCAD 2013 CSharp
plug-in template...

5. Set the Name of the new project and location to save then click OK...

14
Creating a Command in AutoCAD with C#

6. Select locations and requirements for the project on the Configurator


dialog then click OK...

7. The project is created with AutoCAD .NET DLL references, debug setup
and some example startup commands.

8. Compile then run debug and Netload into AutoCAD...

15
Creating a Command in AutoCAD with C#

Create custom commands to be used within AutoCAD

In startup project and in the wizard project the CommandMethod attribute was used to specify the
command(s). There is also a LispFunction attribute to define AutoLisp functions from a .NET AutoCAD
plugin.

CommandMethod attribute properties and Constructor overrides:

16
Creating a Command in AutoCAD with C#

LispFunction attribute properties and Constructor overrides:

Command Flags:

17
Creating a Command in AutoCAD with C#

Using the project we just created we will add a couple commands and
LispFunctions that use some of the properties and constructors...

1. Start Visual Studio and open the project created from the AutoCAD plugin
template...

2. Open the Class file (e.g. MyCommands.cs)...

Double-Click with left mouse button


to open the file

3. Scroll to the bottom of the MyCommands.cs file and before the last 2 closing
} brackets add the following command...
[CommandMethod("FirstCommand", "_FirstCommand", CommandFlags.Modal)]
public void fCommand()
{
Document doc = Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = doc.Editor;

ed.WriteMessage("Writing message to he command line...\n");


}

This command illustrates creating a command that uses the Modal flag, with a group name of FirstGroup
and a global name...

Run the with debug Starting AutoCAD then Netload the DLL and run the command.

18
Creating a Command in AutoCAD with C#

4. Next we will looks at the Session Flag...

Scroll to bottom and add the new command (debug/Netload)...


[CommandMethod("sessionCommand", "_sessionCommand",
CommandFlags.Modal | CommandFlags.Session)]
public void sessionCommand()
{
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
try
{
Document curdoc = Application.DocumentManager.MdiActiveDocument;
Document doc = Application.DocumentManager.Add("acad.dwt");

using (DocumentLock lockDoc = doc.LockDocument())


{
using (Transaction tr =
doc.Database.TransactionManager.StartTransaction())
{
// Open BlockTable
BlockTable blkTbl =
(BlockTable)tr.GetObject(doc.Database.BlockTableId,
OpenMode.ForRead);

// Open Modelspace BlockTableRecord for write


BlockTableRecord blkTblRec =
(BlockTableRecord)tr.GetObject(
blkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite);

// New circle with a radius of 2 at 10,6


Circle circ = new Circle(); Notes:
circ.SetDatabaseDefaults();
circ.Center = new Point3d(10, 6, 0); 1. The session flag cause
circ.Radius = 2; the command to run in
Application context.
// Add circle to ModelSpace and the transaction
blkTblRec.AppendEntity(circ); 2. Locking the document is
tr.AddNewlyCreatedDBObject(circ, true); required when running
in session context.
// Commit circle to the database
tr.Commit(); 3. The Using statement
} does cleanup when
} exited.

} 4. Try/Catch is used in
catch (System.Exception ex) case of errors.
{
ed.WriteMessage("Exception : " + ex.Message); 5. Notice the + used to add
} multiple flags...
}

19
Creating a Command in AutoCAD with C#

5. Add the following Command to Use the Undefined Undefined Command flag causes
Flag then run debug and Netload the DLL into command to be loaded as undefined.
AutoCAD...
[CommandMethod("undefinedCommand","_undefinedCommand",
CommandFlags.Modal | CommandFlags.Undefined)]
public void uCommand()
{
Document doc = Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = doc.Editor;

ed.WriteMessage("This command is undefined...\n");


}

Notice that the command is undefined in AutoCAD (Use .undefinedCommand)...

6. Add the following Command for an example of selecting an Entity in


AutoCAD...
[CommandMethod("getEntity", "_getEntity", CommandFlags.Modal)]
public void getEntityCommand()
{
Document doc = Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = doc.Editor;
PromptEntityOptions options =
new PromptEntityOptions("\r\nSelect an entity: ");
//Could set pre filter
//options.SetRejectMessage("\r\nMust be a Line...");
//options.AddAllowedClass(typeof(Line), true);
PromptEntityResult selectRes = ed.GetEntity(options);
if (selectRes.Status == PromptStatus.OK)
{
using (Transaction tr = HostApplicationServices.WorkingDatabase
.TransactionManager.StartTransaction())
{
DBObject dbObj = tr.GetObject(selectRes.ObjectId,
OpenMode.ForRead);
ed.WriteMessage("\r\nEntity selected was a " +
dbObj.GetRXClass().Name);
}
}
else
{
ed.WriteMessage("Nothing selected...\n");
}
}
Use the Runtime RX Class to get
Name property of the Database object.

20
Creating a Command in AutoCAD with C#

7. Use LispFunction Attribute to add an AutoLisp function, this simple example


takes an argument for the diameter and returns the circumference...
[LispFunction("getcircumference")]
public object getCircumference(ResultBuffer args)
{
Object ret = 0; Arguments are passed in as
if (args != null) a ResultBuffer
{
TypedValue[] typeVal;
typeVal = args.AsArray();

//ret = (Convert.ToDouble(typeVal[0].Value) * Math.PI);

//In real world case type vale should be type tested


//if ((int)typeVal[0].TypeCode == (int)LispDataType.Int16)
//{
// //DoSomething
//}
//else if ((int)typeVal[0].TypeCode == (int)LispDataType.Int32)
//{
// //DoSomething
//}
//else if ((int)typeVal[0].TypeCode == (int)LispDataType.Double)
Run debug and Netload the DLL, then type the following Lisp expression at
//{ the AutoCAD command line:
// //DoSomething
//} (setq circ (getcircumference 10.0))
}
return ret; The return value should be 34.159 and the variable circ is set to that value...
}

8. Use LispFunction to Return an AutoLisp LIST...


[LispFunction("returnList")]
public static ResultBuffer returnList(ResultBuffer resBufIn)
{
// Create ResultBuffer
ResultBuffer resBufOut = new ResultBuffer();
resBufOut.Add(new TypedValue((int)LispDataType.Text, "XXX"));
resBufOut.Add(new TypedValue((int)LispDataType.ListBegin));
resBufOut.Add(new TypedValue((int)LispDataType.Text, "YYY 1"));
resBufOut.Add(new TypedValue((int)LispDataType.Text, "YYY 2"));
resBufOut.Add(new TypedValue((int)LispDataType.ListEnd));
resBufOut.Add(new TypedValue((int)LispDataType.Text, "ZZZ"));

return resBufOut; Run debug and Netload the DLL, then type the following Lisp expression
} at the AutoCAD command line: (setq myList (returnlist))

21
Creating a Command in AutoCAD with C#

Create and use dialogs with custom AutoCAD commands

1. In Solution Explorer right-click on project.

a.select Add on the context menu...

b. select New Item...

c. select Windows Form and name the form in


text box...

Name the Form in Lower left


corner of the Add New Item
dialog. Then Click Add...

d. This creates the form, now use toolbox and add a button...

Drop the Button onto the


form...

e. After adding modify properties in properties window.

f. double click on the button and a new method will be created...in the
method type: close()

22
Creating a Command in AutoCAD with C#

2. In solution explorer double click on the myCommand class

3. With myCommand class opened, now add a new command:


[CommandMethod("FormShow", "_FormShow", CommandFlags.Modal)]
public void frmShow()
{
Document doc = Application.DocumentManager.MdiActiveDocument;
Hello frm = new Hello();
Application.ShowModalDialog(Application.MainWindow.Handle, frm);
}
Debug and Netload, then run the command, this displays the dialog...

Move the dialog, close it and run the command again...

The previous command created a Modeless dialog, change the command to:

Application.ShowModalDialog(Application.MainWindow.Handle, frm);

4. Use a LispFunction to display the dialog...

a. Add a Label to the dialog...

b. Add the following LispFunction to myCommands.cs


[LispFunction("displayForm")]
public object displayForm(ResultBuffer args)
{
Object ret = 0;
if (args != null)
{ Change Modifiers
TypedValue[] typeVal; to Public...
typeVal = args.AsArray();
ret = typeVal[0].Value;

Hello frm = new Hello();


frm.label1.Text = typeVal[0].Value.ToString();
Application.ShowModelessDialog(Application.MainWindow.Handle, frm);
}
return ret;
}

23
Creating a Command in AutoCAD with C#

Create initialization code for command line prompts, splash screen, or other
initial settings required on loading

The Autodesk Runtime IExtensionApplication Interface is used to do one time initialization when the
plugin application is loaded. This is where you would do command line initialization of your application
and display a splash screen.

1. In the plugin that was created with the AutoCAD plugin wizard a class named
myPlugin.cs was created when the project was created. Go to the Solution
Explorer and double-click on that class to open it.

2. Inside the IExtensionApplication.Initialize method add the following code:


Document doc = Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = doc.Editor;
ed.WriteMessage("\r\nThis is an Initialization Startup text.");

This code will print the TEXT to the command line when the application is loaded, build and debug to test
this code.

3. Add this code:


string assyPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
ed.WriteMessage( "\r\nAU 2012 Class CP2767-L");
ed.WriteMessage( "\r\nLocation: " + assyPath);

This Will display the location path of the application, there are several properties available that could be
displayed on initialization as well as start up instructions.

4. To create a Splash screen we Add a new form like we did above for displaying a
dialog.

5. In Solution Explorer right-click on the project


a. select Add on the context menu...

b. select New Item...

24
Creating a Command in AutoCAD with C#

c. select Windows Form and name the form in text box...

Name the Form in Lower left


corner of the Add New Item
dialog. Then Click Add...

6. A new form is created that we will use for the splash screen. In the new forms
properties change the border style to NONE.

This will turn off the title and all of the buttons,
leaving an empty container.

7. Set the BackGround image in properties to an image.

Click then select Local Resource,


then Import a local Image...

25
Creating a Command in AutoCAD with C#

8. Add the following code to in the IExtensionApplication.Initialize method of the


myPlugin class:
splash ss = new splash();
ss.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
ss.TopMost = true;
ss.Opacity = 0.8;

Application.ShowModelessDialog(Application.MainWindow.Handle, ss, false);



// Pause to display splash screen
System.Threading.Thread.Sleep(3000);

//Close splash screen
ss.Close();

This will display the splash screen in the center of the screen for a few seconds when the Application is
loaded.

Thanks for Attending...


26

You might also like