an overview of vba in autocad® 2006 · an overview of vba in autocad® 2006 cp22-2 this course...

18
Walt Disney World Swan and Dolphin Resort Orlando, Florida 11/29/2005 - 5:00 pm - 6:30 pm Room:Swan 2 (Swan) An Overview of VBA in AutoCAD® 2006 This course presents an overview of how VBA fits into the customization scheme in AutoCAD 2006. CP22-2 About the Speaker: Phil Kreiker - Looking Glass Microproducts Phil is CTO at Looking Glass Microproducts, an Autodesk Registered Developer, where he is responsible for AutoCAD training, customization, and support. He has designed and programmed computers since 1963 and has used AutoCAD since 1984. Phil taught AutoCAD at the Colorado School of Mines from 1998 to 2003. He wrote the “CAD Cookbook” column for 10 years for CADalyst, and was technical editor-at-large for CADENCE magazine from 1996 to 1997. He is the author of several books including his latest Visual LISP: A Guide to Artful Programming which is part of the Programmer’s Series from Autodesk Press. Phil received his Bachelor of Engineering degree from Cooper Union for the Advancement of Science and Art and his M.S. degree from Lowell Technological Institute. [email protected]

Upload: others

Post on 24-Mar-2020

48 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: An Overview of VBA in AutoCAD® 2006 · An Overview of VBA in AutoCAD® 2006 CP22-2 This course presents an overview of how VBA fits into the customization scheme in AutoCAD 2006

Walt Disney World Swan and Dolphin ResortOrlando, Florida

11/29/2005 - 5:00 pm - 6:30 pm Room:Swan 2 (Swan)

An Overview of VBA in AutoCAD® 2006

This course presents an overview of how VBA fits into the customization scheme in AutoCAD 2006.CP22-2

About the Speaker:

Phil Kreiker - Looking Glass Microproducts

Phil is CTO at Looking Glass Microproducts, an Autodesk Registered Developer, where he is responsible for AutoCAD training, customization, and support. He has designed and programmed computers since 1963 and has used AutoCAD since 1984. Phil taught AutoCAD at the Colorado School of Mines from 1998 to 2003. He wrote the “CAD Cookbook” column for 10 years for CADalyst, and was technical editor-at-large for CADENCE magazine from 1996 to 1997. He is the author of several books including his latest Visual LISP: A Guide to Artful Programming which is part of the Programmer’s Series from Autodesk Press. Phil received his Bachelor of Engineering degree from Cooper Union for the Advancement of Science and Art and his M.S. degree from Lowell Technological [email protected]

Page 2: An Overview of VBA in AutoCAD® 2006 · An Overview of VBA in AutoCAD® 2006 CP22-2 This course presents an overview of how VBA fits into the customization scheme in AutoCAD 2006
Page 3: An Overview of VBA in AutoCAD® 2006 · An Overview of VBA in AutoCAD® 2006 CP22-2 This course presents an overview of how VBA fits into the customization scheme in AutoCAD 2006

An Overview of VBA in AutoCAD® 2006

2

Introduction This course presents an overview of how VBA fits into the customization scheme in AutoCAD 2006. We’ll be covering the following topics:

• A Brief History of Visual Basic

• Command Line Programs vs. GUI Programs

• Comparison of Visual LISP, VBA, C++

• The Strengths and Weaknesses of each vis à vis AutoCAD

• Interfacing with AutoCAD

• Graphic User Interface (GUI)

• Reactors

• ActiveX Automation

• Recommendations

A Brief History of Visual Basic With command line programs, the program dictates the order of the user’s actions. Despite the graphics screen, AutoCAD started out as a Command Line program. In may respects, it still is:

Command: -block Enter block name or [?]: mental Specify insertion base point: Select objects:

Page 4: An Overview of VBA in AutoCAD® 2006 · An Overview of VBA in AutoCAD® 2006 CP22-2 This course presents an overview of how VBA fits into the customization scheme in AutoCAD 2006

An Overview of VBA in AutoCAD® 2006

3

GUI programs are event-driven programs. The user determines the next program action by triggering a specific event:

• Click

• Keypress

• BeginCommand

• EndSave

Although the command line is still present (when you want it) in AutoCAD 2006, AutoCAD 2006 is now, for the most part, a GUI program.

Before Visual Basic (1991-), you had to know C++ and you had to know the Windows API. Only the truly dedicated and skilled (geeks) could attempt to write Windows Programs.

With Visual Basic (1999+), you draw your own User Interface (UI), you add the code to react to events, you concentrate on the problem at hand, and you don’t have to be a (major) geek to do it.

There are probably more lines of production code written in Visual Basic than in any other language.

Page 5: An Overview of VBA in AutoCAD® 2006 · An Overview of VBA in AutoCAD® 2006 CP22-2 This course presents an overview of how VBA fits into the customization scheme in AutoCAD 2006

An Overview of VBA in AutoCAD® 2006

4

Comparison of Visual LISP, VBA, C++ How does VBA stack up against the other major AutoCAD programming languages? Let’s take a look at the following table:

Visual LISP VBA VB C++

GUI Cryptic Easy Easy Difficult

Who Drives? AutoCAD AutoCAD VB AutoCAD or C++

Event Driven Cryptic Easy Moderate Difficult

ActiveX Automation

Cryptic Easy Easy Easy

Development Environment

Included in AutoCAD

Included in AutoCAD

$1,079.00 $1,079.00

Skill Transfer Virtually None ActiveX ActiveX & Standalone

The World

Modal Dialog Box Modal dialog boxes halt their calling programs until you tell them to continue; e.g., OK, Cancel.

Let’s take a look at a simple modal dialog box as implemented in both Visual LISP and VBA. First Visual LISP:

// hello.dcl hello : dialog { label = "Sample Dialog Box"; : text { label = "Hello, world"; } : button { key = "accept"; label = " OK "; is_default = true; fixed_width = true; alignment = centered; is_cancel = true; } }

You define your dialog box with a DCL (Dialog Control Language) file.

For you historical buffs, DCL was invented by Autodesk, as part of the Prometheous project, to deal with the problem of defining dialog boxes for diverse platforms (Windows, DOS, Sun, etc.). For you mythology buffs, Proteus was an ancient sea-god and the herdsman of Poseidon's seals. Like the other sea-gods, he had the gift of prophecy and the ability to change his shape at will.

Page 6: An Overview of VBA in AutoCAD® 2006 · An Overview of VBA in AutoCAD® 2006 CP22-2 This course presents an overview of how VBA fits into the customization scheme in AutoCAD 2006

An Overview of VBA in AutoCAD® 2006

5

Now that the DCL file is defined, you can evoke it with the following code:

;;; Hello.lsp (defun C:HELLO (/ dcl_id) (setq dcl_id (load_dialog "hello.dcl")) (if (not (new_dialog "hello" dcl_id)) (exit) ) (start_dialog) (unload_dialog dcl_id) (princ) )

Now let’s see what it takes to do the same thing with VBA:

Page 7: An Overview of VBA in AutoCAD® 2006 · An Overview of VBA in AutoCAD® 2006 CP22-2 This course presents an overview of how VBA fits into the customization scheme in AutoCAD 2006

An Overview of VBA in AutoCAD® 2006

6

With VBA, you define your dialog box by dragging, dropping, and editing controls from our toolbox. In addition to the tools shown above, (Label, TextBox, ComboBox, ListBox, CheckBox, OptionButton, ToggleButton, Frame, CommandButton, TabStrip, MultiPage, ScrollBar, SpinButton and Image), there are over 300 sets of additional controls on my computer. I don’t know how many there are on yours. In addition, if you need a specialized control that you don’t have, you can buy third-party controls, or roll your own with C++.

Page 8: An Overview of VBA in AutoCAD® 2006 · An Overview of VBA in AutoCAD® 2006 CP22-2 This course presents an overview of how VBA fits into the customization scheme in AutoCAD 2006

An Overview of VBA in AutoCAD® 2006

7

You can define the look and feel of our form and each of its controls with the properties window.

As for the code, it practically writes itself.

In Userform1

In Module1

Non-Modal Dialog Boxes You're probably familiar with modal dialog boxes. They make you dismiss them before returning control to the calling program. Non-modal dialog boxes return control to their calling programs, and hang around until you dismiss them. You can't do this in Visual LISP, but you can in VBA.

Let's define a simple non-modal dialog box that can be used to provide numeric input to the AutoCAD command prompt.

Here are our dialog box and a few of the callback functions associated with it:

'UserForm1 Code Private Sub CommandButton1_Click() ThisDrawing.SendCommand "1" End Sub Private Sub CommandButton2_Click() ThisDrawing.SendCommand "2" End Sub … Private Sub CommandButton17_Click() ThisDrawing.SendCommand vbCr End Sub

Page 9: An Overview of VBA in AutoCAD® 2006 · An Overview of VBA in AutoCAD® 2006 CP22-2 This course presents an overview of how VBA fits into the customization scheme in AutoCAD 2006

An Overview of VBA in AutoCAD® 2006

8

With each button click, we merely stuff the appropriate string down the AutoCAD command throat.

The default for a Command button is to take focus when you click on it. You don't want this here, so you just disable it in its properties. You'll find it useful to create one control, set its properties, and paste it multiple times.

To keep things clean when we close all the open drawings, we add the following:

AcadDocument Code Private Sub AcadDocument_BeginClose() If Application.Documents.Count() <= 1 Then Unload UserForm1 End If End Sub

To fire it up, we create a module, and add the following code:

'Module1 Code Public Sub ShowTenKey() UserForm1.Show vbModeless End Sub

You're not quite done. Modeless dialog boxes do not work correctly until you include an 'AutoCAD Focus Control for VBA Type Library' on your form. This control installs with all supported versions of AutoCAD. Here's how you use it:

You select Tools… References… and enable the control from the available references

Next, you add the control to your toolbox.

Select Tools… Additional Controls, and enable the AcFocusCtrl control to appear on the Toolbox. The new control is the one with the blue bar on the Toolbox.

Page 10: An Overview of VBA in AutoCAD® 2006 · An Overview of VBA in AutoCAD® 2006 CP22-2 This course presents an overview of how VBA fits into the customization scheme in AutoCAD 2006

An Overview of VBA in AutoCAD® 2006

9

You add the control to your form, and sweep it under the carpet.

There's one more thing you'll want to do. To prevent your visible command buttons from showing focus, add the following sub to your form:

Private Sub UserForm_Activate()

AcFocusCtrl1.SetFocus

End Sub

Page 11: An Overview of VBA in AutoCAD® 2006 · An Overview of VBA in AutoCAD® 2006 CP22-2 This course presents an overview of how VBA fits into the customization scheme in AutoCAD 2006

An Overview of VBA in AutoCAD® 2006

10

Reactors Reactors allow your program to respond (react) to selected user-driven events. In effect, this makes AutoCAD your GUI, and lets you insinuate yourself into the AutoCAD experience.

Here are the VBA reactors, there are corresponding Visual LISP reactors

Reactor Event

Activate After a document window is activated.

AppActivate Before the main application window is activated.

AppDeactivate Before the main application window is deactivated.

ARXLoaded After an ObjectARX application has been loaded.

ARXUnloaded After an ObjectARX application has been unloaded.

BeginClose After AutoCAD receives a request to close a drawing.

BeginCommand After a command is issued, but before it completes.

BeginDocClose After AutoCAD receives a request to close a drawing.

BeginDoubleClick After the user double-clicks an object in the drawing.

BeginFileDrop After a file is dropped on the main application window.

BeginLISP After AutoCAD receives a request to evaluate a LISP expression.

BeginModal Before a modal dialog is displayed.

BeginOpen After AutoCAD receives a request to open an existing drawing.

BeginPlot After AutoCAD receives a request to print a drawing.

BeginQuit Before an AutoCAD session ends or a document closes.

BeginRightClick After the user right-clicks on the drawing window.

BeginSave After AutoCAD receives a request to save the drawing.

BeginShortcutMenuCommand After the user right-clicks on the drawing window, and before the shortcut menu appears in command mode.

BeginShortcutMenuDefault After the user right-clicks on the drawing window, and before the shortcut menu appears in default mode.

BeginShortcutMenuEdit After the user right-clicks on the drawing window, and before the shortcut menu appears in edit mode.

BeginShortcutMenuGrip After the user right-clicks on the drawing window, and before the shortcut menu appears in grip mode.

BeginShortcutMenuOSnap After the user right-clicks on the drawing window, and before the shortcut menu appears in osnap mode.

Deactivate After the drawing window is deactivated.

EndCommand After a command completes.

EndLISP After evaluating a LISP expression.

Page 12: An Overview of VBA in AutoCAD® 2006 · An Overview of VBA in AutoCAD® 2006 CP22-2 This course presents an overview of how VBA fits into the customization scheme in AutoCAD 2006

An Overview of VBA in AutoCAD® 2006

11

EndModal After a modal dialog is dismissed.

EndOpen After AutoCAD finishes opening an existing drawing.

EndPlot After a document has been sent to the printer.

EndSave After AutoCAD has finished saving the drawing.

EndShortcutMenu After the shortcut menu appears.

LayoutSwitched After the user switches to a different layout.

LISPCancelled After the evaluation of a LISP expression is cancelled.

Modified After an object or collection in the drawing has been modified.

NewDrawing Before a new drawing is created.

ObjectAdded After an object has been added to the drawing.

ObjectErased After an object has been erased from the drawing.

ObjectModified After an object in the drawing has been modified.

SelectionChanged After the current pickfirst selection set changes.

SysVarChanged After the value of a system variable is changed.

WindowChanged After there is a change to the application or document windows.

WindowMovedOrResized After the application or drawing window has been moved or resized.

Visual LISP Example

The following file illustrates Visual LISP Reactors:

;;;---------------------------------------- ;;; File reactors.lsp ;;;---------------------------------------- ;;;---------------------------------------- ;;; Add our reactors to the reactor list ;;;---------------------------------------- (defun AddReactors (appname / editor-reactor-var reactor-list) (setq reactor-list (list (cons :vlr-commandWillStart (read (strcat appname "-commandWillStart"))) (cons :vlr-commandEnded (read (strcat appname "-commandEnded"))) ) ) (setq editor-reactor-var (read (strcat appname "-EDITOR-REACTOR"))) (if (and reactor-list (not (vl-symbol-value editor-reactor-var))) (set editor-reactor-var (vlr-editor-reactor appname reactor-list)) ) ) ;;;---------------------------------------- ;;; Remove our reactors from the reactor list ;;;---------------------------------------- (defun RemoveReactors (appname / editor-reactor mouse-reactor temp) (setq editor-reactor (read (strcat appname "-EDITOR-REACTOR"))) (if (setq temp (vl-symbol-value editor-reactor)) (progn (vlr-remove temp) (set editor-reactor nil)) )

Page 13: An Overview of VBA in AutoCAD® 2006 · An Overview of VBA in AutoCAD® 2006 CP22-2 This course presents an overview of how VBA fits into the customization scheme in AutoCAD 2006

An Overview of VBA in AutoCAD® 2006

12

(setq mouse-reactor (read (strcat appname "-MOUSE-REACTOR"))) (if (setq temp (vl-symbol-value mouse-reactor)) (progn (vlr-remove temp) (set mouse-reactor nil)) ) ) ;;;---------------------------------------- ;;; Command Will Start Reactor ;;;---------------------------------------- (defun AU2005-commandWillStart (reactor command-list) (alert (strcat "commandWillStart: " (car command-list))) (princ) ) ;;;---------------------------------------- ;;; Command Ended Reactor ;;;---------------------------------------- (defun AU2005-commandEnded (reactor command-list) (alert (strcat "commandEnded: " (car command-list))) (princ) ) ;;;---------------------------------------- ;;; Command Ended Reactor ;;;---------------------------------------- (setq appname "AU2005") (AddReactors appname)

In this file, we've defined functions that add and remove our reactors, a pair of reactors for commandStarted and commandEnded. AddReactors may be generalized for any number of reactors to be added to the reactor list.

At the end of the file, we've defined our application name and added our reactors.

After loading our file, here's what we'll see:

VBA Reactors

With VBA, you simply select the event for which you wish a reactor, and VBA constructs a reactor subroutine for you. You fill in the code, and VBA and deals with connecting and disconnecting the reactors.

Page 14: An Overview of VBA in AutoCAD® 2006 · An Overview of VBA in AutoCAD® 2006 CP22-2 This course presents an overview of how VBA fits into the customization scheme in AutoCAD 2006

An Overview of VBA in AutoCAD® 2006

13

Return to AutoCAD, call up the line command, and here's what you'll see:

ActiveX Automation ActiveX Automation is a Microsoft standard for interaction between Windows programs. It enables one application to use the functions of another application such that

• The two applications appear to be a single program, or

• One application seems to have the capabilities of the other.

With ActiveX Automation, we can have an Excel spreadsheet create, access, and/or modify an AutoCAD drawing, and we can have an AutoCAD drawing create, access, and/or modify an Excel spreadsheet.

Most importantly, a Visual LISP or VBA or VB application can access AutoCAD. With ActiveX Automation, you can write programs that

• Are faster than using the AutoCAD command throat.

• Are faster than using entmake, entget, and entmod.

• Can directly access almost every aspect of AutoCAD.

Page 15: An Overview of VBA in AutoCAD® 2006 · An Overview of VBA in AutoCAD® 2006 CP22-2 This course presents an overview of how VBA fits into the customization scheme in AutoCAD 2006

An Overview of VBA in AutoCAD® 2006

14

• Can do much more than Visual LISP alone.

Here’s a small section of the AutoCAD ActiveX Automation object model:

From this abbreviated model, we can see that the Application object (AutoCAD) is at the top of the model. The Application contains a Documents collection. The Documents collection contains Documents. Each document contains a Blocks collection, a ModelSpace collection, and a PaperSpace Collections. Each of these collections consists of graphical objects such as lines, circles, arcs, etc.

What we have here is a collection of containers and the objects that go in them. While the concept may be strange to you, it’s fairly easy to come to grips with.

Let’s draw a circle with Visual LISP and ActiveX Automation:

((vl-load-com) (defun DrawCircle (/ circleObj centerPoint radius) (setq centerPoint '(2.0 3.0 0.0)) (setq radius 1.0) (setq circleObj (vla-AddCircle (vla-get-ModelSpace (vla-get-ActiveDocument (vlax-get-acad-object) ) ) (vlax-3D-Point centerPoint) radius ) ) (vla-zoomextents (vlax-get-acad-object)) )

Now let’s do it with VBA:

Page 16: An Overview of VBA in AutoCAD® 2006 · An Overview of VBA in AutoCAD® 2006 CP22-2 This course presents an overview of how VBA fits into the customization scheme in AutoCAD 2006

An Overview of VBA in AutoCAD® 2006

15

Sub DrawCircle() Dim circObj As AcadCircle Dim ctrPnt(0 To 2) As Double Dim rad As Double ctrPnt(0) = 2# ctrPnt(1) = 3# ctrPnt(2) = 0# rad = 1# Set circObj = ThisDrawing.ModelSpace.AddCircle(ctrPnt, rad) ZoomExtents End Sub

Development Environment AutoCAD provides development environments for both Visual LISP and VBA. The development environments for VB and C++ are part of Microsoft Visual Studio.

The VBA IDE offers the following options:

• Auto Syntax Check

• Require Explicit Variable Declaration

• Auto List members

• Auto Quick Info

• Auto Data Tips

• Auto Indent

• Object Browser

The Visual LISP IDE offers none of these.

Performance The following graph was prepared by Autodesk, and illustrates the comparative performance for ObjectARX, VBA, Visual LISP, and VB for manipulating an AutoCAD database:

Page 17: An Overview of VBA in AutoCAD® 2006 · An Overview of VBA in AutoCAD® 2006 CP22-2 This course presents an overview of how VBA fits into the customization scheme in AutoCAD 2006

An Overview of VBA in AutoCAD® 2006

16

CO

M (V

B)

LISP

CO

M (V

BA

)

Obj

ectA

RX

Create 1000 Circles

Create 1000 lines

Update 1000 Circles

Add XData to 1000 Entities

Create 1000 2dPolylines

Total

0.00

10.00

20.00

30.00

40.00

50.00

60.00

70.00

80.00

90.00

100.00

Seco

nds

AutoCAD's APIs

While VBA isn't as fast as Object, it's a close second.

Skills Transfer While Visual LISP is an extremely powerful platform for developing AutoCAD applications (it was the first), there’s not much call for LISP programmers out there.

As much as I like Visual LISP, it’s pretty much a dead end when it comes to skills transfer. In addition, if you avoid Visual LISP, there’s more work for me.

The skills you acquire using VBA, on the other hand, can be used with any application that supports VBA and/or ActiveX Automation. Microsoft Word, PowerPoint, Access, and Excel come to mind.

These skills are transferable to both VB and to C++, although admittedly, C++ will be a more intense transformation.

Recommendations If you have an application in Visual LISP, leave it there. Although porting between Visual LISP and VBA is fairly easy, why spend time reinventing the wheel? You might consider using VBA for dialog and message boxes; Visual LISP can call VBA and vice versa.

If you’re looking at a new application, consider moving to VBA. It’s vastly superior user interface and IDE will more than compensate for the learning curve.

Page 18: An Overview of VBA in AutoCAD® 2006 · An Overview of VBA in AutoCAD® 2006 CP22-2 This course presents an overview of how VBA fits into the customization scheme in AutoCAD 2006