creating a command in autocad® with vb -...

26
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]

Upload: nguyenhuong

Post on 01-Feb-2018

245 views

Category:

Documents


0 download

TRANSCRIPT

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  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 VB.NET

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 Basic Language...

Creating a Command in AutoCAD® with VB.NET

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 VB.NET

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 VB.NET

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 VB.NET

6

On the properties page select the References Tab...

The References for AutoCAD® need to be added.

Note that currently the only References are the .NET System References...

To ADD references, select the Add button...

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...

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 VB.NET

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...

9. The next step is to add Imports 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 VB.NET

8

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...

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 VB.NET

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 VB.NET

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 VB.NET

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 VB.NET

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 VB.NET

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 VB plug-in template...

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

Creating a Command in AutoCAD® with VB.NET

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 VB.NET

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 VB.NET

16

LispFunction attribute properties and Constructor overrides:

Command Flags:

Creating a Command in AutoCAD® with VB.NET

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.vb)...

3. Scroll to the bottom of the MyCommands.vb file and before the ‘End Class’ line add the following command...

               <CommandMethod("FirstGroup",  "_FirstCommand",  CommandFlags.Modal)>  _                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.DocumentExtensionNote: Adding these namespaces will allow Adding a document to the collection...

Creating a Command in AutoCAD® with VB.NET

18

Double-Click with left mouse button to open the file

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

               <CommandMethod("sessionGroup",  "_sessionCommand",                                                                            CommandFlags.Modal  +  CommandFlags.Session)>  _                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

Creating a Command in AutoCAD® with VB.NET

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("undefinedGroup",  "_undefinedCommand",                                                                CommandFlags.Modal  +    CommandFlags.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®...

               <CommandMethod("getEntity",  "_getEntity",  CommandFlags.Modal)>  _                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

Creating a Command in AutoCAD® with VB.NET

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  Function  getCircumference(ByVal  args  As  ResultBuffer)                        Dim  ret  As  Object  =  0                        If  (args  <>  Nothing)  Then                                Dim  typeVal()  As  TypedValue                                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

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

               <LispFunction("returnList")>  _                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

Creating a Command in AutoCAD® with VB.NET

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 VB.NET

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  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

               <LispFunction("displayForm")>  _                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

Creating a Command in AutoCAD® with VB.NET

23

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...

Creating a Command in AutoCAD® with VB.NET

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 VB.NET

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:

                       '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...

Creating a Command in AutoCAD® with VB.NET

26