creating a command in autocad® with...
TRANSCRIPT
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 ObjectivesAt 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 SpeakerJames 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]
Getting Started with .NET and AutoCAD® plugin developmentTo 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...
Creating a Command in AutoCAD® with C#
2
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...
Creating a Command in AutoCAD® with C#
3
4. At the Bottom of the New Project dialog enter the name of the project..
We have an empty Class Library project started (now to turn it into an AutoCAD® plugin)...
Creating a Command in AutoCAD® with C#
4
The project is started with an empty class file named Class1 with a Class1 defined and has basic .NET required references.
Use the Browse button on right side to browse to a folder for saving the project...
Then select OK button on right side...
5. Under the Visual Studio menu ‘Project’ select the projects properties
Creating a Command in AutoCAD® with C#
5
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...
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 DLL’s .
That opens the Add Reference Dialog...
Creating a Command in AutoCAD® with C#
6
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...
Or on References, Right-Click, select the Add Reference...
Or in the Solution Explorer, Right-Click on the project. select Add Reference...
Select the Project Menu, then select AddReference...
7. After adding the References to AcCoreMgd.dll, AcDbMgd.dll and AcMgd.dll we need to adjust the setting for the DLL’s to be copied local to False...
When the AutoCAD® References are added they are set to be copied local with the project, this needs to be changed to False...
8. Setup For Debugging...
Creating a Command in AutoCAD® with C#
7
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
On the properties page select the Debug Tab...
Select the ‘...’ button to browse to the location of the AutoCAD® executable file ‘acad.exe’...
Select Start External Program...
To select the three References we added hold down the Shift key and select the references with mouse Left-Click...
9. The next step is to add Using statements to add references to the namespaces we will be using...
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.
Creating a Command in AutoCAD® with C#
8
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...
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.
12. Save the Project
Creating a Command in AutoCAD® with C#
9
Use the CommandMethod with a global name to add a command.
There are additional options we will use later...
Use Save All to save the project and all files...
The next step is to build, A build will also save the project...
13. The project needs to be built...
OR:
After Build:
Creating a Command in AutoCAD® with C#
10
In the Solution Explorer. Right -click on the project to show the context menu...
.....Select 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...
.....From the Build Menu Select Build Solution or use the Function key F6
14. Configuration...
Setting the Platform to Any CPU will allow your project to run on both 32 and 64 bit systems...
Creating a Command in AutoCAD® with C#
11
For debugging the configuration should be set to Debug...
Change to Release for deploying...
Check Project property settings after setting configuration to Release...
15. Test the command, Start a Session of AutoCAD® for debug...
Or Click Toolbar button:
16. At AutoCAD® Command line type the Command ‘Netload’
Creating a Command in AutoCAD® with C#
12
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®...
Browse to the Compiled DLL for the project and click the Open button...
17. Issue the command (our example is MyCommand)
18. To Debug...
Creating a Command in AutoCAD® with C#
13
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..
This simple command only displays an Alert box in AutoCAD®...
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...
Creating a Command in AutoCAD® with C#
14
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®...
Creating a Command in AutoCAD® with C#
15
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:
Creating a Command in AutoCAD® with C#
16
LispFunction attribute properties and Constructor overrides:
Command Flags:
Creating a Command in AutoCAD® with C#
17
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)...
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.
Creating a Command in AutoCAD® with C#
18
Double-Click with left mouse button to open the file
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(); circ.SetDatabaseDefaults(); circ.Center = new Point3d(10, 6, 0); circ.Radius = 2;
// Add circle to ModelSpace and the transaction blkTblRec.AppendEntity(circ); tr.AddNewlyCreatedDBObject(circ, true);
// Commit circle to the database tr.Commit(); } }
} catch (System.Exception ex) { ed.WriteMessage("Exception : " + ex.Message); } }
Creating a Command in AutoCAD® with C#
19
Notes:
1. The session flag cause the command to run in Application context.
2. Locking the document is required when running in session context.
3. The Using statement does cleanup when exited.
4. Try/Catch is used in case of errors.
5. Notice the + used to add multiple flags...
5. Add the following Command to Use the Undefined Flag then run debug and Netload the DLL into 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"); } }
Creating a Command in AutoCAD® with C#
20
Undefined Command flag causes command to be loaded as undefined.
Use the Runtime RX Class to get Name property of the Database object.
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; if (args != null) { 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) //{ // //DoSomething //} } return ret; }
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; }
Creating a Command in AutoCAD® with C#
21
Arguments are passed in as a ResultBuffer
Run debug and Netload the DLL, then type the following Lisp expression at the AutoCAD® command line:
(setq circ (getcircumference 10.0))
The return value should be 34.159 and the variable ‘circ’ is set to that value...
Run debug and Netload the DLL, then type the following Lisp expression at the AutoCAD command line: (setq myList (returnlist))
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...
d. This creates the form, now use toolbox and add a button...
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()
Creating a Command in AutoCAD® with C#
22
Name the Form in Lower left corner of the Add New Item dialog. Then Click Add...
Drop the Button onto the form...
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) { TypedValue[] typeVal; 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; }
Creating a Command in AutoCAD® with C#
23
Change Modifiers to Public...
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...
Creating a Command in AutoCAD® with C#
24
c. select Windows Form and name the form in text box...
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.
Creating a Command in AutoCAD® with C#
25
Click then select Local Resource, then Import a local Image...
Name the Form in Lower left corner of the Add New Item dialog. Then Click Add...
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...
Creating a Command in AutoCAD® with C#
26