Creating a Command in AutoCAD® with VB.NET. James E. Johnson – Synergis
Software. CP2767-L This hands-on lab will show you how to create a new ...
Creating a Command in AutoCAD® with VB.NET James E. Johnson – Synergis Software
CP2767-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 VB.NET
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 VB.NET
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 Basic Language...
3
Creating a Command in AutoCAD® with VB.NET
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 VB.NET
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 VB.NET
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 .
On the properties page select the References Tab...
To ADD references, select the Add button...
The References for AutoCAD® need to be added. Note that currently the only References are the .NET System References...
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 VB.NET
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...
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 the Debug Tab...
Select Start External Program...
Select the ‘...’ button to browse to the location of the AutoCAD® executable file ‘acad.exe’...
7
Creating a Command in AutoCAD® with VB.NET
9. The next step is to add Imports statements to add references to the namespaces we will be using... Open the Class1.vb 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 VB.NET
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 VB.NET
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 VB.NET
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 VB.NET
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 VB.NET
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 VB.NET
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 VB 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 VB.NET
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 VB.NET
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 VB.NET
LispFunction attribute properties and Constructor overrides:
Command Flags:
17
Creating a Command in AutoCAD® with VB.NET
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.vb)...
Double-Click with left mouse button to open the file
3. Scroll to the bottom of the MyCommands.vb file and before the ‘End Class’ line add the following command... _
Public Sub fCommand() Dim doc As Document = Application.DocumentManager.MdiActiveDocument Dim db As Database = doc.Database Dim ed As Editor = doc.Editor ed.WriteMessage("Writing message to he command line...") End Sub 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.
4. Next we will looks at the Session Flag... Scroll to top of MyCommands.vb class file and add the additional Imports... Imports Autodesk.AutoCAD.ApplicationServices.DocumentCollectionExtension Imports Autodesk.AutoCAD.ApplicationServices.DocumentExtension Note: Adding these namespaces will allow Adding a document to the collection...
18
Creating a Command in AutoCAD® with VB.NET
Scroll back to bottom and add the new command (debug/Netload)... _ Public Sub sessionCommand() Dim ed As Editor = Application.DocumentManager.MdiActiveDocument.Editor Try Dim curDoc As Document = Application.DocumentManager.MdiActiveDocument Dim doc As Document = Add(Application.DocumentManager, "acad.dwt") Using lockDoc As DocumentLock = doc.LockDocument() Using tr As Transaction = doc.Database.TransactionManager.StartTransaction() ' Open BlockTable Dim blkTbl As BlockTable blkTbl = tr.GetObject(doc.Database.BlockTableId, OpenMode.ForRead) ' Open Modelspace BlockTableRecord for write Dim blkTblRec As BlockTableRecord blkTblRec = tr.GetObject(blkTbl(BlockTableRecord.ModelSpace), OpenMode.ForWrite) ' New circle with a radius of 2 at 10,6 Dim circ As Circle = 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() End Using End Using Catch ex As System.Exception ed.WriteMessage("Exception : " & ex.Message) End Try End Sub
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...
19
Creating a Command in AutoCAD® with VB.NET
5. Add the following Command to Use the Undefined Flag then run debug and Netload the DLL into AutoCAD®...
Undefined Command flag causes command to be loaded as undefined.
_ Public Sub uCommand() Dim doc As Document = Application.DocumentManager.MdiActiveDocument Dim db As Database = doc.Database Dim ed As Editor = doc.Editor ed.WriteMessage("This command is undefined...") End Sub
Notice that the command is undefined in AutoCAD® (Use .undefinedCommand)... 6. Add the following Command for an example of selecting an Entity in AutoCAD®... _
Public Sub getEntityCommand() Dim doc As Document = Application.DocumentManager.MdiActiveDocument Dim db As Database = doc.Database Dim ed As Editor = doc.Editor Dim options As New PromptEntityOptions(vbLf & "Select an entity: ") ' Could set pre filter 'options.SetRejectMessage(vbLf & "Must be a Line...") 'options.AddAllowedClass(GetType(Line), True) Dim selectRes As PromptEntityResult selectRes = ed.GetEntity(options) If (selectRes.Status = PromptStatus.OK) Then Using tr As Transaction = HostApplicationServices.WorkingDatabase _ .TransactionManager _ .StartTransaction() Dim dbObj As DBObject dbObj = tr.GetObject(selectRes.ObjectId, OpenMode.ForRead) ed.WriteMessage(vbLf & "Entity selected was a " & dbObj.GetRXClass.Name) End Using Else ed.WriteMessage("Nothing selected...\n") End If End Sub Use the Runtime RX Class to get Name property of the Database object.
20
Creating a Command in AutoCAD® with VB.NET
7. Use LispFunction Attribute to add an AutoLisp function, this simple example takes an argument for the diameter and returns the circumference... _
Public Function getCircumference(ByVal args As ResultBuffer) Dim ret As Object = 0 If (args Nothing) Then Arguments are passed in as Dim typeVal() As TypedValue a ResultBuffer typeVal = args.AsArray() ret = (Convert.ToDouble(typeVal(0).Value) * Math.PI) ' Type value should be type tested 'If (typeVal(0).TypeCode = LispDataType.Int16) Then 'DoSomething 'ElseIf (typeVal(0).TypeCode = LispDataType.Int32) Then 'DoSomething 'ElseIf (typeVal(0).TypeCode = LispDataType.Double) Then 'DoSomething 'End If End If Return ret End Function
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...
8. Use LispFunction to Return an AutoLisp LIST... _
Public Function returnList(ByVal resBufIn As ResultBuffer) As ResultBuffer ' Create ResultBuffer Dim resBufOut As ResultBuffer = New ResultBuffer() resBufOut.Add(New TypedValue(LispDataType.Text, "XXX")) resBufOut.Add(New TypedValue(LispDataType.ListBegin)) resBufOut.Add(New TypedValue(LispDataType.Text, "YYY 1")) resBufOut.Add(New TypedValue(LispDataType.Text, "YYY 2")) resBufOut.Add(New TypedValue(LispDataType.ListEnd)) resBufOut.Add(New TypedValue(LispDataType.Text, "ZZZ")) Return resBufOut End Function 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 VB.NET
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 VB.NET
2. In solution explorer double click on the myCommand class 3. With myCommand class opened, now add a new command: _
Public Sub frmShow() Dim doc As Document = Application.DocumentManager.MdiActiveDocument Dim frm As New Hello Application.ShowModalDialog(Application.MainWindow.Handle, frm) End Sub
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.vb _
Public Function displayForm(ByVal args As ResultBuffer) Dim ret As Object = 0 If (args Nothing) Then Dim typeVal() As TypedValue typeVal = args.AsArray() Dim frm As New Hello frm.Label1.Text = typeVal(0).Value.ToString() Application.ShowModelessDialog(Application.MainWindow.Handle, frm) End If Return ret End Function
23
Creating a Command in AutoCAD® with VB.NET
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.vb 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:
Dim doc As Document = Application.DocumentManager.MdiActiveDocument Dim db As Database = doc.Database Dim ed As Editor = doc.Editor ed.WriteMessage("This 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: Dim assyPath As String = System.Reflection.Assembly.GetExecutingAssembly().Location ed.WriteMessage("Location: " & 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 VB.NET
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 VB.NET
8. Add the following code to in the IExtensionApplication.Initialize method of the myPlugin class: 'Do splash screen Dim ss As 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(4000) ' 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