Autocad 2004 ActiveX and VBA Developer - S Guide
Autocad 2004 ActiveX and VBA Developer - S Guide
2004
February 2003
AUTODESK, INC., MAKES NO WARRANTY, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY
IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE REGARDING THESE
MATERIALS, AND MAKES SUCH MATERIALS AVAILABLE SOLELY ON AN "AS-IS" BASIS.
IN NO EVENT SHALL AUTODESK, INC., BE LIABLE TO ANYONE FOR SPECIAL, COLLATERAL, INCIDENTAL,
OR CONSEQUENTIAL DAMAGES IN CONNECTION WITH OR ARISING OUT OF PURCHASE OR USE OF THESE MATERIALS.
THE SOLE AND EXCLUSIVE LIABILITY TO AUTODESK, INC., REGARDLESS OF THE FORM OF ACTION, SHALL NOT
EXCEED THE PURCHASE PRICE OF THE MATERIALS DESCRIBED HEREIN.
Autodesk, Inc., reserves the right to revise and improve its products as it sees fit. This publication describes the state of this product at
the time of its publication, and may not reflect the product at all times in the future.
Autodesk Trademarks
The following are registered trademarks of Autodesk, Inc., in the USA and/or other countries: 3D Props, 3D Studio, 3D Studio MAX, 3D
Studio VIZ, 3DSurfer, ActiveShapes, ActiveShapes (logo), Actrix, ADI, AEC Authority (logo), AEC-X, Animator Pro, Animator Studio, ATC,
AUGI, AutoCAD, AutoCAD LT, AutoCAD Map, Autodesk, Autodesk Inventor, Autodesk (logo), Autodesk MapGuide, Autodesk University
(logo), Autodesk View, Autodesk WalkThrough, Autodesk World, AutoLISP, AutoSketch, Biped, bringing information down to earth, CAD
Overlay, Character Studio, Cinepak, Cinepak (logo), Codec Central, Combustion, Design Your World, Design Your World (logo), Discreet,
EditDV, Education by Design, gmax, Heidi, HOOPS, Hyperwire, i-drop, Inside Track, Kinetix, MaterialSpec, Mechanical Desktop, NAAUG,
ObjectARX, PeopleTracker, Physique, Planix, Powered with Autodesk Technology (logo), RadioRay, Revit, Softdesk, Texture Universe, The
AEC Authority, The Auto Architect, VISION, Visual, Visual Construction, Visual Drainage, Visual Hydro, Visual Landscape, Visual
Roads, Visual Survey, Visual Toolbox, Visual TugBoat, Visual LISP, Volo, WHIP!, and WHIP! (logo).
The following are trademarks of Autodesk, Inc., in the USA and/or other countries: 3ds max, AutoCAD Architectural Desktop, AutoCAD
Learning Assistance, AutoCAD LT Learning Assistance, AutoCAD Simulator, AutoCAD SQL Extension, AutoCAD SQL Interface, Autodesk
Map, Autodesk Streamline, AutoSnap, AutoTrack, Built with ObjectARX (logo), Burn, Buzzsaw, Buzzsaw.com, Cinestream, Cleaner, Cleaner
Central, ClearScale, Colour Warper, Content Explorer, Dancing Baby (image), DesignCenter, Design Doctor, Designer's Toolkit,
DesignProf, DesignServer, Design Web Format, DWF, DWG Linking, DXF, Extending the Design Team, GDX Driver, gmax (logo), gmax
ready (logo),Heads-up Design, IntroDV, jobnet, ObjectDBX, onscreen onair online, Plans & Specs, Plasma, PolarSnap,
ProjectPoint, Reactor, Real-time Roto, Render Queue, Visual Bridge, Visual Syllabus, and Where Design Connects.
GOVERNMENT USE
Use, duplication, or disclosure by the U.S. Government is subject to restrictions as set forth in FAR 12.212 (Commercial Computer
Software- Restricted Rights) and DFAR 227.7202 (Rights in Technical Data and Computer Software), as applicable.
Contents
Introduction .
Chapter 1
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
1
.2
.3
.3
.4
.4
.5
.5
.6
.6
.7
.7
.8
.8
. 11
.
.
.
.
.
.
.
.
12
13
13
14
14
15
15
15
iii
Chapter 2
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
16
16
17
17
18
18
19
19
20
21
22
24
25
25
26
28
29
29
30
. 31
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
32
34
34
35
36
36
38
38
39
39
40
41
41
42
42
43
43
Chapter 3
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
. 44
. 44
. 44
. 45
. 46
. 46
. 47
. 51
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
Contents
v
. 52
. 53
. 54
. 55
. 56
. 56
. 57
. 60
. 61
. 64
. 64
. 65
. 65
. 66
. 66
. 67
. 70
. 71
. 73
. 73
. 74
. 74
. 75
. 76
. 77
. 78
. 78
Chapter 4
Create Objects . . . . . . . . . . . . . .
Determine the Container Object . . . . . . .
Create Lines . . . . . . . . . . . . .
Create Curved Objects . . . . . . . . . .
Create Point Objects . . . . . . . . . . .
Create Solid-Filled Areas . . . . . . . . .
Work with Regions . . . . . . . . . . .
Create Hatches . . . . . . . . . . . .
Work with Selection Sets . . . . . . . . . . .
Create a Selection Set . . . . . . . . . .
Add Objects to a Selection Set . . . . . . . .
Define Rules for Selection Sets . . . . . . . .
Display Information About a Selection Set . . . .
Remove Objects from a Selection Set . . . . .
Edit Objects . . . . . . . . . . . . . . .
Work with Named Objects . . . . . . . . .
Copy Objects . . . . . . . . . . . . .
Offset Objects . . . . . . . . . . . . .
Mirror Objects . . . . . . . . . . . . .
Array Objects . . . . . . . . . . . . .
Move Objects . . . . . . . . . . . . .
Rotate Objects . . . . . . . . . . . . .
Delete Objects . . . . . . . . . . . . .
Scale Objects . . . . . . . . . . . . .
Transform Objects . . . . . . . . . . .
Extend and Trim Objects . . . . . . . . .
Explode Objects . . . . . . . . . . . .
Edit Polylines . . . . . . . . . . . . .
Edit Splines . . . . . . . . . . . . . .
Edit Hatches . . . . . . . . . . . . .
Use Layers, Colors, and Linetypes . . . . . . . .
Work with Layers . . . . . . . . . . . .
Work with Colors. . . . . . . . . . . .
Work with Linetypes. . . . . . . . . . .
Assign Layers, Colors, and Linetypes to Objects . .
Save and Restore Layer Settings . . . . . . . . .
Understand How AutoCAD Saves Layer Settings . .
Use the LayerStateManager to Manage Layer Settings
vi |
Contents
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
. 81
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
82
82
83
83
84
86
87
90
93
94
94
95
102
103
104
104
105
109
110
112
115
116
117
118
119
122
123
124
126
128
132
133
138
139
141
144
144
146
Chapter 5
Dimensioning Concepts . . . . . . . .
Parts of a Dimension . . . . . . .
Define the Dimension System Variables .
Set Dimension Text Styles. . . . . .
Understand Leader Lines . . . . . .
Understand Associative Dimensions . .
Create Dimensions . . . . . . . . . .
Create Linear Dimensions. . . . . .
Create Radial Dimensions . . . . . .
Create Angular Dimensions . . . . .
Create Ordinate Dimensions . . . . .
Edit Dimensions . . . . . . . . . .
Override Dimension Text . . . . . .
Work with Dimension Styles
. . . . . .
Create, Modify, and Copy Dimension Styles
Override the Dimension Style . . . .
Dimension in Model Space and Paper Space . .
Create Leaders and Annotation . . . . . .
Create a Leader Line . . . . . . .
Add the Annotation to a Leader Line . .
Leader Associativity. . . . . . . .
Edit Leader Associativity . . . . . .
Edit Leaders . . . . . . . . . .
Use Geometric Tolerances . . . . . . .
Create Geometric Tolerances . . . . .
Edit Tolerances . . . . . . . . .
Chapter 6
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
. . . .
. . . .
. . . .
. . . .
Characters
. . . .
. . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
. 169
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
150
151
157
161
164
166
166
170
170
171
172
172
173
173
173
174
176
177
179
179
180
181
182
187
187
187
189
189
190
191
191
191
192
. 193
.
.
.
Contents
vii
194
195
196
Chapter 7
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
Use Events .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
196
197
198
198
199
200
200
202
203
203
205
206
209
209
210
212
212
213
215
216
216
218
219
220
221
222
223
223
224
225
227
viii |
Contents
Chapter 8
Chapter 9
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
Chapter 10
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
. 241
.
.
.
.
.
.
.
.
.
.
.
.
.
242
244
245
248
249
249
250
252
253
253
255
255
257
. 261
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
262
262
262
263
263
265
265
267
268
268
272
272
274
274
275
275
276
277
. 279
.
.
.
.
.
280
280
281
282
285
Contents
ix
Chapter 11
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
Contents
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
. . .
. . .
. . .
. . .
. . .
. . .
. . .
. . .
. . .
. . .
. . .
. . .
. . .
. . .
. . .
. . .
Loaded .
. . .
. . .
. . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
286
287
292
299
300
300
301
302
303
304
305
306
307
309
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
310
310
311
312
313
314
315
316
316
317
319
319
319
320
320
320
321
321
322
322
Chapter 12
Chapter 13
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
Index .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
. 323
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
. 331
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
324
324
325
326
326
329
332
332
333
334
334
335
338
339
342
343
344
344
345
348
348
350
. 353
354
. 365
Contents
xi
xii
Introduction
In this chapter
Overview of
AutoCAD ActiveX
Technology
Overview of AutoCAD
VBA Together
How This Guide Is
Organized
Conventions Used in This
Guide
Sample Code
Migrating Automation
Projects
Visual Basic
Java
Delphi
MS Word VBA
AutoCAD VBA
Excel VBA
AutoCAD Application
drawing.dwg
2 |
Introduction
Graphical objects such as lines, arcs, text, and dimensions are objects.
Style settings such as linetypes and dimension styles are objects.
There are three fundamental elements that define ActiveX and VBA
program- ming in AutoCAD. The first is AutoCAD itself, which has a rich set
of objects that encapsulates AutoCAD entities, data, and commands. Because
AutoCAD was designed as an open-architecture application with multiple
levels of interface, familiarity with AutoCAD programmability is highly
desirable in
order to use VBA effectively. If youve used AutoLISP to control AutoCAD
programmatically, you already have a good understanding of the AutoCAD
facilities. However, you will find the VBA object-based approach to be quite
different from that of AutoLISP.
The second element is the AutoCAD ActiveX Automation interface, which
establishes messages (communication) with AutoCAD objects. Programming
in VBA requires a fundamental understanding of ActiveX Automation. A
description of the AutoCAD ActiveX Automation interface can be found in
the ActiveX and VBA Reference. Even the experienced VB programmer will
find the AutoCAD ActiveX Automation interface invaluable for understanding and developing AutoCAD VBA applications.
The third element is the VBA programming environment (IDE) which has its
own set of objects, keywords, constants, and so forth that provides program
flow, control, debugging, and execution. Microsofts own extensive online
Help for VBA is included with the AutoCAD VBA and is accessible from the
VBA IDE by any of the following methods:
Speed
Running in-process with VBA, ActiveX applications are faster than either
AutoLISP or ADS applications.
Ease of Use
The programming language and development environment are easy to
use and come installed with AutoCAD.
Windows Interoperability
ActiveX and VBA are designed to be used with other Windows applications and provide an excellent path for communication of information
across applications.
Rapid Prototyping
The rapid interface development of VBA provides the perfect environment for prototyping applications, even if those applications will
eventually be developed in another language.
Programmer Base
There are millions of Visual Basic programmers around the world.
AutoCAD ActiveX and VBA technology open up AutoCAD
customization and application development to these programmers and
the many more who will learn Visual Basic in the future.
Sample Code
This manual and the ActiveX and VBA Reference together contain over 800
example VBA subroutines that demonstrate the usage of ActiveX methods,
properties, and events.
There are also many sample applications provided in the AutoCAD Sample
directory. These sample applications show a wide range of fuctionality, from
extracting AutoCAD drawing data into Microsoft Excel spreadsheets to drawing and performing stress analysis on an electrical transmission tower.
These samples also show how to combine the versatility of the Visual Basic
for Applications programming environment with the power of the AutoCAD
ActiveX interface to create customized applications.
Additionally, example code in the ActiveX and VBA Developers Guide and
ActiveX and VBA Reference can be copied from the Help files, pasted directly
into the AutoCAD VBA environment, and then executed with one requirement: the current active drawing in AutoCAD must be a blank drawing
open to model space.
To run the examples from the Help files
1 Copy the example from the Help file into an empty VBA code module.
2 Verify that AutoCAD has a blank drawing open to model space.
3 Open the Macros dialog box by entering the command VBARUN.
4 Choose the macro and press Run.
More information on running macros and the Macros dialog box is
available in Run a Macro on page 17.
6 |
Introduction
New Objects
The following section lists new objects and their new methods, events, and
properties.
New methods, properties, and events since AutoCAD 2002
Object
Method/Property/Event name
AcCmColor
FileDependencies
FileDependency
SecurityParams
Changed Items
The following section describes existing items that have changed.
Changed methods and properties
AutoCAD 2002 item
Description of change
AddHatch method
AddHatch method
AddMInsertBlock method
AddMInsertBlock method
AttachExternalReference method
AttachExternalReference method
Color property
TrueColor property
Migrating Automation
Projects | 7
Description of change
InsertBlock method
InsertBlock Method
ObjectARXPath property
ObjectARXPath property
Open method
Open method
SaveAs method
SaveAs method
Removed Items
The following items were removed in AutoCAD 2004:
XMLDatabase object
LicenseServer property
8 |
Introduction
Migrating Automation
Projects | 9
10
In this chapter
Understand Embedded
and
Global VBA Projects
Organize Your Projects
Exercise
More Information
Review AutoCAD VBA
Project
Terms
AutoCAD VBA Commands
11
Enter the VBALOAD command, which opens the Open VBA Project
dialog box.
Drag a DVB file from Windows Explorer and drop it into an open
drawing in the AutoCAD window.
Virus Alert
Each time you load a project you are given the option of enabling or disabling the code within that project as a protection against viruses. If you
enable the code, viruses in the code can begin executing. If you disable the
code, the project will still be loaded, but all code within that project is prevented from running. The virus alert is not displayed when you load a
project by dragging a DVB file from Windows Explorer and dropping it into
an open drawing in the AutoCAD window.
More information about the virus alert is available in Set the Project
Options on page 18.
Unload a Project
Unloading a project frees up memory and keeps the list of loaded projects at
a length that is easy to manage.
You cannot unload embedded projects or projects that are referenced by
other loaded projects.
To unload a VBA project
1 In the VBA Manager, select the project you want to unload.
2 Choose Unload.
3 Or, use the VBAUNLOAD command, which prompts you for the project to
be unloaded.
Create
Project
New
New projects are created as unsaved global projects. Once a project has been
created, you can then embed the project in a drawing, or save the project
out to a project file.
To create
project
1
Open
Manager.
new
the
VBA
VBA
2 Choose New.
A new project will be created with the default name of ACADProject. To
change the project name you must go into the VBA IDE. For more information on naming your project in the VBA IDE, see Name Your
Project on page 24.
Save
Project
Your
Handle Your
Macros
A macro is a public (executable) subroutine. Each project usually contains at
least one macro.
By limiting the valid range you can control how many macro names appear
in the list. This will help you in the cases when many macros are available in
the loaded drawings and projects.
To create a new macro
1 Open the Macros dialog box and enter the name for the new macro.
2 In the Macros In drop-down list, select a project to create the new macro
in.
3 Choose Create.
If a macro with the specified name already exists, you will be asked if you
want to replace the existing macro.
If you select Yes at the prompt, the code in the existing macro will be
deleted and a new, empty macro will be created with the specified name.
If you select No at the prompt, you will be returned to the Macros dialog box
to enter a new name for the macro.
If you select Cancel at the prompt, the Macros dialog box will be dismissed
and no new macro will be created.
To delete a macro
1 Open the Macros dialog box and select the macro to delete.
2 Choose Delete. You will be prompted to confirm the delete.
3 At the prompt, choose Yes to delete the macro, or No to cancel the delete.
Run a Macro
Running a macro executes the macro code within the context of the current
AutoCAD session. The current active drawing is considered to be the open
drawing that has the focus when macro execution begins. All VBA
references to the ThisDrawing object will refer to the current active drawing
for macros in global projects. For macros in embedded projects, the
ThisDrawing object always refers to the drawing in which the macro is
embedded.
To run a macro from the Macros dialog box
1 Open the Macros dialog box and select the macro to run.
2 Choose Run.
To run a macro from the VBA IDE
From the Run menu, use the Run Macro menu option.
If no macro or form is current, a dialog box will display allowing you to
choose the macro to run.
If a given macro is current (the cursor is in a procedure), that macro will
be executed.
Edit a Macro
Editing a macro will open the VBA IDE with the chosen macro open in the
Code window. For more information on editing macros in the VBA IDE see
Edit Your Projects with the VBA IDE on page 19.
To edit a macro
1 Open the Macros dialog box and select the macro to edit.
2 Choose Edit.
When this option is enabled, unhandled errors found during the execution
of a VBA macro will suspend the execution of the macro and display the
VBA IDE at the point of the error in the macro.
When this option is disabled, untrapped errors found during the execution
of a VBA macro will display a message box alerting you to the error, and
then end execution of the macro.
Enable
Macro
Virus
Protection
The virus protection mechanism displays a built-in warning message whenever you open a drawing that may contain macro viruses.
View
Information
Project
The VBA IDE contains a window called the Project window, which displays a
list of all loaded VBA projects. It also displays the code, class, and form modules included in the project, the document associated with the project, all
other VBA projects referenced from the project, and the physical location
(path) of the project.
The Project window has its own toolbar, which can be used to open various
project components for editing. Use the View Code button to open the code
for a selected module. Use the View Object button to display selected
objects such as forms.
View Object
View Code
Objects
The object component represents the type of object, or document, that the
VBA code will access. For AutoCAD VBA projects, this object represents the
current AutoCAD drawing.
Forms
The form component contains the custom dialog boxes you constructed for
use with your project.
Standard Modules
The code module component contains your generic procedures and
functions. A standard module is also referred to as a code module, or as
simply a module.
Class Modules
The class module component contains all your own objects, which are
defined as classes.
References
The reference component contains all your references to other projects or
libraries.
Edit Components
You can edit standard modules, class modules, and forms in the VBA IDE.
Standard and class modules are edited in a Code window. Forms are edited in
the UserForm window using a special toolbox.
You can open as many Code windows as you have modules, so you can
easily view the code in different forms or modules, and copy and paste
between them.
To edit a component in your project
1 In the Project window of the VBA IDE, select the component you want to
edit.
2 Select the View Code button in the Project window to open a
Code window.
3
The margin indicator bar is located down the left side of the Code window.
It is used to display margin indicators that are used during code editing and
debugging.
The full view and procedure view icons are located at the bottom-left
corner of the Code window and toggle the display from only one
procedure at a time to viewing the entire module at one time.
current object
current procedure
margin
indicator
bar
split bar
Procedure/
Full View
buttons
Use
the
Window
UserForm
The UserForm window allows you to create custom dialog boxes in your
project.
To add a control simply drag the desired control from the toolbox and place
it on the form. You can set your controls to align with the grid of your
form from the General tab of the Options dialog box. You can view the
form grid and determine the size of the gridlines from the General tab of
the Options dialog box. (See Set the VBA IDE Options on page 26 for more
information on the Options dialog box.)
Each form you design will automatically have a Maximize, Minimize, and
Close button. These buttons have already been implemented for you.
To add code to the control, simply double-click on the control once it has
been placed on the form. This will open a Code window for the control.
2 In the Save As dialog box, enter the new name and location for the
project file.
Note Before you save a project, it is assigned the default file name
project.dvb. It is important that you assign a new name to your project file
when you save the project. If you save a project with the default file name
project.dvb, you will no longer be able to create new empty projects. Each time
you create a new project, you will actually be loading the saved project called
project.dvb.
Project referencing is a standard feature of Microsoft VBA. There is no additional work in AutoCAD to extend this functionality. You can find more
information on referencing projects in the Microsoft Visual Basic help file.
You can open the Microsoft Visual Basic help file from the Help menu in the
VBA IDE.
Editor
The Editor tab specifies the Code window and Project window settings.
Code settings include
Editor Format
The Editor Format tab specifies the appearance of your Visual Basic code.
You can
General
The General tab specifies the settings, error handling, and compile settings
for your current Visual Basic project.
You can
Docking
The Docking tab allows you to choose which windows you want to be
dockable.
Perform an Introductory
Exercise
Now that you have learned the basics of programming in AutoCAD VBA,
lets try creating a simple Hello World exercise. In this exercise you will
create a new AutoCAD drawing, add a line of text to that drawing, then
save the drawing, all from VBA.
Create the Hello World text object
1 Open the VBA IDE by entering the following command from the
AutoCAD command line:
Command: VBAIDE
2 Open the Code window by selecting the Code option from the View
menu in the VBA IDE.
3 Create a new procedure in the project by selecting the Procedure option
from the Insert menu in the VBA IDE.
4 When prompted for the procedure information, enter a name such as
HelloWorld. Make sure the Type selected is Sub, and the Scope selected is
Public.
5 Choose OK.
6 Enter the following code (that opens a new drawing) between the lines
Public Sub HelloWorld() and End Sub.
ThisDrawing.Application.Documents.Add
7 Enter the following code (that creates the text string and defines its insertion location) immediately following the code entered in step 6.
Dim
Dim
Dim
Dim
insPoint(0
textHeight
textStr As
textObj As
insPoint(0) = 2
insPoint(1) = 4
insPoint(2) = 0
To 2) As Double
As Double
String
AcadText
'Declare
'Declare
'Declare
'Declare
insertion point
text height
text string
text object
textHeight = 1
textStr = "Hello World!"
8 Enter the code (that saves the drawing) immediately following the code
entered in step 7.
ThisDrawing.SaveAs("Hello.dwg")
9 Run your program by selecting the Run Sub/UserForm option from the
Run menu in the VBA IDE.
When the program finishes running, bring the AutoCAD application to the
front. You should see your text Hello World! visible in your drawing. The
drawing name should be Hello.dwg.
More Information
More information on the VBA IDE and the Visual Basic programming language is available in the Help files provided by Microsoft. To access the
Microsoft Help files, choose Microsoft Visual Basic Help from the Help
menu in the VBA IDE.
Embedded
Project
Regular
Document
Smart Document
Current Project
ThisDrawing
VBA IDE
More Information
29
VBA Manager
Macros Dialog
Box
VBALOAD
VBARUN
VBAUNLOAD
VBAMAN
VBASTMT
ActiveX Automation
Basics
In this chapter
Understand the
AutoCAD Object
Model
Collection Objects
Hierarchy
Understand Properties
and
Methods
Understand Parent
F1
Objects
and
Properties
Using Other
IDE and
Programming
Languages
press
F1 .
31
Graphical objects such as lines, arcs, text, and dimensions are objects.
Style settings such as linetypes and dimension styles are objects.
Organizational structures such as layers, groups, and blocks are objects.
The drawing display such as view and viewport are objects.
Even the drawing and the AutoCAD application are considered objects.
The Application object is also the Global object for the ActiveX interface.
This means that all the methods and properties for the Application object
are available in the global name space.
Layers, Linetypes, and TextStyles. The Document object also provides access
to the Plot and Utility objects.
Collections also have some other methods and properties in common. The
Count property can be used to obtain a zero-based count of the objects in a
collection. The Item method can be used to obtain any object within a
collection.
AutoCAD Application
Preferences
PreferencesDisplay
PreferencesDrafting
PreferencesFiles
PreferencesOpenSave
PreferencesOutput
PreferencesProfile
PreferencesSelection
PreferencesSystem
PreferencesUser
Documents
Document
DatabasePreferences
Plot
Utility
The Plot object provides access to settings in the Plot dialog box and gives an
application the ability to plot the drawing using various methods. For more
information on plotting, see Plot Your Drawing on page 275.
The Utility object provides user input and conversion functions. The user
input functions are methods that prompt the user on the AutoCAD command line for input of various types of data, such as strings, integers, reals,
points, and so forth. The conversion functions are methods that operate on
AutoCAD-specific data types such as points and angles, in addition to string
and number handling. For more information on the user input functions,
see Prompt for User Input on page 73.
The following statement then adds a line to the model space using the userdefined variable:
Dim startPoint(0 To 2) As Double, endPoint(0 To 2) As Double
Dim LineObj as AcadLine
startPoint(0) = 0: startPoint(1) = 0: startPoint(2) = 0
endPoint(0) = 30: endPoint(1) = 20: endPoint(2) = 0
Set LineObj = moSpace.AddLine(startPoint,endPoint)
Collection
Objects
A Collection object is a predefined object that contains (is a parent object
for) all instances of a similar object. There is a Collection object for the
following objects:
Documents
Collection
ModelSpace
Collection
PaperSpace
Collection
Block Object
Blocks Collection
Collection Objects
39
Dictionaries
Collection
DimStyles
Collection
Groups
Collection
Hyperlinks
Collection
Layers Collection
Layouts
Collection
Linetypes
Collection
MenuBar
Collection
MenuGroups
Collection
RegisteredApplic
ations Collection
SelectionSets
Collection
TextStyles
Collection
UCSs Collection
Views Collection
Viewports
Collection
Access a Collection
Most collection objects are accessed through the Document object. The
Document object contains a property for each of the Collection objects. For
example, the following code defines a variable and sets it to the Layers collection of the current drawing:
Note Do not use the entity edit methods (Copy, Array, Mirror, and so forth)
on any object while simultaneously iterating through a collection using the For
Each mechanism. Either finish your iteration before you attempt to edit an
object in the collection or create a temporary array and set it equal to the
collection. Then you can iterate through the copied array and perform your
edits.
Iterate through the Layers collection
The following example iterates through a collection and displays the
names of all layers in the collection:
Sub Ch2_IterateLayer()
' Iterate through the collection
On Error Resume Next
Dim
Dim
msg
For
I As Integer
msg As String
= ""
I = 0 To ThisDrawing.Layers.count - 1
msg = msg + ThisDrawing.Layers.Item(I).Name + vbCrLf
Next
MsgBox msg
End Sub
Once an object has been deleted, you must never attempt to access the
object again later in the program.
For example, a Circle object has the Center property. This property
represents the 3D World Coordinate System coordinate at the center of
that circle. To change the center of the circle, simply set this property to the
new coordi- nate. The Circle object also has a method called Offset. This
method creates a new object at a specified offset distance from the existing
circle. To see a list of all properties and methods for the Circle object, refer
to the Circle object in the AutoCAD ActiveX and VBA Reference.
What Is a Variant?
A variant is a special data type that can contain any kind of data except
fixed- length string data and user-defined types. A variant can also contain
the special values Empty, Error, Nothing, and NULL. You can determine how
the data in a variant is treated using the VarType or TypeName Visual Basic
functions.
You can use the Variant data type in place of most any data type to work
with data in a more flexible way.
_
")
_
point: ")
Note The registry key for COM application access for AutoCAD 2004 is
AutoCAD.Application.16.
Next, set the document variable to the Document object in the AutoCAD
application. The Document object is returned by the ActiveDocument property of the Application object.
Dim acadDoc as AcadDocument
Set acadDoc = acadApp.ActiveDocument
From this point on, use the acadDoc variable to reference the current
AutoCAD drawing.
50
effectively in
the
AutoCAD
In this chapter
Open, Save, and Close
Drawings
Set AutoCAD Preferences
Control the Application
Window
Control the Drawing
Windows
Variables
Draw with Precision
Prompt for User Input
Access the
AutoCAD
Command Line
Work with No Documents
Open
Import Other File Formats
Export to Other File
Formats
51
Set AutoCAD
Preferences
There are nine objects pertaining to options, each representing a tab on the
Options dialog box. These objects provide access to all of the registry-stored
options in the Options dialog box. You can customize many of the
AutoCAD settings by using properties found on these objects. These objects
are
PreferencesDisplay
PreferencesDrafting
PreferencesFiles
PreferencesOpenSave
PreferencesOutput
PreferencesProfiles
PreferencesSelection
PreferencesSystem
PreferencesUser
These objects are accessible via the Preferences object. To gain access to the
Preferences object, use the Preferences property of the Application object:
Dim acadPref as AcadPreferences
Set acadPref = ThisDrawing.Application.Preferences
You can then access any of the specific Preferences objects using the
Display, Drafting, Files, OpenSave, Output, Profile, Selection, System, and
User properties.
Set the crosshairs to full screen
Sub Ch2_PrefsSetCursor()
' This example sets the crosshairs of the AutoCAD drawing
cursor
' to full screen.
' Access the Preferences object
Dim acadPref As AcadPreferences
Set acadPref = ThisDrawing.Application.Preferences
' Use the CursorSize property to set the size of the
crosshairs acadPref.Display.CursorSize = 100
End Sub
Database Preferences
In addition to the nine Preferences objects, the DatabasePreferences object
contains all the options stored in the drawing. This separate object was provided to make the drawing-stored options available to applications accessing
AutoCAD drawings without first starting the AutoCAD application
(ObjectDBXTM applications).
The DatabasePreferences object is found under the Document object.
Sub Ch3_CurrentWindowState()
Dim CurrWindowState As Integer
Dim msg As String
CurrWindowState = ThisDrawing.Application.WindowState
msg = Choose(CurrWindowState, "normal", _
"minimized", "maximized")
MsgBox "The application window is " + msg
End Sub
Sub Ch3_SizeDocumentWindow()
ThisDrawing.Width = 400
ThisDrawing.Height = 400
End Sub
Use Zoom
A view is a specific magnification, position, and orientation of a drawing.
The most common way to change a view is to use one of the many
AutoCAD Zoom options, which increases or decreases the size of the image
displayed in the graphics area. For more information on zooming in
AutoCAD, see Magnify a View (Zoom) in the Users Guide.
Scale a View
If you need to increase or decrease the magnification of the image by a
precise scale, you can specify a zoom scale in three ways:
To scale a view, use the ZoomScaled method. This method takes two
param- eters as input: the scale and the type of scale. The scale is simply a
number. How that number gets interpreted by AutoCAD depends on the
type of scale you choose.
The type of scale determines if the scale value is created relative to the drawing limits, the current view, or the paper space units. To scale relative to the
drawing limits, use the constant acZoomScaledAbsolute. To scale the view
relative to the current view, use the constant acZoomScaledRelative. To scale
relative to paper space units, use the constant
acZoomScaledRelativePSpace.
Center Objects
You can move a specific point in your drawing to the center of the graphics
area. The ZoomCenter method is useful for resizing an object and bringing
it to the center of the viewport. With ZoomCenter, you can specify a scale
size by entering a magnification relative to the current view.
Zoom in on the active drawing to a specified center
The following example shows the effects of using ZoomCenter to display a
view at the same size and at twice the size:
Sub Ch3_ZoomCenter()
MsgBox "Perform a ZoomCenter using:" & vbCrLf & _
"Center 3, 3, 0" & vbCrLf & _
"Magnification: 10", , "ZoomCenter"
Dim Center(0 To 2) As Double
Dim magnification As Double
Center(0) = 3: Center(1) = 3: Center(2) = 0
magnification = 10
ThisDrawing.Application.ZoomCenter Center, magnification
End Sub
ZoomAll displays the entire drawing. If the objects extend beyond the limits,
ZoomAll displays the extents of the objects. If the objects are drawn within
the limits, ZoomAll displays the limits.
ZoomExtents calculates zooms based on the extents of the active viewport,
not the current view. Usually the active viewport is entirely visible, so the
results are obvious and intuitive. However, when using the Zoom methods
in model space while working in a paper space viewport, if you are zoomed
in beyond the paper space viewports borders, some of the area zoomed may
not be visible.
ZoomExtents changes the view to encompass the entity extents for the current drawing. In some cases (for both ZoomAll and ZoomExtents), this may
cause a regeneration. Regeneration will not occur on layers that are frozen
or turned off. If your drawing has no objects, ZoomExtents displays the
drawing limits.
For 3D views, ZoomAll and ZoomExtents have the same effect. Infinite construction lines (xlines) and rays do not affect either option.
ZoomPrevious zooms the current viewport to its previous extents.
See Magnify a View (Zoom) in the Users Guide for illustrations of how
zooming works.
Zoom in on the active drawing to all contents and to the drawing extents
Sub Ch3_ZoomAll()
' ZoomAll
MsgBox "Perform a ZoomAll", , "ZoomAll"
ThisDrawing.Application.ZoomAll
' ZoomExtents
MsgBox "Perform a ZoomExtents", , "ZoomExtents"
ThisDrawing.Application.ZoomExtents
End Sub
To delete a named view, simply use the Delete method. The Delete
method for the View object lies on the View object, not its parent.
Add a View object
Sub Ch3_AddView()
' Add a named view to the views collection
Dim viewObj As AcadView
Set viewObj = ThisDrawing.Views.Add("View1")
End Sub
Zoom, set the Snap, Grid, and UCS icon modes, and restore named
views in individual viewports
Draw from one viewport to another when executing a command
Name a configuration of viewports so you can reuse it
You can display tiled viewports in various configurations. How you display
the viewports depends on the number and size of the views you need to
see.
For further information and illustrations describing viewports, see Set
Model Tab Viewports in the Users Guide.
0,1
1,1
.5,.5
0,0
1,0
In this example:
1)
1)
5)
5)
Split
a viewport, then iterate through the
windows
This example splits a viewport into four windows. It then iterates through all
the viewports in the drawing and displays the viewport name and the lowerleft and upper-right corner for each viewport.
Sub Ch3_IteratingViewportWindows()
' Create a new viewport and make it active
Dim vportObj As AcadViewport
Set vportObj = ThisDrawing.Viewports.Add("TEST_VIEWPORT")
ThisDrawing.ActiveViewport = vportObj
' Split vport into 4 windows
vportObj.Split acViewport4
' Iterate through the viewports,
' highlighting each viewport and displaying
' the upper right and lower left corners
' for each.
Dim vport As AcadViewport
Dim LLCorner As Variant
Dim URCorner As Variant
For Each vport In ThisDrawing.Viewports
ThisDrawing.ActiveViewport = vport
LLCorner = vport.LowerLeftCorner
URCorner = vport.UpperRightCorner
MsgBox "Viewport: " & vport.Name & " is now active." & _
vbCrLf & "Lower left corner: " & _
LLCorner(0) & ", " & LLCorner(1) & vbCrLf & _
"Upper right corner: " & _
URCorner(0) & ", " & URCorner(1)
Next vport
End Sub
To reset these objects, simply set the ActiveTextStyle, ActiveUCS, or ActiveViewport property, using the updated object.
Reset the active viewport
The following example changes the display of the grid in the active
viewport and then resets the viewport as the active viewport to display the
change.
Sub Ch3_ResetActiveViewport()
' Toggle the setting of the grid display
' for the active viewport
ThisDrawing.ActiveViewport.GridOn = _
Not (ThisDrawing.ActiveViewport.GridOn)
' Reset the active viewport
ThisDrawing.ActiveViewport = ThisDrawing.ActiveViewport
End Sub
For more information about this topic, see Use Precision Tools in the Users
Guide.
Note Both properties require a call to the Update method to update the
AutoCAD display.
See Adjust Grid and Grid Snap in the Users Guide for more information on
using and setting snaps and grids.
Change the snap base point and rotation angle
This example changes the snap base point to (1,1) and the snap rotation
angle to 30 degrees. The grid is turned on so that the changes are visible.
Sub Ch3_ChangeSnapBasePoint()
' Turn on the grid for the active viewport
ThisDrawing.ActiveViewport.GridOn = True
' Change the snap base point to 1, 1
Dim newBasePoint(0 To 1) As Double
newBasePoint(0) = 1: newBasePoint(1) = 1
ThisDrawing.ActiveViewport.SnapBasePoint = newBasePoint
' Change the snap rotation angle to 30 degrees (0.575 radians)
Dim rotationAngle As Double
rotationAngle = 0.575
ThisDrawing.ActiveViewport.SnapRotationAngle = rotationAngle
' reset the viewport
ThisDrawing.ActiveViewport = ThisDrawing.ActiveViewport
End Sub
on the current snap angle or UCS.) Ortho mode works with activities that
require you to specify a second point. You can use Ortho not only to
establish vertical or horizontal alignment but also to enforce parallelism or
create reg- ular offsets.
By allowing AutoCAD to impose orthogonal restraints, you can draw more
quickly. For example, you can create a series of perpendicular lines by
turning on Ortho mode before you start drawing. Because the lines are
constrained to the horizontal and vertical axes, you can draw faster,
knowing that the lines are perpendicular.
ortho mode on
As you move the cursor, a rubber-band line that defines the displacement follows the horizontal or vertical axis, depending on which axis is nearest to the
cursor. AutoCAD ignores Ortho mode in perspective views, or when you
enter coordinates on the command line or specify an object snap.
To turn Ortho mode on or off, use the OrthoOn property. This property
requires a Boolean for input. Set to TRUE to turn Ortho mode on, and to
FALSE to turn Ortho mode off. For example, the following statement turns
Ortho mode on for the active viewport:
ThisDrawing.ActiveViewport.OrthoOn = True
Create Rays
A ray is a line in 3D space that starts at a point you specify and extends to
infinity. Unlike xline construction lines, which extend in two directions,
rays extend in only one direction. As a result, rays help reduce the visual
clutter caused by numerous construction lines.
Like construction lines, rays are ignored by commands that display the drawing extents.
For more information on rays, see Draw Construction Lines (and Rays) in
the Users Guide.
Query Rays
Once created, you can query the first point of a ray using the BasePoint property. The second point used to create the ray is not stored with the object.
Instead, use the DirectionVector property to obtain the directional vector for
the ray.
Add, query, and edit a Ray object
The following example code creates a Ray object using the two points
(5, 0, 0) and (1, 1, 0). It then queries the current base point and direction
vector and displays the results in a message box. The direction vector is then
changed and the base point and new direction vector are queried and
displayed.
Sub Ch3_EditRay()
Dim rayObj As AcadRay
Dim basePoint(0 To 2) As Double
Dim secondPoint(0 To 2) As Double
' Define the ray
basePoint(0) = 3#: basePoint(1) = 3#: basePoint(2) = 0#
secondPoint(0) = 4#: secondPoint(1) = 4#: secondPoint(2) = 0#
' Creates a Ray object in model space
Set rayObj = ThisDrawing.ModelSpace.AddRay _
(basePoint, secondPoint)
ThisDrawing.Application.ZoomAll
' Find the current status of the Ray
MsgBox "The base point of the ray is: " & _
rayObj.basePoint(0) & ", " & _
rayObj.basePoint(1) & ", " & _
rayObj.basePoint(2) & vbCrLf & _
"The directional vector for the ray is: " & _
rayObj.DirectionVector(0) & ", " & _
rayObj.DirectionVector(1) & ", " & _
rayObj.DirectionVector(2), , "Edit Ray"
' Change the directional vector for the ray
Dim newVector(0 To 2) As Double
newVector(0) = -1
newVector(1) = 1
newVector(2) = 0
rayObj.DirectionVector = newVector
ThisDrawing.Regen False
MsgBox "The base point of the ray is: " & _
rayObj.basePoint(0) & ", " & _
rayObj.basePoint(1) & ", " & _
rayObj.basePoint(2) & vbCrLf & _
"The directional vector for the ray is: " & _
rayObj.DirectionVector(0) & ", " & _
rayObj.DirectionVector(1) & ", " & _
rayObj.DirectionVector(2), , "Edit Ray"
End Sub
Calculate
Values
Points
and
By using the methods provided by the Utility object, you can quickly solve
a mathematical problem or locate points on your drawing. By using
methods on the Utility object, you can do the following:
Find the angle of a line from the X axis with the AngleFromXAxis
method
Convert an angle as a string to a real (double) value with the
AngleToReal method
Find the distance between two points with the GetDistance method
This example uses the GetDistance method to obtain the point coordinates,
and the MsgBox function to display the calculated distance.
Sub Ch3_GetDistanceBetweenTwoPoints()
Dim returnDist As Double
' Return the value entered by user. A prompt is provided.
returnDist = ThisDrawing.Utility.GetDistance _
(, "Pick two points.")
MsgBox "The distance between the two points is: " & returnDist
End Sub
Calculate Areas
You can find the area of an arc, circle, ellipse, lightweight polyline,
polyline, region, or planar-closed spline by using the Area property.
If you need to calculate the combined area of more than one object, you can
keep a running total as you add or use the Boolean method on a series of
regions to obtain a single region representing the desired area. From this single region you can use the Area property to obtain its area.
The calculated area differs according to the type of object you query. For an
explanation of how area is calculated for each object type, see Obtain Area
Information in the Users Guide.
GetString Method
The GetString method prompts the user for input of a string at the
AutoCAD Command prompt. This method accepts two parameters. The first
parameter controls the input of spaces in the input string. If it is set to 0,
spaces are not allowed ( SPACEBAR terminates the input); if set to 1, the
string can contain spaces ( ENTER must be used to terminate the input). The
second parameter is the prompt string.
Get a string value from the user at the AutoCAD command line
The following example displays the Enter Your Name prompt, and requires
that the input from the user be terminated by pressing ENTER (spaces are
allowed in the input string). The string value is stored in the retVal
variable and is displayed using a message box.
Sub Ch3_GetStringFromUser()
Dim retVal As String
retVal = ThisDrawing.Utility.GetString _
(1, vbCrLf & "Enter your name: ")
MsgBox "The name entered was: " & retVal
End Sub
GetPoint Method
The GetPoint method prompts the user for the specification of a point at the
AutoCAD Command prompt. This method accepts two parameters, an
optional from point and the prompt string. If the from point is provided,
AutoCAD draws a rubber-band line from that point. To control the user
input, this method can be preceded by a call to the InitializeUserInput
method.
Get a point selected by the user
The following example prompts the user for two points, then draws a line
using those points as the start point and endpoint.
Sub Ch3_GetPointsFromUser()
Dim startPnt As Variant
Dim endPnt As Variant
Dim prompt1 As String
Dim prompt2 As String
prompt1 = vbCrLf & "Enter the start point of the line: "
prompt2 = vbCrLf & "Enter the end point of the line: "
' Get the first point without entering a base point
startPnt = ThisDrawing.Utility.GetPoint(, prompt1)
' Use the point entered above as the base point
endPnt = ThisDrawing.Utility.GetPoint(startPnt, prompt2)
' Create a line using the two points entered
ThisDrawing.ModelSpace.AddLine startPnt, endPnt
ThisDrawing.Application.ZoomAll
End Sub
GetKeyword Method
The GetKeyword method prompts the user for input of a keyword at the
AutoCAD Command prompt. This method accepts only one parameter,
which is the prompt string. The keywords and input parameters are defined
with a call to the InitializeUserInput method.
Get a keyword from the user at the AutoCAD command line
The following example forces the user to enter a keyword by setting the first
parameter of InitializeUserInput to 1, which disallows NULL input (pressing
ENTER ). The second parameter establishes the list of valid keywords.
Sub Ch3_KeyWord()
Dim keyWord As String
ThisDrawing.Utility.InitializeUserInput 1, "Line Circle Arc"
keyWord = ThisDrawing.Utility.GetKeyword _
(vbCrLf & "Enter an option (Line/Circle/Arc): ")
MsgBox keyWord, , "GetKeyword Example"
End Sub
Sub Ch3_UserInput()
' The first parameter of InitializeUserInput (6)
' restricts input to positive and non-negative
' values. The second parameter is the list of
' valid keywords.
ThisDrawing.Utility.InitializeUserInput 6, "Big Small Regular"
' Set the prompt string variable
Dim promptStr As String
promptStr = vbCrLf & "Enter the size or (Big/Small/<Regular>):"
' At the GetInteger prompt, entering a keyword or pressing
' ENTER without entering a value results in an error. To allow
' your application to continue and check for the error
' description, you must set the error handler to resume on
error.
On Error Resume Next
' Get the value entered by the user
Dim returnInteger As Integer
returnInteger = ThisDrawing.Utility.GetInteger(promptStr)
' Check for an error. If the error number matches the
' one shown below, then use GetInput to get the returned
' string; otherwise, use the value of returnInteger.
If Err.Number = -2145320928 Then
Dim returnString As String
Debug.Print Err.Description
returnString = ThisDrawing.Utility.GetInput()
If returnString = "" Then
'ENTER returns null string
returnString = "Regular"
'Set to default
End If
Err.Clear
Else
'Otherwise,
returnString = returnInteger
'Use the value entered
End If
' Display the result
MsgBox returnString, , "InitializeUserInput Example"
End Sub
You
You
You
You
can
can
can
can
open a document.
create a new document.
import a document.
exit out of AutoCAD.
These actions are all available from the Documents collection. The methods
and properties of the Documents collection, in addition to a limited set of
methods and properties of the Application object, are the only valid
interface available when there are no documents open. If you perform any
other action, such as attempting to access user options, your actions will
result in an error.
Use the Count property on the Documents collection to determine if
AutoCAD is in a zero document state. If Documents.Count = 0, then
AutoCAD is in a zero document state. If Documents.Count > 0, then there
is at least one drawing open.
Sub Ch3_ImportingAndExporting()
' Create the circle for visual representation
Dim circleObj As AcadCircle
Dim centerPt(0 To 2) As Double
Dim radius As Double
centerPt(0) = 2: centerPt(1) = 2: centerPt(2) = 0
radius = 1
Set circleObj = ThisDrawing.ModelSpace.AddCircle _
(centerPt, radius)
ThisDrawing.Application.ZoomAll
' Create an empty selection set
Dim sset As AcadSelectionSet
Set sset = ThisDrawing.SelectionSets.Add("NEWSSET")
'Export the current drawing to a DXF file in the
' AutoCAD temporary file directory
Dim tempPath As String
Dim exportFile As String
Const dxfname As String = "DXFExprt"
tempPath = _
ThisDrawing.Application.preferences.Files.TempFilePath
exportFile = tempPath & dxfname
ThisDrawing.Export exportFile, "DXF", sset
' Delete the empty selection set
ThisDrawing.SelectionSets.Item("NEWSSET").Delete
' Open a new drawing
ThisDrawing.Application.Documents.Add "acad.dwt"
' Define the import
Dim importFile As String
Dim insertPoint(0 To 2) As Double
Dim scalefactor As Double
importFile = tempPath & dxfname & ".dxf"
insertPoint(0) = 0: insertPoint(1) = 0: insertPoint(2) = 0
scalefactor = 2#
' Import the file
ThisDrawing.Import importFile, insertPoint, scalefactor
ThisDrawing.Application.ZoomAll
End Sub
80
In this chapter
Create Objects
Linetyp
es
Save and Restore Layer
Settings
Add Text to Drawings
81
Create Objects
While there are often several different ways to create the same graphical
object in AutoCAD, ActiveX Automation offers only one creation method
per object. For example, in AutoCAD there are four different ways you can
create a circle: (1) by specifying the center and radius, (2) by two points
defin- ing the diameter, (3) by three points defining the circumference, or
(4) by two tangents and a radius. However, in ActiveX Automation there is
only one creation method provided to create a circle, and that method uses
the center and radius.
Note The VB and VBA methods of creating objects using either CreateObject
or Dim with the New keyword can only be used to create the AutoCAD Application object. All other AutoCAD objects must be created using the Add or
Add<objectname> methods provided in the AutoCAD interface.
moSpace
paSpace
moSpace
paSpace
As AcadModelSpace
As AcadPaperSpace
= ThisDrawing.ModelSpace
= ThisDrawing.PaperSpace
The following statement adds a line to the model space using the userdefined variable:
Set lineObj = moSpace.AddLine(startPoint,endPoint)
Create Lines
The line is the most basic object in AutoCAD. You can create a variety of
linessingle lines, and multiple line segments with and without arcs. In
general, you draw lines by specifying coordinate points. The default
linetype is CONTINUOUS, an unbroken line, but various linetypes are
available that use dots and dashes.
To create a line, use one of the following methods:
AddLine
AddLightweightPolyline
Creates a 2D lightweight polyline from a list of vertices.
AddMLine
Creates a multiline.
AddPolyline
Creates a 2D or 3D polyline.
Standard lines and multilines are created on the XY plane of the WCS.
Polylines and Lightweight Polylines are created in the Object Coordinate
Sys- tem (OCS). For information about converting OCS coordinates, see
Convert Coordinates on page 245.
Create a Polyline object
This example uses the AddLightweightPolyline method to create a simple
two-segment polyline using the 2D coordinates (2,4), (4,2), and (6,4).
Sub Ch4_AddLightWeightPolyline()
Dim plineObj As AcadLWPolyline
Dim points(0 To 5) As Double
' Define the 2D polyline
points(0) = 2: points(1)
points(2) = 4: points(3)
points(4) = 6: points(5)
points
= 4
= 2
= 4
Create Objects
83
AddCircle
AddEllipse
AddSpline
For more information about splines, see the Spline object and AddSpline
method documentation in the AutoCAD ActiveX and VBA Reference.
Adding 32, 64, or 96 to the previous value selects a shape to draw around the
point in addition to the figure drawn through it:
32
33
34
35
36
64
65
66
67
68
96
97
98
99
100
PDSIZE controls the size of the point figures, except for PDMODE values 0 and
Create Objects
85
The first two points define one edge of the polygon. The third point is
defined diagonally opposite from the second. If the fourth point is set equal
to the third point, then a filled triangle is created.
To create a solid-filled area, use the AddSolid method.
For more information about filling solids, see Create Solid-Filled Areas in
the Users Guide.
Create a solid-filled object
The following code example creates a quadrilateral solid in model space
using the coordinates (0, 0, 0), (5, 0, 0), (5, 8, 0), and (0, 8, 0).
Sub Ch4_CreateSolid()
Dim solidObj As AcadSolid
Dim point1(0 To 2) As Double
Dim point2(0 To 2) As Double
Dim point3(0 To 2) As Double
Dim point4(0 To 2) As Double
' Define the solid
point1(0) = 0#: point1(1) = 0#: point1(2) = 0#
point2(0) = 5#: point2(1) = 0#: point2(2) = 0#
point3(0) = 5#: point3(1) = 8#: point3(2) = 0#
point4(0) = 0#: point4(1) = 8#: point4(2) = 0#
' Create the solid object in model space
Set solidObj = ThisDrawing.ModelSpace.AddSolid _
(point1, point2, point3, point4)
ZoomAll
End Sub
Create Regions
To create a region, use the AddRegion method. This method will create a
region out of every closed loop formed by the input array of curves.
AutoCAD converts closed 2D and planar 3D polylines to separate regions,
then con- verts polylines, lines, and curves that form closed planar loops. If
more than two curves share an endpoint, the resulting region might be
arbitrary. Because of this, several regions may actually be created when
using the AddRegion method. Use a variant to hold the newly created array
of regions.
To calculate the total number of Region objects created, use the UBound and
LBound Visual Basic functions, as in the following example:
UBound(objRegions) - LBound(objRegions) + 1
Sub Ch4_CreateRegion()
' Define an array to hold the
' boundaries of the region.
Dim curves(0 To 0) As AcadCircle
' Create a circle to become a
' boundary for the region.
Dim center(0 To 2) As Double
Dim radius As Double
center(0) = 2
center(1) = 2
center(2) = 0
radius = 5#
Set curves(0) = ThisDrawing.ModelSpace.AddCircle _
(center, radius)
' Create the region
Dim regionObj As Variant
regionObj = ThisDrawing.ModelSpace.AddRegion(curves)
ZoomAll
End Sub
Find the area of the resulting region with the Area property.
Unite Regions
To unite regions, call the Boolean method and enter the constant acUnion
for the operation instead of acSubtraction. You can combine regions in
any order to unite them.
Create Hatches
Hatching fills a specified area in a drawing with a pattern.
When creating a hatch, you do not initially specify the area to be filled.
First you must create the Hatch object. Once this is done, you can specify
the outer loop, which is the outermost boundary for the hatch. You can
then continue to specify any inner loops that may exist in the hatch.
For more information about working with hatches, see Overview of Hatch
Patterns and Fills in chapter 18, Hatches, Fills, and Wipeouts, in the
Users Guide.
Associate a Hatch
You can create associative or nonassociative hatches. Associative hatches
are linked to their boundaries and updated when the boundaries are
modified. Nonassociative hatches are independent of their boundaries.
Associativity can only be set when a hatch is created. Once a hatch has been
created, you can unassociate it, but you cannot associate it again.
To make a hatch associative, set the Associativity parameter of the
AddHatch method to TRUE. To make a hatch nonassociative, set the
Associativity parameter of the AddHatch method to FALSE.
To specify a unique pattern, you must enter both a pattern type and a
pattern name when creating the Hatch object. The pattern type specifies
where to look up the pattern name. When entering the pattern type, use
one of the following constants:
acHatchPatternTypePredefined
Selects the pattern name from those defined in the
acad.pat file
acHatchPatternTypeUserDefined
Defines a pattern of lines using the current linetype
acHatchPatternTypeCustomDefined
Selects the pattern name from a PAT other than the
acad.pat file
When entering the pattern name, use a name that is valid for the file specified by the pattern type.
Condition
Description
Normal
Condition
Description
Outer
Ignore
When you have finished defining the hatch it must be evaluated before it
can be displayed. Use the Evaluate method to do this.
Create a Hatch object
This example creates an associate hatch in model space. Once the hatch has
been created, you can change the size of the circle that the hatch is
associated with. The hatch will change to match the current circle size.
Sub Ch4_CreateHatch()
Dim hatchObj As AcadHatch
Dim patternName As String
Dim PatternType As Long
Dim bAssociativity As Boolean
' Define the hatch
patternName = "ANSI31"
PatternType = 0
bAssociativity = True
' Create the associative Hatch object
Set hatchObj = ThisDrawing.ModelSpace.AddHatch _
(PatternType, patternName, bAssociativity)
' Create the outer boundary for the hatch. (a circle)
Dim outerLoop(0 To 0) As AcadEntity
Dim center(0 To 2) As Double
Dim radius As Double
center(0) = 3: center(1) = 3: center(2) = 0
radius = 1
Set outerLoop(0) = ThisDrawing.ModelSpace. _
AddCircle(center, radius)
' Append the outerboundary to the hatch
' object, and display the hatch
hatchObj.AppendOuterLoop (outerLoop)
hatchObj.Evaluate
ThisDrawing.Regen True
End Sub
Create a Selection
Set
To create a named selection set, use the Add method. This method requires
only a single parameterthe name of the selection set.
If a selection set of the same name already exists, AutoCAD returns an error
message. It is a good programming practice to delete a selection set when
you no longer need it. Use the Delete method to delete a selection set, as in
the following example:
ThisDrawing.SelectionSets.Item("NewSelectionSet").Delete
Select
SelectAtPoint
SelectByPolygon
SelectOnScreen
Sub Ch4_AddToASelectionSet()
' Create a new selection set
Dim sset As AcadSelectionSet
Set sset = ThisDrawing.SelectionSets.Add("SS1")
' Prompt the user to select objects
' and add them to the selection set.
' To finish selecting, press ENTER.
sset.SelectOnScreen
End Sub
Filter type
Filter type
60
62
67
For a complete list of DXF group codes, see Group Codes in Numerical
Order in the DXF Reference.
The filter arguments are declared as arrays. The filter type is declared as an
integer and the filter value as a variant. Each filter type must be paired with
a filter value. For example:
FilterType(0) = 0
'Indicates filter refers to an object
type
FilterData(0) = "Circle"
'Indicates the object type is "Circle"
Sub Ch4_FilterBlueCircleOnLayer0()
Dim sstext As AcadSelectionSet
Dim FilterType(2) As Integer
Dim FilterData(2) As Variant
Set sstext = ThisDrawing.SelectionSets.Add("SS4")
FilterType(0) = 0
FilterData(0) = "Circle"
FilterType(1) = 62
FilterData(1) = acBlue
FilterType(2) = 8
FilterData(2) = "0"
sstext.SelectOnScreen FilterType, FilterData
End Sub
Description
"*"
"="
Equals
"!="
Not equal to
"/="
Not equal to
"<>"
Not equal to
"<"
Less than
"<="
">"
Greater than
Description
">="
"&"
"&="
Logical operators in filter lists are also indicated by a 4 group code, and the
operator is a string, but the operators must be paired. The opening operator
is preceded by a less-than symbol (<), and the closing operator is followed
by a greater-than symbol (>). The following table lists the logical operators
allowed in selection set filtering.
Logical grouping operators for selection set filter lists
Starting
operator
Encloses
Ending
operator
"<AND"
"AND>"
"<OR"
"OR>"
"<XOR"
Two operands
"XOR>"
"<NOT"
One operand
"NOT>"
Sub Ch4_FilterRelational()
Dim sstext As AcadSelectionSet
Dim FilterType(2) As Integer
Dim FilterData(2) As Variant
Set sstext = ThisDrawing.SelectionSets.Add("SS5")
FilterType(0)
FilterData(0)
FilterType(1)
FilterData(1)
FilterType(2)
FilterData(2)
=
=
=
=
=
=
0
"Circle"
-4
">="
40
5#
Definition
(pound)
(at)
Definition
(period)
(asterisk)
(question mark)
(tilde)
[...]
[~...]
(hyphen)
(comma)
(reverse quote)
Use a reverse quote (`) to indicate that a character is not a wild-card, but is
to be taken literally. For example, to specify that only an anonymous block
named *U2 be included in the selection set, use the following filter
arguments:
FilterType(0) = 2
FilterData(0) = "`*U2"
Sub Ch4_FilterPolygonWildcard()
Dim sstext As AcadSelectionSet
Dim FilterType(1) As Integer
Dim FilterData(1) As Variant
Dim pointsArray(0 To 11) As Double
Dim mode As Integer
mode = acSelectionSetWindowPolygon
pointsArray(0) = -12#: pointsArray(1) = -7#: pointsArray(2)
pointsArray(3) = -12#: pointsArray(4) = 10#: pointsArray(5)
pointsArray(6) = 10#: pointsArray(7) = 10#: pointsArray(8) =
pointsArray(9) = 10#: pointsArray(10) = -7#: pointsArray(11)
0
Set sstext = ThisDrawing.SelectionSets.Add("SS10")
FilterType(0)
FilterData(0)
FilterType(1)
FilterData(1)
=
=
=
=
= 0
= 0
0
=
0
"MTEXT"
1
"*The*"
Sub Ch4_FilterXdata()
Dim sstext As AcadSelectionSet
Dim mode As Integer
Dim pointsArray(0 To 11) As Double
mode = acSelectionSetWindowPolygon
pointsArray(0) = -12#: pointsArray(1) = -7#: pointsArray(2) = 0
pointsArray(3) = -12#: pointsArray(4) = 10#: pointsArray(5) = 0
pointsArray(6) = 10#: pointsArray(7) = 10#: pointsArray(8) = 0
pointsArray(9) = 10#: pointsArray(10) = -7#: pointsArray(11) = 0
Dim FilterType(1) As Integer
Dim FilterData(1) As Variant
Set sstext = ThisDrawing.SelectionSets.Add("SS9")
FilterType(0)
FilterData(0)
FilterType(1)
FilterData(1)
=
=
=
=
0
"Circle"
1001
"MY_APP"
End Sub
Clear
Erase
Delete
Edit Objects
To modify an existing object, use the methods and properties associated
with that object. If you modify a visible property of a graphic object, use the
Update method to redraw the object onscreen.
This section describes how to edit 2D objects.
Rename Objects
As your drawings become more complex, you can rename objects to keep the
names meaningful or to avoid conflicts with names in other drawings you
have inserted in the main drawings.
You can rename any named object except those that AutoCAD names
by default, for example, layer 0 or the CONTINUOUS linetype.
Copy Objects
You can copy single or multiple objects within the current drawing. Offsetting creates new objects at a specified distance from selected objects, or
through a specified point. Mirroring creates a mirror image of objects in a
specified mirror line. Arraying creates sets of copied objects in a rectangular
or circular pattern.
For more information about copying objects, see Copy, Offset, or Mirror
Objects in the Users Guide.
Note You cannot perform any of the copy methods while simultaneously
iter- ating through a collection. An iteration will open the workspace for a readonly operation while these methods attempt to perform a read-write operation.
Complete any iteration of a collection before you call these methods.
Edit Objects
105
Sub Ch4_CopyCircleObjects()
Dim DOC1 As AcadDocument
Dim circleObj1 As AcadCircle
Dim circleObj2 As AcadCircle
Dim circleObj1Copy As AcadCircle
Dim circleObj2Copy As AcadCircle
Dim centerPoint(0 To 2) As Double
Dim radius1 As Double
Dim radius2 As Double
Dim radius1Copy As Double
Dim radius2Copy As Double
Dim objCollection(0 To 1) As Object
Dim retObjects As Variant
' Define the Circle object
centerPoint(0) = 0: centerPoint(1) = 0: centerPoint(2) = 0
radius1 = 5#: radius2 = 7#
radius1Copy = 1#: radius2Copy = 2#
' Create a new drawing
Set DOC1 = ThisDrawing.Application.Documents.Add
' Add two circles to the drawing
Set circleObj1 = DOC1.ModelSpace.AddCircle _
(centerPoint, radius1)
Set circleObj2 = DOC1.ModelSpace.AddCircle _
(centerPoint, radius2)
ZoomAll
' Put the objects to be copied into a form
' compatible with CopyObjects
Set objCollection(0) = circleObj1
Set objCollection(1) = circleObj2
' Copy object and get back a collection of
' the new objects (copies)
retObjects = DOC1.CopyObjects(objCollection)
' Get newly created object and apply
' new properties to the copies
Set circleObj1Copy = retObjects(0)
Set circleObj2Copy = retObjects(1)
circleObj1Copy.radius = radius1Copy
circleObj1Copy.Color = acRed
circleObj2Copy.radius = radius2Copy
circleObj2Copy.Color = acRed
ZoomAll
End Sub
Edit Objects
107
Sub Ch4_Copy_to_New_Drawing()
Dim DOC0 As AcadDocument
Dim circleObj1 As AcadCircle, circleObj2 As AcadCircle
Dim centerPoint(0 To 2) As Double
Dim radius1 As Double, radius2 As Double
Dim radius1Copy As Double, radius2Copy As Double
Dim objCollection(0 To 1) As Object
Dim retObjects As Variant
' Define the Circle object
centerPoint(0) = 0: centerPoint(1) = 0: centerPoint(2) = 0
radius1 = 5#: radius2 = 7#
radius1Copy = 1#: radius2Copy = 2#
' Add two circles to the current drawing
Set circleObj1 = ThisDrawing.ModelSpace.AddCircle _
(centerPoint, radius1)
Set circleObj2 = ThisDrawing.ModelSpace.AddCircle _
(centerPoint, radius2)
ThisDrawing.Application.ZoomAll
' Save pointer to the current drawing
Set DOC0 = ThisDrawing.Application.ActiveDocument
' Copy objects
'
' First put the objects to be copied into a form compatible
' with CopyObjects
Set objCollection(0) = circleObj1
Set objCollection(1) = circleObj2
' Create a new drawing and point to its model space
Dim Doc1MSpace As AcadModelSpace
Dim DOC1 As AcadDocument
Set DOC1 = Documents.Add
Set Doc1MSpace = DOC1.ModelSpace
' Copy the objects into the model space of the new drawing. A
' collection of the new (copied) objects is returned.
retObjects = DOC0.CopyObjects(objCollection, Doc1MSpace)
Dim circleObj1Copy As AcadCircle, circleObj2Copy As AcadCircle
' Get the newly created object collection and apply new
' properties to the copies.
Set circleObj1Copy = retObjects(0)
Set circleObj2Copy = retObjects(1)
circleObj1Copy.radius = radius1Copy
circleObj1Copy.Color = acRed
circleObj2Copy.radius = radius2Copy
circleObj2Copy.Color = acRed
ThisDrawing.Application.ZoomAll
Offset Objects
Offsetting an object creates a new object at a specified offset distance from
the original object. You can offset arcs, circles, ellipses, lines, lightweight
polylines, polylines, splines, and xlines.
To offset an object, use the Offset method provided for that object. The
only input to this method is the distance to offset the object. If this
distance is negative, it is interpreted by AutoCAD as being an offset to make
a smaller curve (that is, for an arc it would offset to a radius that is the
given distance less than the starting curves radius). If smaller has no
meaning, then AutoCAD would offset in the direction of smaller X,Y,Z
WCS coordinates. If the offset distance is invalid then an error is returned.
offset polylines
For many objects, the result of this operation will be a single new curve
(which may not be of the same type as the original curve). For example,
offsetting an ellipse will result in a spline because the result does fit the
equa- tion of an ellipse. In some cases it may be necessary for the offset
result to be several curves. Because of this, the method returns the new
object, or array of objects, as a variant.
For more information about offsetting objects, see Copy, Offset, or Mirror
Objects in the Users Guide.
Offset a polyline
This example creates a lightweight polyline and then offsets the polyline.
Edit Objects
109
Sub Ch4_OffsetPolyline()
' Create the polyline
Dim plineObj As AcadLWPolyline
Dim points(0 To 11) As Double
points(0) = 1: points(1) = 1
points(2) = 1: points(3) = 2
points(4) = 2: points(5) = 2
points(6) = 3: points(7) = 2
points(8) = 4: points(9) = 4
points(10) = 4: points(11) = 1
Set plineObj = ThisDrawing.ModelSpace. _
AddLightWeightPolyline(points)
plineObj.Closed = True
ZoomAll
' Offset the polyline
Dim offsetObj As Variant
offsetObj = plineObj.Offset(0.25)
ZoomAll
End Sub
Mirror Objects
Mirroring creates a mirror image copy of an object around an axis or mirror
line. You can mirror all drawing objects.
To mirror an object, use the Mirror method provided for that object. This
method requires two coordinates as input. The two coordinates specified
become the endpoints of the mirror line around which the base object is
reflected. In 3D, this line orients a mirroring plane perpendicular to the XY
plane of the UCS containing the mirror line.
Unlike the mirror command in AutoCAD, this method places the reflected
image into the drawing and retains the original object. (To remove the original object, use the Erase method.)
selected objects
mirror line
mirrored object
before mirroring
after mirroring
(MIRRTEXT=1)
after mirroring
(MIRRTEXT=0)
You can mirror a Viewport object in paper space, although doing so has no
effect on its model space view or on model space objects.
For more information about mirroring objects, see Copy, Offset, or Mirror
Objects in the Users Guide.
Mirror a polyline about an axis
This example creates a lightweight polyline and mirrors that polyline about
an axis. The newly created polyline is colored blue.
Sub Ch4_MirrorPolyline()
' Create the polyline
Dim plineObj As AcadLWPolyline
Dim points(0 To 11) As Double
points(0) = 1: points(1) = 1
points(2) = 1: points(3) = 2
points(4) = 2: points(5) = 2
points(6) = 3: points(7) = 2
points(8) = 4: points(9) = 4
points(10) = 4: points(11) = 1
Set plineObj = ThisDrawing.ModelSpace. _
AddLightWeightPolyline(points)
plineObj.Closed = True
ZoomAll
' Define the mirror axis
Dim point1(0 To 2) As Double
Dim point2(0 To 2) As Double
point1(0) = 0: point1(1) = 4.25: point1(2) = 0
point2(0) = 4: point2(1) = 4.25: point2(2) = 0
' Mirror the polyline
Dim mirrorObj As AcadLWPolyline
Set mirrorObj = plineObj.Mirror(point1, point2)
Dim col As New AcadAcCmColor
Call col.SetRGB(125, 175, 235)
mirrorObj.TrueColor = col
ZoomAll
End Sub
Array Objects
You can copy an object in polar or rectangular arrays. For polar arrays, you
control the number of copies of the object and the angle to fill the array to.
For rectangular arrays, you control the number of rows and columns and the
distance between them.
For more information about arrays, see Create an Array of Objects in the
Users Guide.
(0,0,0)
Sub Ch4_ArrayingACircle()
' Create the circle
Dim circleObj As AcadCircle
Dim center(0 To 2) As Double
Dim radius As Double
center(0) = 2#: center(1) = 2#: center(2) = 0#
radius = 1
Set circleObj = ThisDrawing.ModelSpace. _
AddCircle(center, radius)
ZoomAll
' Define the polar array
Dim noOfObjects As Integer
Dim angleToFill As Double
Dim basePnt(0 To 2) As Double
noOfObjects = 4
angleToFill = 3.14
' 180 degrees
basePnt(0) = 4#: basePnt(1) = 4#: basePnt(2) = 0#
' The following example will create 4 copies
' of an object by rotating and copying it about
' the point (3,3,0).
Dim retObj As Variant
retObj = circleObj.ArrayPolar _
(noOfObjects, angleToFill, basePnt)
ZoomAll
End Sub
rectangular array
a
base object
b
Sub Ch4_ArrayRectangularExample()
' Create the circle
Dim circleObj As AcadCircle
Dim center(0 To 2) As Double
Dim radius As Double
center(0) = 2#: center(1) = 2#: center(2) = 0#
radius = 0.5
Set circleObj = ThisDrawing.ModelSpace. _
AddCircle(center, radius)
ZoomAll
' Define the rectangular array
Dim numberOfRows As Long
Dim numberOfColumns As Long
Dim numberOfLevels As Long
Dim distanceBwtnRows As Double
Dim distanceBwtnColumns As Double
Dim distanceBwtnLevels As Double
numberOfRows = 5
numberOfColumns = 5
numberOfLevels = 2
distanceBwtnRows = 1
distanceBwtnColumns = 1
distanceBwtnLevels = 1
' Create the array of objects
Dim retObj As Variant
retObj = circleObj.ArrayRectangular _
(numberOfRows, numberOfColumns, numberOfLevels, _
distanceBwtnRows, distanceBwtnColumns, distanceBwtnLevels)
ZoomAll
End Sub
Move Objects
You can move objects along a vector without changing their orientation or
size. You can also rotate objects around a base point.
For more information about moving objects, see Move Objects in the Users
Guide.
1
select object
2
select object with two points indicated
moved object
Rotate Objects
You can rotate all drawing objects and attribute reference objects.
To rotate an object, use the Rotate method provided for that object. This
method requires as input a base point and a rotation angle. The base point
is a variant array with three doubles. These doubles represent a 3D WCS
coor- dinate specifying the point through which the axis of rotation is
defined. The angle of rotation is specified in radians. This angle determines
how far an object rotates around the base point relative to its current
location.
selected objects
rotation angle
rotated object
For more information about rotating objects, see Rotate Objects in the
Users Guide.
Rotate a polyline about a base point
This example creates a closed lightweight polyline, and then rotates the
polyline 45 degrees about the base point (4, 4.25, 0).
Sub Ch4_RotatePolyline()
' Create the polyline
Dim plineObj As AcadLWPolyline
Dim points(0 To 11) As Double
points(0) = 1: points(1) = 2
points(2) = 1: points(3) = 3
points(4) = 2: points(5) = 3
points(6) = 3: points(7) = 3
points(8) = 4: points(9) = 4
points(10) = 4: points(11) = 2
Set plineObj = ThisDrawing.ModelSpace. _
AddLightWeightPolyline(points)
plineObj.Closed = True
ZoomAll
' Define the rotation of 45 degrees about a
' base point of (4, 4.25, 0)
Dim basePoint(0 To 2) As Double
Dim rotationAngle As Double
basePoint(0) = 4: basePoint(1) = 4.25: basePoint(2) = 0
rotationAngle = 0.7853981
' 45 degrees
' Rotate the polyline
plineObj.Rotate basePoint, rotationAngle
plineObj.Update
End Sub
Delete Objects
You can delete individual objects by using the Delete method.
Scale Objects
You scale an object by specifying a base point and a length, which is used as
a scale factor based on the current drawing units. You can scale all the drawing objects, as well as attribute reference objects.
To scale an object, use the ScaleEntity method provided for that object. This
method scales the object equally in the X, Y, and Z directions. It takes as
input the base point for the scale and a scale factor. The base point is a
variant array with three doubles. These doubles represent a 3D WCS
coordinate spec- ifying the point from which the scale begins. The scale
factor is the factor by which to scale the object. The dimensions of the
object are multiplied by the scale factor. A scale factor greater than 1
enlarges the object. A scale factor between 0 and 1 reduces the object.
scale factor = .5
scale factor = 2
For more information about scaling, see Resize or Reshape Objects in the
Users Guide.
Scale a polyline
This example creates a closed lightweight polyline and then scales the
polyline by 0.5.
Sub Ch4_ScalePolyline()
' Create the polyline
Dim plineObj As AcadLWPolyline
Dim points(0 To 11) As Double
points(0) = 1: points(1) = 2
points(2) = 1: points(3) = 3
points(4) = 2: points(5) = 3
points(6) = 3: points(7) = 3
points(8) = 4: points(9) = 4
points(10) = 4: points(11) = 2
Set plineObj = ThisDrawing.ModelSpace. _
AddLightWeightPolyline(points)
plineObj.Closed = True
ZoomAll
' Define the scale
Dim basePoint(0 To 2) As Double
Dim scalefactor As Double
basePoint(0) = 4: basePoint(1) = 4.25: basePoint(2) = 0
scalefactor = 0.5
' Scale the polyline
plineObj.ScaleEntity basePoint, scalefactor
plineObj.Update
End Sub
Transform Objects
You move, scale, or rotate an object given a 4 4 transformation matrix
using the TransformBy method.
The following table demonstrates the transformation matrix configuration,
where R = Rotation and T = Translation:
Transformation matrix configuration
R00
R01
R02
T0
R10
R11
R12
T1
R20
R21
R22
T2
To transform an object, first initialize the transformation matrix. The following example shows a transformation matrix, assigned to the variable
tMatrix, which will rotate an entity by 90 degrees about the point (0, 0, 0):
tMatrix(0,0)
tMatrix(0,1)
tMatrix(0,2)
tMatrix(0,3)
tMatrix(1,0)
tMatrix(1,1)
tMatrix(1,2)
tMatrix(1,3)
tMatrix(2,0)
tMatrix(2,1)
tMatrix(2,2)
tMatrix(2,3)
tMatrix(3,0)
tMatrix(3,1)
tMatrix(3,2)
tMatrix(3,3)
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
0.0
-1.0
0.0
0.0
1.0
0.0
0.0
0.0
0.0
0.0
1.0
0.0
0.0
0.0
0.0
1.0
After the transformation matrix is complete, apply the matrix to the object
using the TransformBy method. The following line of code demonstrates
applying a matrix (tMatrix) to an object (anObj):
anObj.TransformBy tMatrix
Sub Ch4_TransformBy()
' Create a line
Dim lineObj As AcadLine
Dim startPt(0 To 2) As Double
Dim endPt(0 To 2) As Double
startPt(0) = 2
startPt(1) = 1
startPt(2) = 0
endPt(0) = 5
endPt(1) = 1
endPt(2) = 0
Set lineObj = ThisDrawing.ModelSpace. _
AddLine(startPt, endPt)
ZoomAll
' Initialize the transMat variable with a
' transformation matrix that will rotate
' an object by 90 degrees about the point(0,0,0)
Dim transMat(0 To 3, 0 To 3) As Double
transMat(0, 0) = 0#: transMat(0, 1) = -1#
transMat(0, 2) = 0#: transMat(0, 3) = 0#
transMat(1, 0) = 1#: transMat(1, 1) = 0#
transMat(1, 2) = 0#: transMat(1, 3) = 0#
transMat(2, 0) = 0#: transMat(2, 1) = 0#
transMat(2, 2) = 1#: transMat(2, 3) = 0#
transMat(3, 0) = 0#: transMat(3, 1) = 0#
transMat(3, 2) = 0#: transMat(3, 3) = 1#
' Transform the line using the defined transformation matrix
lineObj.TransformBy transMat
lineObj.Update
End Sub
1.0
0.0
0.0
1.0
0.0
0.0
0.0
0.0
0.0
1.0
0.0
0.0
0.0
0.0
1.0
0.707107
0.707107
0.0
5.0
0.707107
0.707107
0.0
2.071068
0.0
1.0
0.0
0.0
0.0
0.0
1.0
1.0
0.0
0.0
10.0
0.0
1.0
0.0
10.0
0.0
0.0
1.0
0.0
0.0
0.0
0.0
1.0
10.0
0.0
0.0
0.0
0.0
10.0
0.0
0.0
0.0
0.0
10.0
0.0
0.0
0.0
0.0
1.0
10.0
0.0
0.0
18.0
0.0
10.0
0.0
18.0
0.0
0.0
10.0
0.0
0.0
0.0
0.0
1.0
You can extend or trim an object by editing its properties. For example, to
lengthen a line, simply change the coordinates of the StartPoint or
EndPoint properties. To change the angle of an arc, change the StartAngle or
EndAngle properties of the arc. Once you have altered an objects property
or proper- ties, use the Update method to see your changes in the drawing.
For more information about extending and trimming objects, see Resize or
Reshape Objects in the Users Guide.
Lengthen a line
This example creates a line then changes the endpoint of that line resulting
in a longer line.
Sub Ch4_LengthenLine()
' Define and create the line
Dim lineObj As AcadLine
Dim startPoint(0 To 2) As Double
Dim endPoint(0 To 2) As Double
startPoint(0) = 0
startPoint(1) = 0
startPoint(2) = 0
endPoint(0) = 1
endPoint(1) = 1
endPoint(2) = 1
Set lineObj = ThisDrawing.ModelSpace. _
AddLine(startPoint, endPoint)
lineObj.Update
' Lengthen the line by changing the
' endpoint to 4, 4, 4
endPoint(0) = 4
endPoint(1) = 4
endPoint(2) = 4
lineObj.endPoint = endPoint
lineObj.Update
End Sub
Explode Objects
Exploding objects converts the objects from single objects to their constituent parts but has no visible effect. For example, exploding forms simple lines
and arcs from 3D polygons, polylines, polygon meshes, and regions. It
replaces a block reference with copies of the simple objects that compose
the block.
For more information about exploding objects, see Disassociate Compound
Objects (Explode) in the Users Guide.
Explode a polyline
This example creates a lightweight polyline object. It then explodes the
polyline into separate objects. The example then loops through the
resulting objects and displays a message box containing the name of each
object and its index in the list of exploded objects.
Sub Ch4_ExplodePolyline()
Dim plineObj As AcadLWPolyline
Dim points(0 To 11) As Double
' Define the 2D polyline points
points(0) = 1: points(1) = 1
points(2) = 1: points(3) = 2
points(4) = 2: points(5) = 2
points(6) = 3: points(7) = 2
points(8) = 4: points(9) = 4
points(10) = 4: points(11) = 1
' Create a light weight Polyline object
Set plineObj = ThisDrawing.ModelSpace. _
AddLightWeightPolyline(points)
' Set the bulge on one segment to vary the
' type of objects in the polyline
plineObj.SetBulge 3, -0.5
plineObj.Update
' Explode the polyline
Dim explodedObjects As Variant
explodedObjects = plineObj.Explode
' Loop through the exploded objects
' and display a message box with
' the type of each object
Dim I As Integer
For I = 0 To UBound(explodedObjects)
explodedObjects(I).Color = acRed
explodedObjects(I).Update
MsgBox "Exploded Object " & I & ": " & _
explodedObjects(I).ObjectName
explodedObjects(I).Color = acByLayer
explodedObjects(I).Update
Next
End Sub
Edit Polylines
2D and 3D polylines, rectangles, polygons, and 3D polygon meshes are all
polyline variants and are edited in the same way.
Coordinates
property
AddVertex
method
SetWidth
Sub Ch4_EditPolyline()
Dim plineObj As AcadLWPolyline
Dim points(0 To 9) As Double
' Define the 2D polyline
points(0) = 1: points(1)
points(2) = 1: points(3)
points(4) = 2: points(5)
points(6) = 3: points(7)
points(8) = 4: points(9)
points
= 1
= 2
= 2
= 2
= 4
Edit Splines
Use the following editable properties to change splines:
Closed
ControlPoints
EndTangent
FitPoints
FitTolerance
Knots
StartTangent
DeleteFitPoint
ElevateOrder
GetFitPoint
Reverse
SetControlPoint
SetFitPoint
Sets the fit point of the spline at a given index. (Sets one
fit point only. To change all the fit points of the spline,
use the FitPoints property.)
SetWeight
Area
IsPeriodic
IsPlanar
IsRational
NumberOfControlPoints
Gets the number of control points of the spline.
NumberOfFitPoints
Gets the number of fit points of the spline.
For more information about editing splines, see Modify Splines in the
Users Guide.
Edit Hatches
You can edit both hatch boundaries and hatch patterns. If you edit the
boundary of an associative hatch, the pattern is updated as long as the editing results in a valid boundary. Associative hatches are updated even if
theyre on layers that are turned off. You can modify hatch patterns or
choose a new pattern for an existing hatch, but associativity can only be set
when a hatch is created. You can check to see if a Hatch object is associative
by using the AssociativeHatch property. (See the AddHatch method for more
information on creating a hatch.)
You must re-evaluate a hatch using the Evaluate method to see any edits
to the hatch.
For more information about editing hatches, see Modify Hatches and SolidFilled Areas in the Users Guide.
Sub Ch4_AppendInnerLoopToHatch()
Dim hatchObj As AcadHatch
Dim patternName As String
Dim PatternType As Long
Dim bAssociativity As Boolean
' Define and create the hatch
patternName = "ANSI31"
PatternType = 0
bAssociativity = True
Set hatchObj = ThisDrawing.ModelSpace. _
AddHatch(PatternType, patternName, bAssociativity)
' Create the outer loop for the hatch.
Dim outerLoop(0 To 1) As AcadEntity
Dim center(0 To 2) As Double
Dim radius As Double
Dim startAngle As Double
Dim endAngle As Double
center(0) = 5: center(1) = 3: center(2) = 0
radius = 3
startAngle = 0
endAngle = 3.141592
Set outerLoop(0) = ThisDrawing.ModelSpace. _
AddArc(center, radius, startAngle, endAngle)
Set outerLoop(1) = ThisDrawing.ModelSpace. _
AddLine(outerLoop(0).startPoint, outerLoop(0).endPoint)
' Append the outer loop to the hatch object
hatchObj.AppendOuterLoop (outerLoop)
' Create a circle as the inner loop for the hatch.
Dim innerLoop(0) As AcadEntity
center(0) = 5: center(1) = 4.5: center(2) = 0
radius = 1
Set innerLoop(0) = ThisDrawing.ModelSpace. _
AddCircle(center, radius)
' Append the circle as an inner loop to the hatch
hatchObj.AppendInnerLoop (innerLoop)
' Evaluate and display the hatch
hatchObj.Evaluate
ThisDrawing.Regen True
End Sub
PatternDouble
PatternName
PatternScale
PatternSpace
SetPattern
Sets the pattern name and pattern type for the hatch.
Sub Ch4_ChangeHatchPatternSpace()
Dim hatchObj As AcadHatch
Dim patternName As String
Dim PatternType As Long
Dim bAssociativity As Boolean
' Define the hatch
patternName = "ANSI31"
PatternType = 0
bAssociativity = True
' Create the associative Hatch object
Set hatchObj = ThisDrawing.ModelSpace. _
AddHatch(PatternType, patternName, bAssociativity)
' Create the outer loop for the hatch.
Dim outerLoop(0 To 0) As AcadEntity
Dim center(0 To 2) As Double
Dim radius As Double
center(0) = 5
center(1) = 3
center(2) = 0
radius = 3
Set outerLoop(0) = ThisDrawing.ModelSpace. _
AddCircle(center, radius)
hatchObj.AppendOuterLoop (outerLoop)
hatchObj.Evaluate
' Change the spacing of the hatch pattern by
' adding 2 to the current spacing
hatchObj.patternSpace = hatchObj.patternSpace + 2
hatchObj.Evaluate
ThisDrawing.Regen True
End Sub
For more information about creating layers, see Create and Name Layers
in the Users Guide.
Create a new layer, assign it the color red, and add an object to the layer
The following code creates a circle and a new layer. The new layer is
assigned the color red. The circle is assigned to the layer, and the color of
the circle changes accordingly.
Sub Ch4_NewLayer()
' Create a circle
Dim circleObj As AcadCircle
Dim center(0 To 2) As Double
Dim radius As Double
center(0) = 2: center(1) = 2: center(2) = 0
radius = 1
Set circleObj = ThisDrawing.ModelSpace. _
AddCircle(center, radius)
' Assign the circle the color "ByLayer" so
' that the circle will automatically pick
' up the color of the layer on which it resides
circleObj.Color = acByLayer
' Create a new layer called "ABC"
Dim layerObj As AcadLayer
Set layerObj = ThisDrawing.Layers.Add("ABC")
' Assign the "ABC" layer the color red
layerObj.Color = acRed
' Assign the circle to the "ABC" layer
circleObj.Layer = "ABC"
circleObj.Update
End Sub
To freeze or thaw a layer, use the Freeze property. If you input a value of
TRUE to this property, the layer is frozen. If you input a value of FALSE, the
layer is thawed.
For more information about freezing and thawing layers, see Control the
Visibility of Objects on a Layer in the Users Guide.
Freeze a layer
This example creates a new layer called ABC and then freezes the layer.
Sub Ch4_LayerFreeze()
' Create a new layer called "ABC"
Dim layerObj As AcadLayer
Set layerObj = ThisDrawing.Layers.Add("ABC")
' Freeze layer "ABC"
layerObj.Freeze = True
End Sub
Delete Layers
To delete a layer, use the Delete method.
You can delete a layer at any time during a drawing session. You cannot
delete the current layer, layer 0, an xref-dependent layer, or a layer that contains objects.
Note
Color name
Red
Yellow
Green
Cyan
Blue
Magenta
Black/White
Note The linetypes used internally by AutoCAD should not be confused with
the hardware linetypes provided by some plotters. The two types of dashed
lines produce similar results. Do not use both types at the same time, however,
because the results can be unpredictable.
Load a linetype into AutoCAD
This example attempts to load the linetype CENTER from the acad.lin file.
If the linetype already exists, or the file does not exist, then a message is
displayed.
Sub Ch4_LoadLinetype()
On Error GoTo ERRORHANDLER
Dim linetypeName As String
linetypeName = "CENTER"
' Load "CENTER" line type from acad.lin file
ThisDrawing.Linetypes.Load linetypeName, "acad.lin"
Exit Sub
ERRORHANDLER:
MsgBox Err.Description
End Sub
ThisDrawing.ActiveLinetype = ThisDrawing. _
Linetypes.Item("CONTINUOUS")
For more information about activating a linetype, see Set the Current Linetype in the Users Guide.
Rename Linetypes
To rename a linetype, use the Name property. When you rename a linetype,
you are renaming only the linetype definition in your drawing. The name in
the LIN library file is not being updated to reflect the new name.
Delete Linetypes
To delete a linetype, use the Delete method. You can delete a linetype at any
time during a drawing session; however, linetypes that cannot be deleted
include BYLAYER, BYBLOCK, CONTINUOUS, the current linetype, and xrefdependent linetypes. Also, linetypes referenced by block definitions cannot
be deleted, even if they are not used by any objects.
For more information about deleting linetypes, see Load Linetypes in the
Users Guide.
For more information about linetype scales, see Control Linetype Scale in
the Users Guide.
Change the linetype scale for a circle
Sub Ch4_ChangeLinetypeScale()
' Save the current linetype
Set currLineType = ThisDrawing.ActiveLinetype
' Change the active linetype to Border, so the scale change will
' be visible.
' First see if the Border linetype is already loaded
On Error Resume Next
'Turn on error trapping
ThisDrawing.ActiveLinetype = ThisDrawing.Linetypes.Item("BORDER")
If Err.Number = -2145386476 Then
' Error indicates linetype is not currently loaded, so load it.
ThisDrawing.Linetypes.Load "BORDER", "acad.lin"
ThisDrawing.ActiveLinetype = _
ThisDrawing.Linetypes.Item("BORDER")
End If
On Error GoTo 0
'Turn off error trapping
' Create a circle object in model space
Dim center(0 To 2) As Double
Dim radius As Double
Dim circleObj As AcadCircle
center(0) = 2
center(1) = 2
center(2) = 0
radius = 4
Set circleObj = ThisDrawing.ModelSpace.AddCircle(center, radius)
circleObj.Update
MsgBox ("Here is the circle with the original linetype")
' Set the linetype scale of a circle to 3
circleObj.LinetypeScale = 3#
circleObj.Update
MsgBox ("Here is the circle with the new linetype")
' Restore original active linetype
ThisDrawing.ActiveLinetype = currLineType
End Sub
The number of layers in a drawing and the number of objects per layer are
virtually unlimited. You can assign a name to each layer and select any combination of layers for display.
You can define blocks from objects that were originally drawn on different
layers with different colors and linetypes. You can preserve the layer, color,
and linetype information of objects in a block. Then, each time you insert
the block, you have each object drawn on its original layer with its original
color and linetype.
Setting a color for the object overrides the color setting for the layer on
which the object resides. If you want to retain an object on a specific layer
but you dont want it to keep the color of that layer, you can change the
objects color.
Change the color of a circle
This example creates a circle and then colors the circle blue.
Sub Ch4_ColorCircle()
Dim color As AcadAcCmColor
Set color = _
AcadApplication.GetInterfaceObject("AutoCAD.AcCmColor.16")
Call color.SetRGB(80, 100, 244)
Dim circleObj As AcadCircle
Dim centerPoint(0 To 2) As Double
Dim radius As Double
centerPoint(0) = 0#: centerPoint(1) = 0#: centerPoint(2) = 0#
radius = 5#
Set circleObj = _
ThisDrawing.ModelSpace.AddCircle(centerPoint, radius)
circleObj.TrueColor = color
ZoomAll
End Sub
Note Before you can assign a linetype to an object, the linetype must be
loaded into the current drawing. To load a linetype into the drawing, use the
Load method.
For more information about linetypes, see Overview of Linetypes in the
Users Guide.
Change the linetype of a circle
This example creates a circle. It then attempts to load the linetype CENTER
from the acad.lin file. If the linetype already exists, or the file does not exist,
then a message is displayed. Finally, it sets the linetype for the circle to be
CENTER.
Sub Ch4_ChangeCircleLinetype()
On Error Resume Next
' Create a circle
Dim circleObj As AcadCircle
Dim center(0 To 2) As Double
Dim radius As Double
center(0) = 2: center(1) = 2: center(2) = 0
radius = 1
Set circleObj = ThisDrawing.ModelSpace. _
AddCircle(center, radius)
Dim linetypeName As String
linetypeName = "CENTER"
' Load "CENTER" line type from acad.lin file
ThisDrawing.Linetypes.Load linetypeName, "acad.lin"
If Err.Description <> "" Then MsgBox Err.Description
' Assign the circle the linetype "CENTER"
circleObj.Linetype = "CENTER"
circleObj.Update
End Sub
Each time you save another layer setting in the drawing, AutoCAD creates
another XRecord object describing the saved settings and stores the XRecord
in the ACAD_LAYERSTATE dictionary. The following diagram illustrates the
process.
AutoCAD Document
Object
Layers Collection
ACAD_LAYERSTATE
Ext Dictionary
layer1
layer2
layer3
Dictionary Object
COLOR_LINETYPE
layer settings
PLOTSTYLE_LINEWEIGHT
layer settings
XRecord
XRecord
You do not need (and should not try) to interpret XRecords when
working with layer settings using ActiveX. Use the functions of the
LayerStateMan- ager object to access saved layer settings.
List the saved layer settings in a drawing
If layer settings have been saved in the current drawing, the following code
lists the names of all saved layer settings:
Sub Ch4_ListStates()
On Error Resume Next
Dim oLSMDict As AcadDictionary
Dim XRec As Object
Dim layerstateNames As String
layerstateNames = ""
' Get the ACAD_LAYERSTATES dictionary, which is in the
' extension dictionary in the Layers object.
Set oLSMDict = ThisDrawing.Layers. _
GetExtensionDictionary.Item("ACAD_LAYERSTATES")
' List the name of each saved layer setting. Settings are
' stored as XRecords in the dictionary.
For Each XRec In oLSMDict
layerstateNames = layerstateNames + XRec.Name + vbCrLf
Next XRec
MsgBox "The saved layer settings in this drawing are: " + _
vbCrLf + layerstateNames
End Sub
Export
Import
Rename
Restore
Save
SetDataBase
After you retrieve the LayerStateManager object, you must associate a database with it before you can access the objects methods. Use the
SetDatabase method to associate a database with the LayerStateManager.
oLSM.SetDatabase ThisDrawing.Database
acLsColor
Color
acLsFrozen
Frozen or thawed
acLsLineType
Linetype
acLsLineWeight
Lineweight
acLsLocked
Locked or unlocked
acLsNewViewport
acLsNone
None
acLsOn
On or off
acLsPlot
Plotting on or off
acLsPlotStyle
Plot style
Note Importing layer settings does not restore them; you must use the
Restore method to set the layers in your drawing to the imported settings.
The Export method accepts two parameters. The first parameter is a string
identifying the saved layer settings you are exporting. The second parameter
is the name of the file you are exporting the settings to. If you do not
specify a path for the file, it is saved in the AutoCAD installation directory.
If the file name you specified already exists, the existing file is overwritten.
Use a .las extension when naming files; this is the extension AutoCAD
recognizes for exported layer setting files.
The Import method accepts one parameter: a string naming the file that contains the layer settings you are importing.
When you are importing layer settings, an error condition is raised if any
properties referenced in the saved settings are not available in the drawing
youre importing to. The import is completed, however, and default properties are used. For example, if an exported layer is set to a linetype that is not
loaded in the drawing it is being imported into, an error condition is raised
and the drawings default linetype is substituted. Your code should account
for this error condition and continue processing if it is raised.
If the imported file defines settings for layers that do not exist in the
current drawing, those layers are created in the current drawing. When you
use the Restore method, the properties specified when the settings were
saved are assigned to the new layers; all other properties of the new layers
are assigned default settings.
Add Text to
Drawings
Text conveys important information in your drawing. Use text for title
blocks, to label parts of the drawing, to give specifications, or to make
annotations.
AutoCAD provides various ways to create text. For short, simple entries, use
line text. For longer entries with internal formatting, use multiline text
(mtext). Although all entered text uses the current text style, which establishes the default font and format settings, you can use several methods to
customize the text appearance.
For more information about working with text, see Notes and Labels, in
the Users Guide.
BigFontFile
Specifies the special shape definition file used for a nonASCII character set.
Height
Width
ObliqueAngle
TextGenerationFlag
Specifies backward text, upside-down text, or both.
If you change an existing styles font or orientation, all text using that style
is changed to use the new font or orientation. Changing text height, width
factor, and oblique angle does not change existing text but does change subsequently created text objects.
Note You must call the Regen or Update methods to see any changes to
the above properties.
For more information about creating text styles, see Create and Modify Text
Styles in the Users Guide.
Assign Fonts
Fonts define the shapes of the text characters that make up each character
set. A single font can be used by more than one style. To assign a font to a
text style, use the FontFile property of the TextStyle object. By entering the
font file containing an AutoCAD-compiled SHX font, you assign that font to
the text style.
For more information about assigning fonts to text styles, see Assign Text
Fonts in the Users Guide.
Set text fonts
This example gets the current font values for the active text style and then
changes the typeface for the font to PlayBill. The new font is then set
using the SetFont method. To see the effects of changing the typeface, add
some MText or Text to your current drawing before running the example.
Note that, if you dont have the PlayBill font on your system, you need to
substi- tute a font you do have in order for this example to work.
Sub Ch4_UpdateTextFont()
MsgBox ("Look at the text now...")
Dim
Dim
Dim
Dim
Dim
Dim
typeFace As String
SavetypeFace As String
Bold As Boolean
Italic As Boolean
charSet As Long
PitchandFamily As Long
Use
Fonts
TrueType
TrueType fonts always appear filled in your drawing, however, when you
plot, the TEXTFILL system variable controls whether the fonts are filled. By
default TEXTFILL is set to 1 to plot the filled-in fonts. When you export the
drawing to PostScript format with the Export method and print it on
a
PostScript device, the font is plotted as designed.
For more information about using TrueType fonts, see Assign Text Fonts
in the Users Guide.
Sub Ch4_ChangeTextHeight()
Dim textObj As AcadText
Dim textString As String
Dim insertionPoint(0 To 2) As Double
Dim height As Double
' Define the text object
textString = "Hello, World."
insertionPoint(0) = 3
insertionPoint(1) = 3
insertionPoint(2) = 0
height = 0.5
' Create the text object in model space
Set textObj = ThisDrawing.ModelSpace. _
AddText(textString, insertionPoint, height)
' Change the value of the Height to 1
textObj.height = 1
textObj.Update
End Sub
Sub Ch4_ObliqueText()
Dim textObj As AcadText
Dim textString As String
Dim insertionPoint(0 To 2) As Double
Dim height As Double
' Define the text object
textString = "Hello, World."
insertionPoint(0) = 3
insertionPoint(1) = 3
insertionPoint(2) = 0
height = 0.5
' Create the text object in model space
Set textObj = ThisDrawing.ModelSpace. _
AddText(textString, insertionPoint, height)
' Change the value of the ObliqueAngle
' to 45 degrees (.707 radians)
textObj.ObliqueAngle = 0.707
textObj.Update
End Sub
Sub Ch4_ChangingTextGenerationFlag()
Dim textObj As AcadText
Dim textString As String
Dim insertionPoint(0 To 2) As Double
Dim height As Double
' Create the text object
textString = "Hello, World."
insertionPoint(0) = 3
insertionPoint(1) = 3
insertionPoint(2) = 0
height = 0.5
Set textObj = ThisDrawing.ModelSpace. _
AddText(textString, insertionPoint, height)
' Change the value of the TextGenerationFlag
textObj.TextGenerationFlag = acTextFlagBackward
textObj.Update
End Sub
Sub Ch4_CreateText()
Dim textObj As AcadText
Dim textString As String
Dim insertionPoint(0 To 2) As Double
Dim height As Double
' Create the text object
textString = "Hello, World."
insertionPoint(0) = 2
insertionPoint(1) = 2
insertionPoint(2) = 0
height = 0.5
Set textObj = ThisDrawing.ModelSpace. _
AddText(textString, insertionPoint, height)
textObj.Update
End Sub
InsertionPoint
ObliqueAngle
Rotation
ScaleFactor
TextAlignmentPoint
Specifies the alignment point for the text.
TextGenerationFlag
Specifies whether the text is displayed backward,
upside-down, or both simultaneously.
TextString
Once you have changed a property, use the Update method to see the
changes in your drawing.
Note For a complete list of methods and properties, see the Text object
docu- mentation in the AutoCAD ActiveX and VBA Reference.
For more information about formatting line text, see Work with Text Styles
in the Users Guide.
Sub Ch4_TextAlignment()
Dim textObj As AcadText
Dim textString As String
Dim insertionPoint(0 To 2) As Double
Dim height As Double
' Define the new Text object
textString = "Hello, World."
insertionPoint(0) = 3
insertionPoint(1) = 3
insertionPoint(2) = 0
height = 0.5
' Create the Text object in model space
Set textObj = ThisDrawing.ModelSpace. _
AddText(textString, insertionPoint, height)
' Create a point over the text alignment point,
' so we can better visualize the alignment process
Dim pointObj As AcadPoint
Dim alignmentPoint(0 To 2) As Double
alignmentPoint(0) = 3
alignmentPoint(1) = 3
alignmentPoint(2) = 0
Set pointObj = ThisDrawing.ModelSpace. _
AddPoint(alignmentPoint)
pointObj.Color = acRed
' Set the point style to crosshair
ThisDrawing.SetVariable "PDMODE", 2
' Align the text to the Left
textObj.Alignment = acAlignmentLeft
ThisDrawing.Regen acActiveViewport
MsgBox "The Text object is now aligned left"
' Align the text to the Center
textObj.Alignment = acAlignmentCenter
' Align the text to the point (necessary for
' all but left aligned text.)
textObj.TextAlignmentPoint = alignmentPoint
ThisDrawing.Regen acActiveViewport
MsgBox "The Text object is now centered"
' Align the text to the Right
textObj.Alignment = acAlignmentRight
ThisDrawing.Regen acActiveViewport
MsgBox "The Text object is now aligned right"
End Sub
ArrayRectangular
Creates a rectangular.
Copy
Erase
Mirror
Move
Rotate
Once the MText object is created, you can apply the text height,
justification, rotation angle, and style to the MText object, or apply
character formatting to selected characters.
Refer to the entry on MText in the ActiveX and VBA Reference for a list of
methods and properties that apply to the MText object.
For more information about creating multiline text, see Create Multiline
Text in the Users Guide.
Create Multiline Text
The following code creates an MText object in model space, at the
coordinate
(2, 2, 0).
Sub Ch4_CreateMText()
Dim mtextObj As AcadMText
Dim insertPoint(0 To 2) As Double
Dim width As Double
Dim textString As String
insertPoint(0) = 2
insertPoint(1) = 2
insertPoint(2) = 0
width = 4
textString = "This is a text string for the mtext object."
' Create a text Object in model space
Set mtextObj = ThisDrawing.ModelSpace. _
AddMText(insertPoint, width, textString)
ZoomAll
End Sub
Sub Ch4_FormatMText()
Dim mtextObj As AcadMText
Dim insertPoint(0 To 2) As Double
Dim width As Double
Dim textString As String
insertPoint(0) = 2
insertPoint(1) = 2
insertPoint(2) = 0
width = 4
' Define the ASCII characters for the control characters
Dim OB As Long ' Open Bracket {
Dim CB As Long ' Close Bracket }
Dim BS As Long ' Back Slash
\
Dim FS As Long ' Forward Slash /
Dim SC As Long ' Semicolon
;
OB = Asc("{")
CB = Asc("}")
BS = Asc("\")
FS = Asc("/")
SC = Asc(";")
' Assign the text string the following line of control
' characters and text characters:
' {{\H1.5x; Big text}\A2; over text\A1;/\A0; under text}
textString = Chr(OB) + Chr(OB) + Chr(BS) + "H1.5x" _
+ Chr(SC) + "Big text" + Chr(CB) + Chr(BS) + "A2" _
+ Chr(SC) + "over text" + Chr(BS) + "A1" + Chr(SC) _
+ Chr(FS) + Chr(BS) + "A0" + Chr(SC) + "under text" _
+ Chr(CB)
' Create a text Object in model space
Set mtextObj = ThisDrawing.ModelSpace. _
AddMText(insertPoint, width, textString)
ZoomAll
End Sub
Use Unicode
Codes, and
Special
Characters
Characters,
Control
You can use Unicode characters, control codes, and special characters in your
text string to represent symbols. (All non-text characters must be entered as
their ASCII equivalent.)
Description
\U+00B0
Degree symbol
\U+00B1
\U+2205
These control codes work with standard AutoCAD text fonts only:
Control code descriptions
Control code
Description
%%o
%%u
%%d
%%p
%%c
%%%
Substitute Fonts
You can designate fonts to be substituted for other fonts or as defaults when
AutoCAD cannot find a font specified in a drawing.
The fonts used for the text in your drawing are determined by the text style
and, for mtext, by individual font formats applied to sections of text.
You can use font mapping tables to ensure that your drawing uses only certain fonts, or to convert the fonts you used to other fonts. You can use
these font mapping tables to enforce corporate font standards, or to
facilitate offline printing. AutoCAD comes with a default font mapping
table. You can edit this file using any ASCII text editor. You also can specify
a different font mapping table file by using the FontFileMap property on
the Preferences object.
For more information about font mapping tables and substituting fonts, see
Substitute Fonts in the Users Guide.
Check Spelling
During a spelling check, AutoCAD matches the words in the drawing to the
words in the current main dictionary. Any words you add are stored in the
custom dictionary that is current at the time of the spelling check. For
exam- ple, you can add proper names so that AutoCAD no longer identifies
them as misspelled words.
168
Dimensions and
Tolerances
In this chapter
Dimensioning Concepts
Create Dimensions
Edit Dimensions
Work with Dimension
Styles
Dimension in Model
Space and
Paper
Space
Annotation
169
Dimensioning Concepts
Dimensions show the geometric measurements of objects, the distances or
angles between objects, or the X and Y coordinates of a feature. AutoCAD
provides three basic types of dimensioning: linear, radial, and angular.
Linear
dimensions include aligned, rotated, and
ordinate
dimensions.
angular
horizontal
aligned
diameter
vertical
radius
continued
baseline
You can create dimensions for lines, multilines, arcs, circles, and polyline
seg- ments, or you can create dimensions that standalone.
AutoCAD draws dimensions on the current layer. Every dimension has a
dimension style associated with it, whether its the default or one you
define. The style controls characteristics such as color, text style, and
linetype scale. Thickness information is not supported. Style families allow
for subtle mod- ifications to a base style for different types of dimensions.
Overrides allow for style modifications to a specific dimension.
For more information about dimensions, see Dimensions and Tolerances,
in the Users Guide.
Parts of a Dimension
This section briefly defines the parts of a dimension.
dimension text
continued
arrowhead
dimension line
extension line
leader
See Parts of a Dimension in the Users Guide for more information about
the parts of a dimension.
See Use Dimension Styles in the Users Guide for more information about
the dimensioning system variables.
Single-line dimension text uses the active text style as specified by the
ActiveTextStyle property. Paragraphs of text use the active text style with
any modifications you make in your text string.
For more information about dimension text, see Control Dimension Text
in the Users Guide.
Leader objects are associated with the annotation, so when the annotation
is edited, the leader is updated accordingly. You can copy annotation used
elsewhere in a drawing and append it to a leader, or you can create a new
annotation. You can also create a leader with no annotation appended.
For more information about leaders, see Overview of Creating Text and
Leaders in the Users Guide.
Create Dimensions
You can create linear, radial, angular, and ordinate dimensions.
When creating dimensions, the active dimension style is used. Once
created, you can modify the extension line origins, the dimension text
location, and the dimension text content and its angle relative to the
dimension line. You can also change the dimension style used by the
dimension.
For more information about creating dimensions, see Dimensions and Tolerances in the Users Guide.
Create Dimensions
173
horizontal
vertical
aligned
For horizontal dimension text, if the angle of the dimension line is more
than 15 degrees from horizontal, and is outside the circle or arc, AutoCAD
draws a hook line, also called a landing or dogleg. The hook line is one
arrow- head long, and is placed next to the dimension text, as shown in the
follow- ing illustrations:
Create Dimensions
175
Sub Ch5_CreateRadialDimension()
Dim dimObj As AcadDimRadial
Dim center(0 To 2) As Double
Dim chordPoint(0 To 2) As Double
Dim leaderLen As Integer
' Define the dimension
center(0) = 0
center(1) = 0
center(2) = 0
chordPoint(0) = 5
chordPoint(1) = 5
chordPoint(2) = 0
leaderLen = 5
' Create the radial dimension in model space
Set dimObj = ThisDrawing.ModelSpace. _
AddDimRadial(center, chordPoint, leaderLen)
ZoomAll
End Sub
Note The LeaderLength setting is only used during the creation of the
dimen- sion (and even then only if the dimension is set to use the default text
position value). After the dimension is closed for the first time, changing the
Leader- Length value will not affect how the dimension displays, but the new
setting will be stored and will show up in DXF, LISP, and ADSRX applications.
Create
Dimensions
Ordinate
Create Dimensions
177
Edit Dimensions
As with other graphical objects in AutoCAD, you can edit dimensions using
the standard methods and properties provided for the object.
The following properties are available for most dimension objects:
Rotation
StyleName
TextOverride
TextPosition
TextRotation
Measurement
ArrayRectangular
Copy
Erase
Mirror
Move
Rotate
ScaleEntity
Edit Dimensions
179
Sub Ch5_CopyDimStyles()
Dim newStyle1 As AcadDimStyle
Dim newStyle2 As AcadDimStyle
Dim newStyle3 As AcadDimStyle
Set newStyle1 = ThisDrawing.DimStyles.Add _
("Style 1 copied from a dim")
Call newStyle1.CopyFrom(ThisDrawing.ModelSpace(0))
Set newStyle2 = ThisDrawing.DimStyles.Add _
("Style 2 copied from Style 1")
Call newStyle2.CopyFrom(ThisDrawing.DimStyles.Item _
("Style 1 copied from a dim"))
Set newStyle2 = ThisDrawing.DimStyles.Add _
("Style 3 copied from the running drawing values")
Call newStyle2.CopyFrom(ThisDrawing)
End Sub
Open the DIMSTYLE dialog. You should now have 3 dimension styles
listed. Style 1 should have a yellow dimension line. Style 2 should be the
same as Style 1. Style 3 should have a blue dimension line.
Arrowhead1Block, Arrowhead2Block
Specifies the block to use as the custom arrowhead for
the dimension line.
Arrowhead1Type, Arrowhead2Type
Specifies the type of arrowhead for the dimension line.
ArrowheadSize
CenterMarkSize
CenterType
DecimalSeparator
Specifies the character to be used as the decimal
separator in decimal dimension and tolerance values.
DimensionLineColor
Specifies the color of the dimension line for a
dimension, leader, or tolerance object.
DimensionLineWeight
Specifies the lineweight for the dimension lines.
DimLine1Suppress, DimLine2Suppress
Specifies the suppression of the dimension lines.
DimLineInside
ExtensionLineColor
Specifies the color for dimension extension lines.
ExtensionLineExtend
Specifies the distance the extension line extends
beyond the dimension line.
ExtensionLineOffset
Specifies the distance the extension lines are offset
from the origin points.
ExtensionLineWeight
Specifies the lineweight for the extension lines.
ExtLine1EndPoint, ExtLine2EndPoint
Specifies the endpoint of extension lines.
ExtLine1StartPoint, ExtLine2StartPoint
Specifies the start point of extension lines.
ExtLine1Suppress, ExtLine2Suppress
Specifies the suppression of extension lines.
Fit
ForceLineInside
Specifies if a dimension line is drawn between the
extension lines even when the text is placed outside the
extension lines.
FractionFormat
Specifies the format of fractional values in dimensions
and tolerances.
HorizontalTextPosition
Specifies the horizontal justification for dimension
text.
LinearScaleFactor
Specifies a global scale factor for linear dimensioning
measurements.
PrimaryUnitsPrecision
Specifies the number of decimal places displayed for the
primary units of a dimension or tolerance.
SuppressLeadingZeros, SuppressTrailingZeros
Specifies the suppression of leading and trailing zeros in
dimension values.
SuppressZeroFeet, SuppressZeroInches
Specifies the suppression of a zero foot and zero inch
measurement in dimension values.
TextColor
TextGap
TextHeight
TextInside
TextInsideAlign
Specifies the position of dimension text inside the
extension lines for all dimension types except ordinate.
TextMovement
Specifies how dimension text is drawn when text is
moved.
TextOutsideAlign
Specifies the position of dimension text outside the
extension lines for all dimension types except ordinate.
TextPosition
TextPrecision
TextPrefix
TextRotation
TextSuffix
ToleranceDisplay
Specifies if tolerances are displayed with the
dimension text.
ToleranceHeightScale
Specifies a scale factor for the text height of tolerance
values relative to the dimension text height.
ToleranceJustification
Specifies the vertical justification of tolerance values
relative to the nominal dimension text.
ToleranceLowerLimit
Specifies the minimum tolerance limit for dimension
text.
TolerancePrecision
Specifies the precision of tolerance values in primary
dimensions.
ToleranceSuppressLeadingZeros
Specifies the suppression of leading zeros in tolerance
values.
ToleranceSuppressTrailingZeros
Specifies the suppression of trailing zeros in dimension
values.
ToleranceUpperLimit
Specifies the maximum tolerance limit for dimension
text.
UnitsFormat
VerticalTextPosition
Specifies the vertical position of text in relation to the
dimension line.
Enter a user-defined suffix for an aligned dimension
This example creates an aligned dimension in model space and uses the
TextSuffix property to allow the user to change the text suffix for the
dimension.
Sub Ch5_AddTextSuffix()
Dim dimObj As AcadDimAligned
Dim point1(0 To 2) As Double
Dim point2(0 To 2) As Double
Dim location(0 To 2) As Double
Dim suffix As String
' Define the dimension
point1(0) = 0: point1(1) = 5: point1(2) = 0
point2(0) = 5: point2(1) = 5: point2(2) = 0
location(0) = 5: location(1) = 7: location(2) = 0
' Create an aligned dimension object in model space
Set dimObj = ThisDrawing.ModelSpace. _
AddDimAligned(point1, point2, location)
ThisDrawing.Application.ZoomAll
' Allow the user to change the text suffix for the dimension
suffix = InputBox("Enter a new text suffix for the dimension" _
, "Set Dimension Suffix", ":SUFFIX")
' Apply the change to the dimension
dimObj.TextSuffix = suffix
ThisDrawing.Regen acAllViewports
End Sub
A small line known as a hook line usually connects the annotation to the
leader. Hook lines appear with mtext and feature control frames if the last
leader line segment is at an angle greater than 15 degrees from horizontal.
The hook line is the length of a single arrowhead. If the leader has no annotation, it has no hook line.
hook line
leader line
To create a leader line, use the AddLeader method. This method requires
three values as input: the array of coordinates to create the leader at, the
annotation object (or NULL if the leader is to have no annotation), and the
type of leader to create. The type of leader specifies whether the leader is to
be a straight line or a smooth spline curve. It also determines whether or not
the leader is to have arrows. Use one of the following constants to specify the
type of leader: acLineNoArrow, acLineWithArrow, acSplineNoArrow, or
acSplineWithArrow. These constants are mutually exclusive of each other.
Create a leader line
This example creates a leader line in model space. There is no annotation
associated with the leader line.
Sub Ch5_CreateLeader()
Dim leaderObj As AcadLeader
Dim points(0 To 8) As Double
Dim leaderType As Integer
Dim annotationObject As AcadObject
points(0) = 0: points(1) = 0: points(2) = 0
points(3) = 4: points(4) = 4: points(5) = 0
points(6) = 4: points(7) = 5: points(8) = 0
leaderType = acLineWithArrow
Set annotationObject = Nothing
' Create the leader object in model space
Set leaderObj = ThisDrawing.ModelSpace. _
AddLeader(points, annotationObject, leaderType)
ZoomAll
End Sub
Leader Associativity
Leaders are associated with their annotation so that when the annotation
moves, the endpoint of the leader moves with it. As you move text and
feature control frame annotation, the final leader line segment alternates
between attaching to the left side and to the right side of the annotation
according to the relation of the annotation to the penultimate (second to
last) point of the leader. If the midpoint of the annotation is to the right of
the penultimate leader point, then the leader attaches to the right;
otherwise, it attaches to the left.
Removing either object from the drawing using either the Erase, Add (to add
a block), or WBlock method will break associativity. If the leader and its
annotation are copied together in a single operation, the new copy is
associa- tive. If they are copied separately, they will not be associative. If
associativity is broken for any reason, for example, by copying only the
Leader object or by erasing the annotation, the hook line will be removed
from the leader.
Associate a leader to the annotation
This example creates an MText object. A leader line is then created using the
MText object as its annotation.
Sub Ch5_AddAnnotation()
Dim leaderObj As AcadLeader
Dim mtextObj As AcadMText
Dim points(0 To 8) As Double
Dim insertionPoint(0 To 2) As Double
Dim width As Double
Dim leaderType As Integer
Dim annotationObject As Object
Dim textString As String, msg As String
' Create the MText object in model space
textString = "Hello, World."
insertionPoint(0) = 5
insertionPoint(1) = 5
insertionPoint(2) = 0
width = 2
Set mtextObj = ThisDrawing.ModelSpace. _
AddMText(insertionPoint, width, textString)
' Data for Leader
points(0) = 0: points(1) = 0: points(2) = 0
points(3) = 4: points(4) = 4: points(5) = 0
points(6) = 4: points(7) = 5: points(8) = 0
leaderType = acLineWithArrow
' Create the Leader object in model space and associate
' the MText object with the leader
Set annotationObject = mtextObj
Set leaderObj = ThisDrawing.ModelSpace. _
AddLeader(points, annotationObject, leaderType)
ZoomAll
End Sub
Edit Leaders
Any modifications to leader annotation that change its position affect the
position of the endpoint of the associated leader. Also, rotating the annotation causes the leader hook line (if any) to rotate.
To resize a leader, you can scale it. Scaling updates only the scale of the
selected object. For example, if you scale the leader, the annotation stays in
the same position relative to the leader endpoint but isnt scaled.
In addition to scaling, you can also move, mirror, and rotate a leader. Use the
ScaleEntity, Move, Mirror, and Rotate methods to edit the leader. You can
also change the text style associated with the annotation by using the StyleName property.
For more information about editing leaders, see Change Text with a Leader
in the Users Guide.
Sub Ch5_CreateTolerance()
Dim toleranceObj As AcadTolerance
Dim textString As String
Dim insertionPoint(0 To 2) As Double
Dim direction(0 To 2) As Double
' Define the tolerance object
textString = "Here is the Feature Control Frame"
insertionPoint(0) = 5
insertionPoint(1) = 5
insertionPoint(2) = 0
direction(0) = 1
direction(1) = 1
direction(2) = 0
' Create the tolerance object in model space
Set toleranceObj = ThisDrawing.ModelSpace. _
AddTolerance(textString, insertionPoint, direction)
ZoomAll
End Sub
Edit Tolerances
Tolerances are influenced by several system variables: DIMCLRD controls the
color of the feature control frame; DIMCLRT controls the color of the tolerance text; DIMGAP controls the gap between the feature control frame and
the text; DIMTXT controls the size of the tolerance text; and DIMTXTSTY
controls the style of the tolerance text. Use the SetVariable method to set the
values of system variables.
In this chapter
and
MenuGroups
Collections
Load Menu Groups
Create New Menu Groups
Change the Menu Bar
Create and Edit Pull-
Down and
Shortcut Menus
for
Menu Items and Toolbar
Items
Add Entries to the Right-
Click
Menu
Customization Guide.
193
MenuBar
PopupMenu
MenuGroups
MenuGroup
PopupMenus
Toolbars
The MenuGroups collection contains the menu groups that are loaded in the
current AutoCAD session. These menu groups contain all the menus that are
available to the AutoCAD session, some or all of which may be displayed on
the AutoCAD menu bar. In addition to the menus, the menu groups also
con- tain all the toolbars that are available to the current AutoCAD session.
Menu groups may also represent tile menus, screen menus, or tablet menus.
Each menu group contains a PopupMenus collection and a Toolbars collection. The PopupMenus collection contains all the menus within the menu
group. Likewise, the Toolbars collection contains all the toolbars within the
menu group.
Each PopupMenu is actually a collection that contains an individual object
for each menu item that appears on that menu. Likewise, each Toolbar is
also a collection that contains an individual object for each toolbar item
that appears on that toolbar.
AutoCAD Application
MenuBar
PopupMenu
MenuGroups
MenuGroup
PopupMenus
PopupMenu
PopupMenuItem
Toolbars
Toolbar
ToolbarItem
When using the Load method, set the BaseMenu parameter to TRUE to load
a new menu group to the menu bar. This will load the menu group as a
base menu in the same manner as the MENU command in AutoCAD.
To load a new menu group as a partial menu, omit the BaseMenu
parameter. This will load the menu group in the same manner as the
MENULOAD com- mand in AutoCAD. Once loaded into the MenuGroups
collection, partial menus can be inserted into the menu bar by using the
InsertMenuIn- MenuBar method, or the InsertInMenuBar method.
Once a menu group has been loaded, all the menus and toolbars defined by
that menu group are available for use. You can
Note
You cannot edit image tile menu items, screen menus, or tablet
menus using ActiveX Automation. However, you can load and unload these
menu types using ActiveX Automation.
You can then edit the menu group to contain the exact configuration you
desire. This process of creating new menu groups based on existing menu
groups has the advantage of automatically providing you with basic menus
such as File, Window, and Help.
Note Menus that have been removed from the menu bar are still available
in their designated menu group. They are simply no longer visible to the user.
Sub Ch6_MoveMenu()
' Define a variable to hold the menu to be moved
Dim moveMenu As AcadPopupMenu
Dim MyMenuBar As AcadMenuBar
Set MyMenuBar = ThisDrawing.Application.menuBar
' Set moveMenu equal to the first menu displayed
' on the menu bar
Set moveMenu = MyMenuBar.Item(0)
' Remove the first menu from the menu bar
MyMenuBar.Item(0).RemoveFromMenuBar
' Add the menu back into the menu bar
' in the last position on the bar
moveMenu.InsertInMenuBar (MyMenuBar.count)
End Sub
menu name
index 0
index 1
index 2
index 3
index 4
index 5
index 6
The first index position is zero (0) and the separators are listed as individual
menu items with their own index position. The Count property for the
menu pictured would be six (6). To add a menu item between Tile
Horizontally and Tile Vertically, set the Index parameter to two (2), which
is the index of the Tile Vertically menu item. This inserts your new menu
item into index two (2) and bumps all the remaining menu items down one
index position.
Once a menu item has been created, you cannot change the index of the
menu item through the Index property. To change the index of an existing
menu item you must delete and re-add the menu item to a different
position, or add or delete surrounding menu items until a proper
placement is achieved.
See Enable and disable menu items on page 208 for an example on
adding separators to a menu.
Sub Ch6_AddASubMenu()
Dim currMenuGroup As AcadMenuGroup
Set currMenuGroup = ThisDrawing.Application.MenuGroups.Item(0)
' Create the new menu
Dim newMenu As AcadPopupMenu
Set newMenu = currMenuGroup.Menus.Add("TestMenu")
' Add the submenu
Dim FileSubMenu As AcadPopupMenu
Set FileSubMenu = newMenu.AddSubMenu("", "OpenFile")
' Add a menu item to the sub menu
Dim newMenuItem As AcadPopupMenuItem
Dim openMacro As String
' Assign the macro the VB equivalent of "ESC ESC _open "
openMacro = Chr(vbKeyEscape) + Chr(vbKeyEscape) + "_open "
Set newMenuItem = FileSubMenu.AddMenuItem _
(newMenu.count + 1, "Open", openMacro)
' Display the menu on the menu bar
newMenu.InsertInMenuBar _
(ThisDrawing.Application.menuBar.count + 1)
End Sub
Label
Caption
Macro
HelpString
Enable
Check
Index
Type
SubMenu
Parent
Sub Ch6_DisableMenuItem()
Dim currMenuGroup As AcadMenuGroup
Set currMenuGroup = ThisDrawing.Application.MenuGroups.Item(0)
' Create the new menu
Dim newMenu As AcadPopupMenu
Set newMenu = currMenuGroup.Menus.Add("TestMenu")
' Add two menu items and a menu separator to the new menu
Dim MenuEnable As AcadPopupMenuItem
Dim MenuDisable As AcadPopupMenuItem
Dim MenuSeparator As AcadPopupMenuItem
Dim openMacro As String
' Assign the macro the VB equivalent of "ESC ESC _open "
openMacro = Chr(vbKeyEscape) + Chr(vbKeyEscape) + "_open "
Set MenuEnable = newMenu.AddMenuItem _
(newMenu.count + 1, "OpenEnabled", openMacro)
Set MenuSeparator = newMenu.AddSeparator("")
Set MenuDisable = newMenu.AddMenuItem _
(newMenu.count + 1, "OpenDisabled", openMacro)
' Disable the second menu item
MenuDisable.Enable = False
' Display the menu on the menu bar
newMenu.InsertInMenuBar _
(ThisDrawing.Application.menuBar.count + 1)
End Sub
Create
Toolbars
New
To create a new toolbar, use the Add method to add a new Toolbar object to
the Toolbars collection.
The Add method requires as input the name of the toolbar to add. The name
is a string of alphanumeric characters with no punctuation other than a
dash () or an underscore (_). The name is the easiest way of identifying the
tool- bar within the collection.
You can change the name of a toolbar once it has been created. To
change the name of an existing toolbar, use the Name property for that
toolbar.
Name
Help String
Macro
FlyoutButton
LargeIconName
The large icon name identifies the ID string of the largeimage resource (24 22 bitmap). The string must
comprise alphanumeric characters with no
punctuation other than a dash () or an underscore (_),
and should include the .bmp extension. The resource
can be either a system bitmap or a user-defined bitmap.
User-defined bitmaps must be of the appropriate size
and must reside in the Support path.
Query an existing toolbar to find the name of the icons for the buttons
Sub Ch6_GetButtonImages()
Dim Button As AcadToolbarItem
Dim Toolbar0 As AcadToolbar
Dim MenuGroup0 As AcadMenuGroup
Dim SmallButtonName As String
Dim LargeButtonName As String
Dim msg As String
Dim ButtonType As String
' Get the first toolbar in the first menu group
Set MenuGroup0 = ThisDrawing.Application. _
MenuGroups.Item(0)
Set Toolbar0 = MenuGroup0.Toolbars.Item(0)
' Clear the string variables
SmallButtonName = ""
LargeButtonName = ""
' Create a header for the message box and
' display the toolbar to be queried
msg = "Toolbar: " + Toolbar0.Name + vbCrLf
Toolbar0.Visible = True
' Iterate through the toolbar and collect data
' for each button in the toolbar. If the toolbar is
' a normal button or a flyout, collect the small
' and large button names for the button.
For Each Button In Toolbar0
ButtonType = Choose(Button.Type + 1, "Button", _
"Separator", "Control", "Flyout")
msg = msg & ButtonType & ":
"
If Button.Type = acToolbarButton Or _
Button.Type = acToolbarFlyout Then
Button.GetBitmaps SmallButtonName, _
LargeButtonName
msg = msg + SmallButtonName + ", " _
+ LargeButtonName
End If
msg = msg + vbCrLf
Next Button
' Display the results
MsgBox msg
End Sub
Sub Ch6_DockToolbar()
Dim currMenuGroup As AcadMenuGroup
Set currMenuGroup = ThisDrawing.Application. _
MenuGroups.Item(0)
' Create the new toolbar
Dim newToolbar As AcadToolbar
Set newToolbar = currMenuGroup.Toolbars. _
Add("TestToolbar")
' Add three buttons to the new toolbar.
' All three buttons will have the same macro attached.
Dim newButton1 As AcadToolbarItem
Dim newButton2 As AcadToolbarItem
Dim newButton3 As AcadToolbarItem
Dim openMacro As String
' Assign the macro the VB equivalent of "ESC ESC _open "
openMacro = Chr(vbKeyEscape) + Chr(vbKeyEscape) + "_open "
Set newButton1 = newToolbar.AddToolbarButton _
("", "NewButton1", "Open a file.", openMacro)
Set newButton2 = newToolbar.AddToolbarButton _
("", "NewButton2", "Open a file.", openMacro)
Set newButton3 = newToolbar.AddToolbarButton _
("", "NewButton3", "Open a file.", openMacro)
' Display the toolbar
newToolbar.Visible = True
' Dock the toolbar to the left of the screen.
newToolbar.Dock acToolbarDockLeft
End Sub
Explore
the
Toolbar Items
Properties
of
Tagstring
Name
Macro
HelpString
Index
Type
Flyout
Parent
Toolbar
Properties
Create Macros
A macro is a series of commands that executes specific actions when a
toolbar item is selected. Macros can simply be recordings of keystrokes that
accom- plish a task, or they can be a complex combination of commands,
AutoLISP, DIESEL, or ActiveX programming code.
If you intend to include command parameters in a menu macro, you must
know the sequence in which that command expects its parameters. Every
character in a menu macro is significant, even the blank spaces. As
AutoCAD is revised and enhanced, the sequence of prompts for various
commands (and sometimes even the command names) might change.
Therefore, your
custom menus might require minor changes when you upgrade to a new
release of AutoCAD.
When command input comes from a menu item, the settings of the
PICKADD and PICKAUTO system variables are assumed to be 1 and 0,
respectively. This preserves compatibility with previous releases of
AutoCAD and makes customization easier because you are not required to
check the settings of these variables.
ASCII equivalent
Description
chr(59)
Issues ENTER
^M
chr(13)
Issues ENTER
^|
chr(94) + chr(124)
Issues TAB
SPACEBAR
chr(32)
chr(92)
chr(95)
chr(43)
=*
chr(61) + chr(42)
*^C^C
chr(36)
^B
chr(2)
Create Macros
219
ASCII equivalent
Description
^C
chr(3)
ESC
chr(3)
^D
chr(4)
^E
chr(5)
^G
chr(7)
^H
chr(8)
Issues backspace
^O
chr(15)
^P
chr(16)
^Q
chr(17)
^T
chr(20)
^V
chr(22)
^Z
chr(26)
Macro Termination
When a macro is executed, AutoCAD places a space at the end of the macro
before processing the
command sequence. AutoCAD processes the
following menu macro as though you had entered line SPACEBAR.
line
If this item simply ended with the backslash (which indicates user input), it
would fail to complete the ERASE operation, because AutoCAD doesnt add a
blank after the backslash. Therefore, this macro uses a semicolon (;) to force
an ENTER after the user input. Here are more examples:
ucs
ucs ;
text \.4 0 DRAFT Inc;;;Main St.;;;City, State;
Selecting the first macro enters ucs and SPACEBAR on the command line,
and the following prompt appears:
Enter an option [New/Move/orthoGraphic/Prev/Restore/Save/Del/Apply/?/
World] <World>:
Selecting the second macro enters ucs, SPACEBAR, and semicolon (;) at the
command line, which accepts the default value, World. No difference
between the first and second item would be evident on the screen;
naturally, you wouldnt put both on the same menu.
Selecting the third macro displays a prompt for a starting point and then
draws the address on three lines. In the triple-semicolon (;;;), the first
semicolon ends the text string, the second causes repetition of the TEXT command, and the third calls for the default placement below the previous line.
Note All special characters must be input using their ASCII equivalents. For
a list of ASCII equivalents, see Macro Characters Mapped to ASCII
Equivalents.
Create Macros
221
The first macro pauses to ask the user for the center point and then reads a
radius of 1 from the macro. Note that there is no space after the backslash
character (\). The next macro pauses to ask the user to enter one layer
name, then turns that layer off and exits the LAYER command. The LAYER
command normally prompts for another operation and exits only if you
press SPACEBAR (blank) or ENTER (;).
Normally, the macro resumes after one item is entered. Therefore, it isnt possible to construct a macro that accepts a variable number of inputs (as in
object selection) and then continues. However, an exception is made for the
SELECT command; a backslash suspends the macro until object selection has
completed. For example, consider the following macro:
select \change previous ;properties color red ;
This macro uses the SELECT command to create a selection set of one or more
objects. It then issues the CHANGE command, references this selection set
using the Previous option, and changes the color of all selected objects to
red.
Because the backslash character (\) causes a macro to pause for user input,
you cannot use a backslash for any other purpose in a macro. When
specify- ing file directory paths, use a forward slash (/) as the path delimiter:
for exam- ple, /direct/file.
The following circumstances delay resumption of a macro:
Cancel a Command
To make sure you have no previous incomplete commands, use ^C^C in a
macro. This is the same as pressing ESC twice from the keyboard. Although
a single ^C cancels most commands, ^C^C is required to return to the
Macro Repetition
Once you have selected a command, you are likely to use it several times
before moving on to another command. That is how most people use tools;
you pick up a tool, do several things with it, then pick up another tool,
and so on. To avoid picking up the tool before each use, AutoCAD provides
a command repetition capability, triggered by a null response. However,
you cannot use this feature to specify command options.
This feature makes it possible for you to repeat frequently used commands
until you choose another command. If a macro begins with *^C^C immediately following the item label, the macro is saved in memory. Subsequent
Command prompts are answered by that macro until it is terminated by ESC
or by the selection of another macro.
Do not use ^C (Cancel) within a macro that begins with the string *^C^C;
this cancels the macro repetition.
The following is an example of the repetitive, or modal, approach to
command handling.
*^C^CMOVE Single
*^C^CCOPY Single
*^C^CERASE Single
*^C^CSTRETCH Single Crossing
*^C^CROTATE Single
*^C^CSCALE Single
Macro repetition does not work for items in image tile menus.
Create Macros
223
This macro terminates the current command and activates the ERASE command with the single selection option. After you select this item, you either
point to the single object to be erased or point to a blank area and specify a
window. The object(s) selected in this way are erased, and the macro is
repeated (due to the leading asterisk) so that you can erase something else.
Single selection mode leads to more dynamic interaction with AutoCAD.
Sub Ch6_AddHelp()
Dim currMenuGroup As AcadMenuGroup
Set currMenuGroup = ThisDrawing.Application.MenuGroups.Item(0)
' Create the new menu
Dim newMenu As AcadPopupMenu
Set newMenu = currMenuGroup.Menus.Add _
("Te" + Chr(Asc("&")) + "stMenu")
' Add a menu item to the new menu
Dim newMenuItem As AcadPopupMenuItem
Dim openMacro As String
' Assign the macro the VBA equivalent of "ESC ESC _open "
openMacro = Chr(vbKeyEscape) + Chr(vbKeyEscape) + "_open "
' Create the menu item
Set newMenuItem = newMenu.AddMenuItem _
(newMenu.count + 1, Chr(Asc("&")) _
+ "Open", openMacro)
' Add the status line help to the menu item
newMenuItem.HelpString = "Opens an AutoCAD drawing file."
' Display the menu on the menu bar
newMenu.InsertInMenuBar _
(ThisDrawing.Application.menuBar.count + 1)
End Sub
New menu groups may or may not have a shortcut menu available. To
create a shortcut menu for a menu group, follow the guidelines listed in
Create New Menus on page 200, and use POP0 as the label for the new
menu.
Add a menu item to the end of the right-click menu
This example adds the menu item OpenDWG to the end of the right-click
menu.
Sub Ch6_AddMenuItemToshortcutMenu()
Dim currMenuGroup As AcadMenuGroup
Set currMenuGroup = ThisDrawing.Application.MenuGroups.Item(0)
' Find the shortcut menu and assign it to the
' shortcutMenu variable
Dim scMenu As AcadPopupMenu
Dim entry As AcadPopupMenu
For Each entry In currMenuGroup.Menus
If entry.shortcutMenu = True Then
Set scMenu = entry
End If
Next entry
' Add a menu item to the shortcut menu
Dim newMenuItem As AcadPopupMenuItem
Dim openMacro As String
' Assign the macro the VBA equivalent of "ESC ESC _open "
openMacro = Chr(vbKeyEscape) + Chr(vbKeyEscape) + "_open "
Set newMenuItem = scMenu.AddMenuItem _
("", Chr(Asc("&")) _
+ "OpenDWG", openMacro)
End Sub
Use Events
In this chapter
AutoCAD
Handlers
Handle Application Level
Events
Events
Events
information you could write a subroutine, or event handler, that uses these events to track the amount of time
a user spends working on a particular drawing.
227
Subroutines that respond to events are called event handlers and are executed
automatically each and every time their designated event is triggered.
Infor- mation contained in events, such as the drawing name in the
BeginOpen event, are passed to event handlers through parameters.
You can write data to any object in the database, except the object
that issued the event.
Obviously, any object causing an event to be triggered could still be open
for use with AutoCAD and the operation currently in progress. Therefore,
avoid writing any information to an object from an event handler for the
same object. However, you can safely read information from the object
triggering an event. For example, suppose you have a floor that is filled
with tiles and you create an event handler attached to the border of the
floor. If you change the size of the floor, the event handler will automatically add or subtract tiles to fill the new area. The event handler will be
able to read the new area of the border, but it cannot attempt any changes
on the border itself.
Do not perform any action from an event handler that will trigger
the same event.
If you perform the same action in an event handler that triggers that
same event, you will create an infinite loop. For example, you should
never attempt to open a drawing from within the BeginOpen event, or
AutoCAD will simply continue to open more drawings until the maximum number of open drawings is reached.
AppDeactivate
ARXLoaded
ARXUnloaded
BeginCommand
BeginFileDrop
BeginLISP
BeginModal
BeginOpen
BeginPlot
BeginQuit
BeginSave
EndCommand
EndLISP
EndModal
EndOpen
EndPlot
EndSave
LISPCancelled
NewDrawing
SysVarChanged
WindowChanged
WindowMovedOrResized
Triggered just after the Application window has been
moved or resized.
After the new object has been declared with events, it appears in the Object
drop-down list box in the class module, and you can write event procedures
for the new object in the class module. (When you select the new object in
the Object box, the valid events for that object are listed in the Procedure
drop-down list box.)
Before the procedures will run, however, you must connect the declared
object in the class module with the Application object. You can do this
with the following code from any module.
To connect the declared object to the Application object
1 In the Code window for your main module, add the following line to the
declarations section:
Dim X As New EventClassModule
3 In the code for your main module, add a call to the InitializeEvents
subroutine:
Call InitializeEvents
Once the InitializeEvents procedure has been run, the App object in the
class module points to the Application object specified, and any event
procedures in the class module will run when the events occur.
Prompt to continue when a drawing is dropped into AutoCAD
This example intercepts the load process when a file has been dragged and
dropped into AutoCAD. A message box containing the name of the file that
was dropped and Yes/No/Continue buttons that allow the user to decide if
the file should continue to be loaded display. If the user chooses to cancel out
of the operation, that decision is returned through the Cancel parameter of
the BeginFileDrop event and the file is not loaded.
Once the document level events are enabled, you have a wide range of
events available to you. These events include
Activate
BeginClose
BeginCommand
BeginDoubleClick
Triggered after the user double-clicks on an object in
the drawing.
BeginLISP
BeginPlot
BeginRightClick
Triggered after the user right-clicks on the Drawing
window.
BeginSave
BeginShortcutMenuCommand
Triggered after the user right-clicks on the Drawing
window, and before the shortcut menu appears in
Command mode.
BeginShortcutMenuDefault
Triggered after the user right-clicks on the Drawing
window, and before the shortcut menu appears in
Default mode.
BeginShortcutMenuEdit
Triggered after the user right-clicks on the Drawing
window, and before the shortcut menu appears in Edit
mode.
BeginShortcutMenuGrip
Triggered after the user right-clicks on the Drawing
window, and before the shortcut menu appears in Grip
mode.
BeginShortcutMenuOsnap
Triggered after the user right-clicks on the Drawing
window, and before the shortcut menu appears in
Osnap mode.
Deactivate
EndCommand
EndLISP
EndPlot
EndSave
EndShortcutMenu
Triggered after the shortcut menu appears.
LayoutSwitched
LISPCancelled
ObjectAdded
ObjectErased
ObjectModified
SelectionChanged
Triggered when the current pickfirst selection set
changes.
WindowChanged
Triggered when there is a change to the
Document window.
WindowMovedOrResized
Triggered just after the Drawing window has been
moved or resized.
After the new object has been declared with events, it appears in the Object
drop-down list box in the class module, and you can write event procedures
for the new object in the class module. (When you select the new object in
the Object box, the valid events for that object are listed in the Procedure
drop-down list box.)
Before the procedures will run, however, you must connect the declared
object in the class module with the Document object. You can do this with
the following code from any module.
To connect the declared object to the Document object
1 In the Code window for your main module, add the following line to the
declarations section:
Dim X As New EventClassModule
3 In the code for your main module, add a call to the InitializeApp
subroutine:
Call InitializeEvents
Once the InitializeEvents procedure has been run, the Doc object in the
class module points to the Document object created, and any event
procedures in the class module will run when the events occur.
4 Open the Code window for the class using F7 , or by selecting the menu
option View Code.
5 In the Code window for the class, add the following line:
Public WithEvents Object As AcadCircle
After the new object has been declared with events, it appears in the Object
drop-down list box in the class module, and you can write event procedures
for the new object in the class module. (When you select the new object in
the Object box, the valid events for that object are listed in the Procedure
drop-down list box.)
Before the procedures will run, however, you must connect the declared
object in the class module with the Circle object. You can do this with the
following code from any module.
To connect the declared object to the Automation object
1 In the Code window for your main module, add the following line to the
declarations section:
Dim X As New EventClassModule
3 In the code for your main module, add a call to the InitializeApp
subroutine:
Call InitializeEvents
Once the InitializeEvents procedure has been run, the Circle object in the
class module points to the Circle object created, and any event procedures in
the class module will run when the events occur.
Note When coding in VBA, you must provide an event handler for all objects
enabled for the Modified event. If you do not provide a handler, VBA may terminate unexpectedly.
Work in Three
Dimensional Space
In this chapter
Specify 3D Coordinates
Define a User
Coordinate
Syste
m
Convert Coordinates
Create 3D Objects
Edit in 3D
Edit 3D Solids
241
Specify 3D Coordinates
Entering 3D WCS coordinates is similar to entering 2D WCS coordinates. In
addition to specifying X and Y values, you specify a Z value. As with the 2D
coordinates, a variant is used to pass the coordinates to ActiveX methods
and properties, and to query the coordinates.
For more information about specifying 3D coordinates, see Enter 3D Coordinates in chapter 15, Use Precision Tools, in the Users Guide.
Define and query the coordinates for 2D and 3D polylines
This example creates two polylines, each with three coordinates. The first
polyline is a 2D polyline, the second polyline is 3D. Notice the length of the
array containing the vertices is expanded to include the Z coordinates in the
creation of the 3D polyline. The example concludes by querying the coordinates of the polylines and displaying the coordinates in a message box.
Sub Ch8_Polyline_2D_3D()
Dim pline2DObj As AcadLWPolyline
Dim pline3DObj As AcadPolyline
Dim points2D(0 To 5) As Double
Dim points3D(0 To 8) As Double
' Define three 2D polyline points
points2D(0) = 1: points2D(1) = 1
points2D(2) = 1: points2D(3) = 2
points2D(4) = 2: points2D(5) = 2
' Define three 3D polyline points
points3D(0) = 1: points3D(1) = 1: points3D(2) = 0
points3D(3) = 2: points3D(4) = 1: points3D(5) = 0
points3D(6) = 2: points3D(7) = 2: points3D(8) = 0
' Create the 2D light weight Polyline
Set pline2DObj = ThisDrawing.ModelSpace. _
AddLightWeightPolyline(points2D)
pline2DObj.Color = acRed
pline2DObj.Update
' Create the 3D polyline
Set pline3DObj = ThisDrawing.ModelSpace. _
AddPolyline(points3D)
pline3DObj.Color = acBlue
pline3DObj.Update
' Query the coordinates of the polylines
Dim get2Dpts As Variant
Dim get3Dpts As Variant
get2Dpts = pline2DObj.Coordinates
get3Dpts = pline3DObj.Coordinates
' Display the coordinates
MsgBox ("2D polyline (red): " & vbCrLf & _
get2Dpts(0) & ", " & get2Dpts(1) & vbCrLf & _
get2Dpts(2) & ", " & get2Dpts(3) & vbCrLf & _
get2Dpts(4) & ", " & get2Dpts(5))
MsgBox ("3D polyline (blue):
get3Dpts(0) & ", " &
get3Dpts(2) & vbCrLf
get3Dpts(3) & ", " &
get3Dpts(5) & vbCrLf
get3Dpts(6) & ", " &
get3Dpts(8))
End Sub
Specify 3D Coordinates
243
Sub Ch8_NewUCS()
' Define the variables we will need
Dim ucsObj As AcadUCS
Dim origin(0 To 2) As Double
Dim xAxisPnt(0 To 2) As Double
Dim yAxisPnt(0 To 2) As Double
' Define the UCS points
origin(0) = 4: origin(1) = 5: origin(2) = 3
xAxisPnt(0) = 5: xAxisPnt(1) = 5: xAxisPnt(2) = 3
yAxisPnt(0) = 4: yAxisPnt(1) = 6: yAxisPnt(2) = 3
' Add the UCS to the
' UserCoordinatesSystems collection
Set ucsObj = ThisDrawing.UserCoordinateSystems. _
Add(origin, xAxisPnt, yAxisPnt, "New_UCS")
' Display the UCS icon
ThisDrawing.ActiveViewport.UCSIconAtOrigin = True
ThisDrawing.ActiveViewport.UCSIconOn = True
' Make the new UCS the active UCS
ThisDrawing.ActiveUCS = ucsObj
MsgBox "The current UCS is : " & ThisDrawing.ActiveUCS.Name _
& vbCrLf & " Pick a point in the drawing."
' Find the WCS and UCS coordinate of a point
Dim WCSPnt As Variant
Dim UCSPnt As Variant
WCSPnt = ThisDrawing.Utility.GetPoint(, "Enter a point: ")
UCSPnt = ThisDrawing.Utility.TranslateCoordinates _
(WCSPnt, acWorld, acUCS, False)
MsgBox "The WCS coordinates are: " & WCSPnt(0) & ", " _
& WCSPnt(1) & ", " & WCSPnt(2) & vbCrLf & _
"The UCS coordinates are: " & UCSPnt(0) & ", " _
& UCSPnt(1) & ", " & UCSPnt(2)
End Sub
Convert Coordinates
The TranslateCoordinates method translates a point or a displacement from
one coordinate system to another. A point argument, called OriginalPoint,
can be interpreted as either a 3D point or a 3D displacement vector. This
argument is distinguished by the Boolean argument, Disp. If the Disp argument is set to TRUE the OriginalPoint argument is treated as a
displacement vector; otherwise, it is treated as a point. Two more
arguments determine which coordinate system the OriginalPoint is from,
and to which coordi- nate system the OriginalPoint is to be converted.
The following AutoCAD coordinate systems can be specified in the From
and To arguments:
Convert Coordinates
245
WCS
UCS
OCS
DCS
PSDCS
Convert Coordinates
247
Sub Ch8_TranslateCoordinates()
' Create a polyline in model space.
Dim plineObj As AcadPolyline
Dim points(0 To 14) As Double
' Define the 2D polyline points
points(0) = 1: points(1) = 1: points(2) = 0
points(3) = 1: points(4) = 2: points(5) = 0
points(6) = 2: points(7) = 2: points(8) = 0
points(9) = 3: points(10) = 2: points(11) = 0
points(12) = 4: points(13) = 4: points(14) = 0
' Create a light weight Polyline object in model space
Set plineObj = ThisDrawing.ModelSpace.AddPolyline(points)
' Find the X and Y coordinates of the
' first vertex of the polyline
Dim firstVertex As Variant
firstVertex = plineObj.Coordinate(0)
' Find the Z coordinate for the polyline
' using the elevation property
firstVertex(2) = plineObj.Elevation
' Change the normal for the pline so that the
' difference between the coordinate systems
' is obvious.
Dim plineNormal(0 To 2) As Double
plineNormal(0) = 0#
plineNormal(1) = 1#
plineNormal(2) = 2#
plineObj.Normal = plineNormal
' Translate the OCS coordinate into WCS
Dim coordinateWCS As Variant
coordinateWCS = ThisDrawing.Utility.TranslateCoordinates _
(firstVertex, acOCS, acWorld, False, plineNormal)
' Display the coordinates of the point
MsgBox "The first vertex has the following coordinates:" _
& vbCrLf & "OCS: " & firstVertex(0) & ", " & _
firstVertex(1) & ", " & firstVertex(2) & vbCrLf & _
"WCS: " & coordinateWCS(0) & ", " & _
coordinateWCS(1) & ", " & coordinateWCS(2)
End Sub
Create 3D
Objects
AutoCAD supports three types of 3D modeling: wireframe, surface, and
solid. Each type has its own creation and editing techniques.
Create Wireframes
With AutoCAD you can create wireframe models by positioning any 2D planar object anywhere in 3D space. You can position 2D objects in 3D space
using several methods:
Also, you can create some wireframe objects, such as polylines, that can exist
in all three dimensions. Use the Add3DPoly method to create 3D polylines.
For more information on creating wireframes, see Create Wireframe Models in the Users Guide.
Create Meshes
A rectangular mesh (PolygonMesh object) represents an objects surface using
planar facets. The mesh density, or number of facets, is defined in terms of a
matrix of M and N vertices, similar to a grid consisting of columns and rows.
M and N specify the column and row position, respectively, of any given vertex. You can create meshes in both 2D and 3D, but they are used primarily
for 3D.
Use the Add3DMesh method for creating rectangular meshes. This method
takes three values as input: the number of vertices in the M direction, the
numer of vertices in the N direction, and a variant array containing coordinates for all the vertices in the mesh.
Once the PolygonMesh is created, use the MClose and NClose properties to
close the mesh.
For more information on creating meshes, see Create Surfaces in the Users
Guide.
Create a polygon mesh
This example creates a 4 4 polygon mesh. The direction of the active viewport is then adjusted so that the three-dimensional nature of the mesh is
more easily viewed.
Create 3D Objects
249
Sub Ch8_Create3DMesh()
Dim meshObj As AcadPolygonMesh
Dim mSize, nSize, Count As Integer
Dim points(0 To 47) As Double
' create the matrix of points
points(0) = 0: points(1) = 0: points(2) = 0
points(3) = 2: points(4) = 0: points(5) = 1
points(6) = 4: points(7) = 0: points(8) = 0
points(9) = 6: points(10) = 0: points(11) = 1
points(12) = 0: points(13) = 2: points(14) = 0
points(15) = 2: points(16) = 2: points(17) = 1
points(18) = 4: points(19) = 2: points(20) = 0
points(21) = 6: points(22) = 2: points(23) = 1
points(24) = 0: points(25) = 4: points(26) = 0
points(27) = 2: points(28) = 4: points(29) = 1
points(30) = 4: points(31) = 4: points(32) = 0
points(33) = 6: points(34) = 4: points(35) = 0
points(36) = 0: points(37) = 6: points(38) = 0
points(39) = 2: points(40) = 6: points(41) = 1
points(42) = 4: points(43) = 6: points(44) = 0
points(45) = 6: points(46) = 6: points(47) = 0
mSize = 4: nSize = 4
' creates a 3Dmesh in model space
Set meshObj = ThisDrawing.ModelSpace. _
Add3DMesh(mSize, nSize, points)
' Change the viewing direction of the viewport
' to better see the cylinder
Dim NewDirection(0 To 2) As Double
NewDirection(0) = -1
NewDirection(1) = -1
NewDirection(2) = 1
ThisDrawing.ActiveViewport.direction = NewDirection
ThisDrawing.ActiveViewport = ThisDrawing.ActiveViewport
ZoomAll
End Sub
Create a Polyface
Mesh
Use the AddPolyfaceMesh method to create a polyface mesh, with each face
capable of having numerous vertices.
Creating a polyface mesh is similar to creating a rectangular mesh. To create
a polyface mesh, specify coordinates for all its vertices then define each face
by entering vertex numbers for all the vertices of that face. As you create the
polyface mesh, you can set specific edges to be invisible, assign them to layers, or give them colors.
To make an edge invisible, enter the vertex number for the edge as a
negative value. For more information on creating polyface meshes, see the
AddPoly- faceMesh method of the ActiveX and VBA Reference.
For more information on creating polyface meshes, see Create a Polyface
Mesh in the Users Guide.
Create a polyface mesh
This example creates a Polyface Mesh object in model space. The viewing
direction of the active viewport is updated to display the three-dimensional
nature of the mesh more easily.
Sub Ch8_CreatePolyfaceMesh()
'Define the mesh vertices
Dim vertex(0 To 17) As Double
vertex(0) = 4: vertex(1) = 7: vertex(2) = 0
vertex(3) = 5: vertex(4) = 7: vertex(5) = 0
vertex(6) = 6: vertex(7) = 7: vertex(8) = 0
vertex(9) = 4: vertex(10) = 6: vertex(11) = 0
vertex(12) = 5: vertex(13) = 6: vertex(14) = 0
vertex(15) = 6: vertex(16) = 6: vertex(17) = 1
' Define the face list
Dim FaceList(0 To 7) As Integer
FaceList(0) = 1
FaceList(1) = 2
FaceList(2) = 5
FaceList(3) = 4
FaceList(4) = 2
FaceList(5) = 3
FaceList(6) = 6
FaceList(7) = 5
' Create the polyface mesh
Dim polyfaceMeshObj As AcadPolyfaceMesh
Set polyfaceMeshObj = ThisDrawing.ModelSpace.AddPolyfaceMesh _
(vertex, FaceList)
' Change the viewing direction of the viewport to
' better see the polyface mesh
Dim NewDirection(0 To 2) As Double
NewDirection(0) = -1
NewDirection(1) = -1
NewDirection(2) = 1
ThisDrawing.ActiveViewport.direction = NewDirection
ThisDrawing.ActiveViewport = ThisDrawing.ActiveViewport
ZoomAll
End Sub
Create 3D Objects
251
Create Solids
A solid object (3DSolid object) represents the entire volume of an object.
Solids are the most informationally complete and least ambiguous of the 3D
modeling types. Complex solid shapes are also easier to construct and edit
than wireframes and meshes.
You create solids from one of the basic solid shapes of box, cone, cylinder,
sphere, torus, and wedge or by extruding a 2D object along a path or revolving a 2D object about an axis. Use one of the following methods to create
solids:
AddBox, AddCone, AddCylinder, AddEllipticalCone, AddEllipticalCylinder,
AddExtrudedSolid, AddExtrudedSolidAlongPath, AddRevolvedSolid,
AddSolid, AddSphere, AddTorus, or AddWedge.
Like meshes, solids are displayed as wireframes until you hide, shade, or render them. Additionally, you can analyze solids for their mass properties (volume, moments of inertia, center of gravity, and so forth). Use the following
properties to analyze solids: MomentOfInertia, PrincipalDirections, PrincipalMoments, ProductOfInertia, RadiiOfGyration, and Volume.
The ContourlinesPerSurface property controls the number of tessellation
lines used to visualize curved portions of the wireframe. The RenderSmoothness property adjusts the smoothness of shaded and hidden-line objects.
For more information on creating solids, see Create 3D Solids in the Users
Guide.
Create a wedge solid
The following example creates a wedge-shaped solid in model space. The
viewing direction of the active viewport is updated to display the threedimensional nature of the wedge more easily.
Sub Ch8_CreateWedge()
Dim wedgeObj As Acad3DSolid
Dim center(0 To 2) As Double
Dim length As Double
Dim width As Double
Dim height As Double
' Define the wedge
center(0) = 5#: center(1) = 5#: center(2) = 0
length = 10#: width = 15#: height = 20#
' Create the wedge in model space
Set wedgeObj = ThisDrawing.ModelSpace. _
AddWedge(center, length, width, height)
' Change the viewing direction of the viewport
Dim NewDirection(0 To 2) As Double
NewDirection(0) = -1
NewDirection(1) = -1
NewDirection(2) = 1
ThisDrawing.ActiveViewport.direction = NewDirection
ThisDrawing.ActiveViewport = ThisDrawing.ActiveViewport
ZoomAll
End Sub
Edit in 3D
This section describes how to edit 3D objects by, for example, rotating, arraying, and mirroring.
Rotate
3D
in
With the Rotate method, you can rotate objects in 2D about a specified
point. The direction of rotation is determined by the WCS. The Rotate3D
method rotates objects in 3D about a specified axis. The Rotate3D method
takes three values as input: the WCS coordinates of the two points defining
the rotation axis and the rotation angle in radians.
Edit in 3D
253
axis point 2
axis point 1
object to rotate
axis of rotation
result
Array in 3D
With the ArrayRectangular method, you can create a rectangular array in
3D. In addition to specifying the number of columns (X direction) and
rows
(Y direction), you also specify the number of levels (Z direction).
For more information on using arrays of objects in 3D, see Create an Array
of Objects in the Users Guide.
Create a 3D rectangular array
This example creates a circle and then uses that circle to create a rectangular
array of 4 rows, 4 columns, and 3 levels of circles.
Sub Ch8_CreateRectangularArray()
' Create the circle
Dim circleObj As AcadCircle
Dim center(0 To 2) As Double
Dim radius As Double
center(0) = 2: center(1) = 2: center(2) = 0
radius = 0.5
Set circleObj = ThisDrawing.ModelSpace. _
AddCircle(center, radius)
' Define the rectangular array
Dim numberOfRows As Long
Dim numberOfColumns As Long
Dim numberOfLevels As Long
Dim distanceBwtnRows As Double
Dim distanceBwtnColumns As Double
Dim distanceBwtnLevels As Double
numberOfRows = 4
numberOfColumns = 4
numberOfLevels = 3
distanceBwtnRows = 1
distanceBwtnColumns = 1
distanceBwtnLevels = 4
' Create the array of objects
Dim retObj As Variant
retObj = circleObj.ArrayRectangular _
(numberOfRows, numberOfColumns, _
numberOfLevels, distanceBwtnRows, _
distanceBwtnColumns, distanceBwtnLevels)
ZoomAll
End Sub
Mirror in 3D
With the Mirror3D method, you can mirror objects along a specified mirroring plane specified by three points.
Edit in 3D
255
1
2
object to mirror
result
For more information on mirroring objects in 3D, see Mirror Objects in the
Users Guide.
Mirror in 3D
This example creates a box in model space. It then mirrors the box about a
plane and colors the mirrored box red.
Sub Ch8_MirrorABox3D()
' Create the box object
Dim boxObj As Acad3DSolid
Dim length As Double
Dim width As Double
Dim height As Double
Dim center(0 To 2) As Double
center(0) = 5#: center(1) = 5#: center(2) = 0
length = 5#: width = 7: height = 10#
' Create the box (3DSolid) object in model space
Set boxObj = ThisDrawing.ModelSpace. _
AddBox(center, length, width, height)
' Define the mirroring plane with three points
Dim mirrorPt1(0 To 2) As Double
Dim mirrorPt2(0 To 2) As Double
Dim mirrorPt3(0 To 2) As Double
mirrorPt1(0) = 1.25: mirrorPt1(1) = 0: mirrorPt1(2) = 0
mirrorPt2(0) = 1.25: mirrorPt2(1) = 2: mirrorPt2(2) = 0
mirrorPt3(0) = 1.25: mirrorPt3(1) = 2: mirrorPt3(2) = 2
' Mirror the box
Dim mirrorBoxObj As Acad3DSolid
Set mirrorBoxObj = boxObj.Mirror3D _
(mirrorPt1, mirrorPt2, mirrorPt3)
mirrorBoxObj.Color = acRed
ZoomAll
End Sub
Edit 3D Solids
Once you have created a solid, you can create more complex shapes by
combining solids. You can join solids, subtract solids from each other, or
find the common volume (overlapping portion) of solids. Use the Boolean
or CheckInterference methods to perform these combinations.
Edit 3D Solids
Sub Ch8_FindInterferenceBetweenSolids()
' Define the box
Dim boxObj As Acad3DSolid
Dim length As Double
Dim width As Double
Dim height As Double
Dim center(0 To 2) As Double
center(0) = 5: center(1) = 5: center(2) = 0
length = 5
width = 7
height = 10
' Create the box object in model space
' and color it white
Set boxObj = ThisDrawing.ModelSpace. _
AddBox(center, length, width, height)
boxObj.Color = acWhite
' Define the cylinder
Dim cylinderObj As Acad3DSolid
Dim cylinderRadius As Double
Dim cylinderHeight As Double
center(0) = 0: center(1) = 0: center(2) = 0
cylinderRadius = 5
cylinderHeight = 20
' Create the Cylinder and
' color it cyan
Set cylinderObj = ThisDrawing.ModelSpace.AddCylinder _
(center, cylinderRadius, cylinderHeight)
cylinderObj.Color = acCyan
' Find the interference between the two solids
' and create a new solid from it. Color the
' new solid red.
Dim solidObj As Acad3DSolid
Set solidObj = boxObj.CheckInterference(cylinderObj, True)
solidObj.Color = acRed
ZoomAll
End Sub
2 | Chapter 8
Space
Edit 3D Solids
260
In this chapter
Layouts
Viewports
Space
261
Layouts
All the geometry of your drawing is contained in layouts. Model space geometry is contained on a single layout named Model. You cannot rename the
model space layout, nor can you create another model space layout. There
can be only one model space layout per drawing.
Paper space geometry is also contained on layouts. You can have many different paper space layouts in your drawing, each representing a different configuration to print. You can change the name of the paper space layouts.
In ActiveX Automation the ModelSpace object contains all the geometry in
the model space layout. Because there can be more than one paper space layout in a drawing, the PaperSpace object points to the last active paper space
layout.
For more information about working with paper space layouts, see Create
Layouts in the Users Guide.
6 | Chapter 9
Plot
Each Layout object is associated with one, and only one, Block object. To
access the Block object associated with a given layout, use the Block
property. Conversely, each Block object is associated with one, and only one,
Layout object. To access the Layout object associated with a given Block,
use the Layout property for that block.
Plot Configurations
A PlotConfiguration object is similar to a Layout object, as both contain
identical plot information. The difference is that a Layout object is
associated with a Block object containing the geometry to plot. A
PlotConfiguration object is not associated with a particular Block object. It
is simply a named collection of plot settings available for use with any
geometry.
Layout Settings
Layout settings control the final plotted output. These settings affect the
paper size, plot scale, plot area, plot origin, and the plot device name.
Under- standing how to use layout settings ensures the layout plots as
expected. All the settings for a layout can be changed from the Layout
object properties and methods.
Layouts
acDisplay
acExtents
acLimits
acView
acWindow
acLayout
When you create a new paper space layout, the default option is acLayout.
8 | Chapter 9
Plot
Viewports
When working in model space you draw geometry in tile viewports (referred
to as Viewport objects in ActiveX Automation). You can display one or
several different viewports at a time. If several tiled viewports are displayed,
editing in one viewport affects all other viewports. However, you can set
magnification, viewpoint, grid, and snap settings individually for each
viewport.
In paper space, you work in floating paper space viewports (referred to as
PViewport objects in ActiveX Automation) to contain different views of your
model. Floating viewports are treated as objects you can move, resize, and
shape to create a suitable layout. You also can draw objects, such as title
blocks or annotations, directly in the paper space view without affecting the
model itself.
tiled viewports
floating viewports
For more information about viewports, see Set Model Tab Viewports, Display Multiple Views, and Create Layout Viewports in the Users Guide.
Floating Viewports
You cannot edit the model in paper space. To access the model in a
PViewport object, toggle from paper space to model space using the
ActiveSpace prop- erty. As a result, you can work with the model while
keeping the overall layout visible. In PViewport objects, the editing and
view-changing capabili- ties are almost the same as in Viewport objects.
However, you have more control over the individual views. For example,
you can freeze or turn off
Viewports
layers in some viewports without affecting others. You can turn an entire
viewport display on or off. You can also align views between viewports and
scale the views relative to the overall layout.
The following illustration shows how different views of a model are displayed in paper space. Each paper space image represents a PViewport object
with a different view. In one view, the dimensioning layer is frozen. Notice
that the title block, border, and annotation, which are drawn in paper space,
do not appear in the Model Space view. Also, the layer containing the viewport borders has been turned off.
the model
When you work in a Viewport object, the ActiveSpace property must always
be set to acModelSpace. When you are working in a PViewport object, you
can set the ActiveSpace property to either acModelSpace or acPaperSpace,
thus allowing you to switch between paper space and model space as
needed.
PViewport object, Viewport object, and ActiveSpace property
settings
Type of viewport
Status
Usage
PViewport
ActiveSpace =
acPaperspace
PViewport
ActiveSpace =
acModelspace
Viewport
ActiveSpace =
acModelspace
In AutoCAD ActiveX Automation, the ActiveSpace property is used to control the TILEMODE system variable. Setting
ThisDrawing.ActiveSpace = acModelSpace is equivalent to setting
TILEMODE = on, and setting ThisDrawing.ActiveSpace = acPaperSpace
is equivalent to setting TILEMODE = off.
Similarly, the MSpace property is the equivalent of both the MSPACE and
PSPACE commands in AutoCAD. Setting ThisDrawing.MSpace = TRUE is the
same as using the MSPACE command: it switches to model space. Setting
ThisDrawing.MSpace = FALSE is the same as using the PSPACE command: it
switches to paper space.
In addition, you are required to use the Display method before setting the
MSpace property to TRUE. The Display method initializes certain graphic settings that must be set before switching to model space. In AutoCAD this is
done behind the scenes. However, in the ActiveX Automation interface,
the programmer must take care of this initialization.
Note Remember, you must turn on the display using the Display method for
at least one PViewport object before you can set the MSpace property to TRUE.
Failure to turn on the display will result in an error being returned when you try
to set the MSpace property.
When you are in paper space, AutoCAD displays the paper space UCS icon
in the lower-left corner of the graphics area. The crosshairs indicate that the
paper space layout area (not the views in the viewports) can be edited.
Note You must create floating viewports before you attempt to switch
to model space.
To switch to tiled viewports
To switch to tiled viewports, perform this additional step:
Note To set or modify aspects of the view (view direction, lens length, and
so forth), the Viewport objects Display method must be set to off (FALSE), and
before you can set a viewport current the Display method must be set to on
(TRUE).
Create four floating viewports
This example takes the example from Create and enable a floating viewport on page 269 and continues it by creating four floating viewports and
setting the view of each to top, front, right, and isometric views,
respectively. Each view is scaled to half the scale of paper space. To ensure
there is some- thing to see in these viewports, you may want to create a 3D
solid sphere before trying this example.
Sub Ch9_FourPViewports()
Dim topVport, frontVport As AcadPViewport
Dim rightVport, isoVport As AcadPViewport
Dim pt(0 To 2) As Double
Dim viewDir(0 To 2) As Double
ThisDrawing.ActiveSpace = acPaperSpace
ThisDrawing.MSpace = True
' Take the existing PViewport and make it the topVport
pt(0) = 2.5: pt(1) = 5.5: pt(2) = 0
Set topVport = ThisDrawing.ActivePViewport
'No need to set Direction for top view
topVport.center = pt
topVport.width = 2.5
topVport.height = 2.5
topVport.Display True
ThisDrawing.MSpace = True
ThisDrawing.ActivePViewport = topVport
ZoomExtents
ZoomScaled 0.5, acZoomScaledRelativePSpace
'Create and setup frontVport
pt(0) = 2.5: pt(1) = 2.5: pt(2) = 0
Set frontVport = ThisDrawing.PaperSpace. _
AddPViewport(pt, 2.5, 2.5)
viewDir(0) = 0: viewDir(1) = 1: viewDir(2) = 0
frontVport.direction = viewDir
frontVport.Display acOn
ThisDrawing.MSpace = True
ThisDrawing.ActivePViewport = frontVport
ZoomExtents
ZoomScaled 0.5, acZoomScaledRelativePSpace
'Create and setup rightVport
pt(0) = 5.5: pt(1) = 5.5: pt(2) = 0
Set rightVport = ThisDrawing.PaperSpace. _
AddPViewport(pt, 2.5, 2.5)
viewDir(0) = 1: viewDir(1) = 0: viewDir(2) = 0
rightVport.direction = viewDir
rightVport.Display acOn
ThisDrawing.MSpace = True
ThisDrawing.ActivePViewport = rightVport
ZoomExtents
ZoomScaled 0.5, acZoomScaledRelativePSpace
'Create and set up isoVport
pt(0) = 5.5: pt(1) = 2.5: pt(2) = 0
Set isoVport = ThisDrawing.PaperSpace. _
AddPViewport(pt, 2.5, 2.5)
viewDir(0) = 1: viewDir(1) = 1: viewDir(2) = 1
isoVport.direction = viewDir
isoVport.Display acOn
ThisDrawing.MSpace = True
ThisDrawing.ActivePViewport = isoVport
ZoomExtents
ZoomScaled 0.5, acZoomScaledRelativePSpace
'Finish: Perform a regen in all viewports
ThisDrawing.Regen True
End Sub
When you work in paper space, the scale factor represents a ratio between
the size of the plotted drawing and the actual size of the model displayed in
the viewports. To derive this scale, divide paper space units by model space
units. For a quarter-scale drawing, for example, you specify a scale factor of
one paper space unit to four model space units (1:4).
Use the ZoomScaled method to scale viewports relative to paper space units.
This method takes three values as input: the viewport to scale, the scale factor, and how you want that scale factor applied. The third value is optional
and determines how the scale is applied:
current view
zoom to 0.5xp
zoom to 2xp
Use the SetVariable method to set the value of the PSLTSCALE system variable.
Plots to a file
PlotToDevice
DisplayPlotPreview
Displays a preview of the specified plot
SetLayoutsToPlot
Establish the list of layouts that will be plotted in the
next call to PlotToFile or PlotToDevice
StartBatchMode
QuietErrorMode
NumberOfCopies
Toggles the quiet error mode for plot error reporting
BatchPlotProgress
Specifies the number of copies to be plotted
The device name can be specified using the ConfigName property. This
device can be overridden in the PlotToDevice method by specifying a PC3 file.
278
In this chapter
Attributes
Use External References
Assign and Retrieve
Extended
Data
computer-rendered images. For information about raster images in addition to the information in this
section, see the Users Guide.
In addition to enhancing your drawings visual image,
AutoCAD provides several features to help you organize
data, allowing you to further expand the intelligence of
the objects in your drawing.
279
If AutoCAD cannot locate the drawing (for example, if you have moved the
file to a different directory than the one saved with the ImageFile property),
it removes relative or absolute path information from the name (for
example,
\images\tree.tga or c:\my project\images\tree.tga becomes tree.tga) and
searches the paths you have defined using the SetProjectFilePath method on
the Preferences object. If the drawing is not located in the paths, it
attempts the first search path again.
You can remove the path from the file name or specify a relative path by
resetting the ImageFile property.
Changing the path in the ImageFile property does not affect the project files
search-path settings.
Name Images
Image names are not necessarily the same as image file names. When you
attach an image to a drawing, AutoCAD uses the file name without the file
extension as the image name. You can change the image name without
affecting the name of the file.
The image file is represented by the ImageFile property on the Raster object.
Changing the ImageFile property will change the image in the drawing. The
image name is represented by the Name property, and changing the Name
property will change the name of the image only, not the file associated
with it.
Note This property affects only the image boundary. To see a change in the
image when toggling this property, look closely at the small boundary surrounding the image.
Color
Linetype
Rotate
Origin
Width
ImageWidth
ImageHeight
ShowRotation
Note Bitonal images and bitonal image boundaries are always the same color.
To change the foreground color of a bitonal image, use the Color property.
To turn the transparency on and off, use the Transparency property.
Contrast
Fade
Clip Images
You can define a region of an image for display and plotting by clipping the
image. The clipping boundary must be a 2D polygon or rectangle with
vertices constrained to lay within the boundaries of the image. Multiple
instances of the same image can have different boundaries.
To clip an image
1 Turn on the image boundaries using the ClippingEnabled property.
2 Specify the clipping boundary and perform the clip using the ClipBoundary method. This method takes one value as input: a variant array of 2D
WCS coordinates specifying the clipping boundary of a raster image.
Sub Ch10_ClippingRasterBoundary()
Dim insertionPoint(0 To 2) As Double
Dim scalefactor As Double
Dim rotationAngle As Double
Dim imageName As String
Dim rasterObj As AcadRasterImage
imageName = "C:\AutoCAD\sample\downtown.jpg"
insertionPoint(0) = 5
insertionPoint(1) = 5
insertionPoint(2) = 0
scalefactor = 2
rotationAngle = 0
On Error GoTo ERRORHANDLER
' Creates a raster image in model space
Set rasterObj = ThisDrawing.ModelSpace.AddRaster _
(imageName, insertionPoint, _
scalefactor, rotationAngle)
ZoomAll
' Establish the clip boundary with
Dim clipPoints(0 To 9) As Double
clipPoints(0) = 6: clipPoints(1) =
clipPoints(2) = 7: clipPoints(3) =
clipPoints(4) = 6: clipPoints(5) =
clipPoints(6) = 5: clipPoints(7) =
clipPoints(8) = 6: clipPoints(9) =
an array of points
6.75
6
5
6
6.75
Define Blocks
To create a new block, use the Add method. This method requires two
values as input: the location in the drawing where the block is added and
the name of the block to create.
Once created, you can add any geometrical object, or another block, to the
newly created block. You can then insert an instance of the block into the
drawing. An inserted block is an object called a block reference.
You can also create a block by using the WBlock method to group objects in
a separate drawing file. The drawing file can then be used as a block definition for other drawings. AutoCAD considers any drawing you insert into
another drawing to be a block.
For more information on defining blocks, see Create Blocks in chapter 16,
Draw Geometric Objects, in the Users Guide.
Insert Blocks
You can insert blocks or entire drawings into the current drawing with the
InsertBlock method. The InsertBlock method takes six values as input: the
insertion point, the name of the block or drawing to insert, the X-scale
factor, the Y-scale factor, the Z-scale factor, and the rotation angle.
When you insert an entire drawing into another drawing, AutoCAD treats
the inserted drawing like any other block reference. Subsequent insertions
reference the block definition (which contains the geometric description of
the block) with different position, scale, and rotation settings. If you
change the original drawing after inserting it, the changes have no effect on
the
inserted block. If you want the inserted block to reflect the changes you
made to the original drawing, you can redefine the block by reinserting the
original drawing. This can be done with the InsertBlock method.
If you insert a drawing as a block, the file name is automatically used as the
name of the block. You can change the name of the block by using the
Name property once the block has been created.
By default, AutoCAD uses the coordinate (0, 0, 0) as the base point for
inserted drawings. You can change the base point of a drawing by opening
the original drawing and using the SetVariable method to specify a different
insertion base point for the INSBASE system variable. AutoCAD uses the new
base point the next time you insert the drawing.
If the drawing you insert contains PaperSpace objects, those objects are not
included in the current drawings block definition. To use the PaperSpace
objects in another drawing, open the original drawing and use the Add
method to define the PaperSpace objects as a block. You can insert the drawing into another drawing in either paper space or model space.
A block reference cannot be iterated to find the original objects that
compose it. However, you can iterate the original block definition, or you
can explode the block reference into its original components.
You can also insert an array of blocks using the AddMInsertBlock method.
This method does not insert a single block into your drawing, as the InsertBlock does, but instead inserts an array of the specified block. This method
returns an MInsertBlock object.
For more information on inserting blocks, see Insert Blocks in chapter 16,
Draw Geometric Objects, in the Users Guide.
Define a block and insert the block into a drawing
This example defines a block and adds a circle to the block definition. It then
inserts the block into the drawing as a block reference.
Sub Ch10_InsertingABlock()
' Define the block
Dim blockObj As AcadBlock
Dim insertionPnt(0 To 2) As Double
insertionPnt(0) = 0
insertionPnt(1) = 0
insertionPnt(2) = 0
Set blockObj = ThisDrawing.Blocks.Add _
(insertionPnt, "CircleBlock")
' Add a circle to the block
Dim circleObj As AcadCircle
Dim center(0 To 2) As Double
Dim radius As Double
center(0) = 0
center(1) = 0
center(2) = 0
radius = 1
Set circleObj = blockObj.AddCircle(center, radius)
' Insert the block
Dim blockRefObj As AcadBlockReference
insertionPnt(0) = 2
insertionPnt(1) = 2
insertionPnt(2) = 0
Set blockRefObj = ThisDrawing.ModelSpace.InsertBlock _
(insertionPnt, "CircleBlock", 1#, 1#, 1#, 0)
ZoomAll
MsgBox "The circle belongs to " & blockRefObj.ObjectName
End Sub
Note
Sub Ch10_ExplodingABlock()
' Define the block
Dim blockObj As AcadBlock
Dim insertionPnt(0 To 2) As Double
insertionPnt(0) = 0
insertionPnt(1) = 0
insertionPnt(2) = 0
Set blockObj = ThisDrawing.Blocks.Add _
(insertionPnt, "CircleBlock")
' Add a circle to the block
Dim circleObj As AcadCircle
Dim center(0 To 2) As Double
Dim radius As Double
center(0) = 0
center(1) = 0
center(2) = 0
radius = 1
Set circleObj = blockObj.AddCircle(center, radius)
' Insert the block
Dim blockRefObj As AcadBlockReference
insertionPnt(0) = 2
insertionPnt(1) = 2
insertionPnt(2) = 0
Set blockRefObj = ThisDrawing.ModelSpace.InsertBlock _
(insertionPnt, "CircleBlock", 1#, 1#, 1#, 0)
ZoomAll
MsgBox "The circle belongs to " & blockRefObj.ObjectName
' Explode the block reference Dim
explodedObjects As Variant
explodedObjects = blockRefObj.Explode
' Loop through the exploded objects
Dim I As Integer
For I = 0 To UBound(explodedObjects)
explodedObjects(I).Color = acRed
explodedObjects(I).Update
MsgBox "Exploded Object " & I & ": " _
& explodedObjects(I).ObjectName
explodedObjects(I).Color = acByLayer
explodedObjects(I).Update
Next
End Sub
Redefine a Block
Use any of the Block object methods and properties to redefine a block.
When you redefine a block, all the references to that block in the drawing are
immediately updated to reflect the new definition.
acAttributeModeVerify
attribute value is
acAttributeModePreset
Sub Ch10_CreatingAnAttribute()
' Define the block
Dim blockObj As AcadBlock
Dim insertionPnt(0 To 2) As Double
insertionPnt(0) = 0
insertionPnt(1) = 0
insertionPnt(2) = 0
Set blockObj = ThisDrawing.Blocks.Add _
(insertionPnt, "BlockWithAttribute")
' Add an attribute to the block
Dim attributeObj As AcadAttribute
Dim height As Double
Dim mode As Long
Dim prompt As String
Dim insertionPoint(0 To 2) As Double
Dim tag As String
Dim value As String
height = 1
mode = acAttributeModeVerify
prompt = "New Prompt"
insertionPoint(0) = 5
insertionPoint(1) = 5
insertionPoint(2) = 0
tag = "New Tag"
value = "New Value"
Set attributeObj = blockObj.AddAttribute(height, mode, _
prompt, insertionPoint, tag, value)
' Insert the block, creating a block reference
' and an attribute reference
Dim blockRefObj As AcadBlockReference
insertionPnt(0) = 2
insertionPnt(1) = 2
insertionPnt(2) = 0
Set blockRefObj = ThisDrawing.ModelSpace.InsertBlock _
(insertionPnt, "BlockWithAttribute", 1#, 1#, 1#, 0)
End Sub
Backward
FieldLength
Height
InsertionPoint
Mode
PromptString
Rotation
ScaleFactor
TagString
Some of the methods you can use to edit the attribute include the following:
ArrayPolar
ArrayRectangular
Copy
Erase
Mirror
Move
Rotate
ScaleEntity
Sub Ch10_RedefiningAnAttribute()
' Define the block
Dim blockObj As AcadBlock
Dim insertionPnt(0 To 2) As Double
insertionPnt(0) = 0
insertionPnt(1) = 0
insertionPnt(2) = 0
Set blockObj = ThisDrawing.Blocks.Add _
(insertionPnt, "BlockWithAttribute")
' Add an attribute to the block
Dim attributeObj As AcadAttribute
Dim height As Double
Dim mode As Long
Dim prompt As String
Dim insertionPoint(0 To 2) As Double
Dim tag As String
Dim value As String
height = 1
mode = acAttributeModeVerify
prompt = "New Prompt"
insertionPoint(0) = 5
insertionPoint(1) = 5
insertionPoint(2) = 0
tag = "New Tag"
value = "New Value"
Set attributeObj = blockObj.AddAttribute(height, mode, _
prompt, insertionPoint, tag, value)
' Insert the block, creating a block reference
' and an attribute reference
Dim blockRefObj As AcadBlockReference
insertionPnt(0) = 2
insertionPnt(1) = 2
insertionPnt(2) = 0
Set blockRefObj = ThisDrawing.ModelSpace.InsertBlock _
(insertionPnt, "BlockWithAttribute", 1#, 1#, 1#, 0)
' Redefine the attribute text to display backwards.
attributeObj.Backward = True
attributeObj.Update
End Sub
Sub Ch10_GettingAttributes()
' Create the block
Dim blockObj As AcadBlock
Dim insertionPnt(0 To 2) As Double
insertionPnt(0) = 0
insertionPnt(1) = 0
insertionPnt(2) = 0
Set blockObj = ThisDrawing.Blocks.Add _
(insertionPnt, "TESTBLOCK")
' Define the attribute definition
Dim attributeObj As AcadAttribute
Dim height As Double
Dim mode As Long
Dim prompt As String
Dim insertionPoint(0 To 2) As Double
Dim tag As String
Dim value As String
height = 1#
mode = acAttributeModeVerify
prompt = "Attribute Prompt"
insertionPoint(0) = 5
insertionPoint(1) = 5
insertionPoint(2) = 0
tag = "Attribute Tag"
value = "Attribute Value"
' Create the attribute definition object on the block
Set attributeObj = blockObj.AddAttribute _
(height, mode, prompt, _
insertionPoint, tag, value)
' Insert the block
Dim blockRefObj As AcadBlockReference
insertionPnt(0) = 2
insertionPnt(1) = 2
insertionPnt(2) = 0
Set blockRefObj = ThisDrawing.ModelSpace.InsertBlock _
(insertionPnt, "TESTBLOCK", 1, 1, 1, 0)
ZoomAll
' Get the attributes for the block reference
Dim varAttributes As Variant
varAttributes = blockRefObj.GetAttributes
' Move the attribute tags and values into a
' string to be displayed in a Msgbox
Dim strAttributes As String
strAttributes = ""
Dim I As Integer
For I = LBound(varAttributes) To UBound(varAttributes)
strAttributes = strAttributes + " Tag: " + _
varAttributes(I).TagString + vbCrLf + _
"
Value: " + varAttributes(I).textString
Next
Update Xrefs
When you open or plot your drawing, AutoCAD reloads each xref to reflect
the latest state of the referenced drawing. After you make changes to an
externally referenced drawing and save the file, other users can access your
changes immediately by reloading the xref.
Attach Xrefs
Attaching an xref links one drawing (the reference file, or xref) to the current
drawing. When a drawing references an xref, AutoCAD attaches only the xref
definition to the drawing, unlike regular blocks, where the block definition
and the contents of the block are stored with the current drawing. AutoCAD
reads the reference drawing to determine what to display in the current drawing. If the reference file is missing or corrupt, its data is not displayed in the
current drawing. Each time you open a drawing, AutoCAD loads all
graphical and non-graphical (such as layers, linetypes, and text styles)
objects from ref- erenced files. If VISRETAIN is on, AutoCAD stores any
updated xref-dependent layer information in the current drawing.
You can attach as many copies of an xref as you want, and each can have
a different position, scale, and rotation. You can also control the
dependent layers and linetype properties that are defined in the xref.
To attach an xref, use the AttachExternalReference method. This method
requires you to input the path and file name of the drawing to be
referenced, the name the xref is to use in the current drawing, the insertion
point, the scale, and rotation information for the xref. The
AttachExternalReference method returns the newly created
ExternalReference object.
For more information on attaching xrefs, see Attach External References in
the Users Guide.
Attach an external reference to a drawing
This example displays all the blocks in the current drawing before and after
adding an external reference. This example uses the City map.dwg found in
the sample directory. If you do not have this image, or it is located in a different directory, insert a valid path and file name for the PathName variable
below.
Sub Ch10_AttachingExternalReference()
On Error GoTo ERRORHANDLER
Dim InsertPoint(0 To 2) As Double
Dim insertedBlock As AcadExternalReference
Dim tempBlock As AcadBlock
Dim msg As String, PathName As String
' Define external reference to be inserted
InsertPoint(0) = 1
InsertPoint(1) = 1
InsertPoint(2) = 0
PathName = "C:/Program Files/AutoCAD 2004/sample/City map.dwg"
' Display current Block information for this drawing
GoSub ListBlocks
' Add the external reference to the drawing
Set insertedBlock = ThisDrawing.ModelSpace. _
AttachExternalReference(PathName, "XREF_IMAGE", _
InsertPoint, 1, 1, 1, 0, False)
ZoomAll
' Display new Block information for this drawing
GoSub ListBlocks
Exit Sub
ListBlocks:
msg = vbCrLf
' Reset message
For Each tempBlock In ThisDrawing.Blocks
msg = msg & tempBlock.Name & vbCrLf
Next
MsgBox "The current blocks in this drawing are: " & msg
Return
ERRORHANDLER:
MsgBox Err.Description
End Sub
Overlay
Xrefs
Overlaying is similar to attaching, except when a drawing is attached or overlaid. Any other overlays nested in it are ignored and, therefore, not displayed.
In other words, nested overlays are not read in.
To
overlay
an
xref,
set
the
bOverlay
AttachExternalReference method to TRUE.
parameter
of
the
Detach
Xrefs
You can detach an xref definition to remove the xrefs completely from your
drawing. You can also erase the individual xref instances. Detaching the xref
definition removes all dependent symbols associated with that xref. If all the
instances of an xref are erased from the drawing, AutoCAD removes the xref
definition the next time the drawing is opened.
To detach an xref, use the Detach method. You cannot detach a nested
xref.
Detach an xref definition
This example attaches an external reference and then detaches the external
reference. This example uses the City map.dwg found in the sample
directory. If you do not have this image, or it is located in a different
directory, insert a valid path and file name for the PathName variable below.
Sub Ch10_DetachingExternalReference()
On Error GoTo ERRORHANDLER
' Define external reference to be inserted
Dim xrefHome As AcadBlock
Dim xrefInserted As AcadExternalReference
Dim insertionPnt(0 To 2) As Double
Dim PathName As String
insertionPnt(0) = 1
insertionPnt(1) = 1
insertionPnt(2) = 0
PathName = "c:/AutoCAD/sample/City map.dwg"
' Add the external reference
Set xrefInserted = ThisDrawing.ModelSpace. _
AttachExternalReference(PathName, "XREF_IMAGE", _
insertionPnt, 1, 1, 1, 0, False)
ZoomAll
MsgBox "The external reference is attached."
' Detach the external reference definition
Dim name As String
name = xrefInserted.name
ThisDrawing.Blocks.Item(name).Detach
MsgBox "The external reference is detached."
Exit Sub
ERRORHANDLER:
MsgBox Err.Description
End Sub
Reload
Xrefs
If someone modifies an externally referenced drawing while you are working
on the host drawing to which that xref is attached, you can update that xref
drawing using the Reload method. When you reload, the selected xref drawing is updated in your host drawing. Also, if you have unloaded an xref, you
can choose to reload that externally referenced drawing at any time.
Unload Xrefs
To unload an xref use the Unload method. When you unload a referenced
file that is not being used in the current drawing, the AutoCAD performance
is enhanced by not having to read and display unnecessary drawing geometry or symbol table information. The xref geometry and that of any nested
xref is not displayed in the current drawing until the xref is reloaded.
Unload an xref definition
This example attaches an external reference and then unloads the external
reference. This example uses the City map.dwg found in the sample
directory. If you do not have this image, or it is located in a different
directory, insert a valid path and file name for the PathName variable below.
Sub Ch10_UnloadingExternalReference()
On Error GoTo ERRORHANDLER
' Define external reference to be inserted
Dim xrefHome As AcadBlock
Dim xrefInserted As AcadExternalReference
Dim insertionPnt(0 To 2) As Double
Dim PathName As String
insertionPnt(0) = 1
insertionPnt(1) = 1
insertionPnt(2) = 0
PathName = "c:/AutoCAD/sample/City map.dwg"
' Add the external reference
Set xrefInserted = ThisDrawing.ModelSpace. _
AttachExternalReference(PathName, "XREF_IMAGE", _
insertionPnt, 1, 1, 1, 0, False)
ZoomAll
MsgBox "The external reference is attached."
' Unload the external reference definition
ThisDrawing.Blocks.Item(xrefInserted.name).Unload
MsgBox "The external reference is unloaded."
Exit Sub
ERRORHANDLER:
MsgBox Err.Description
End Sub
Bind Xrefs
Binding an xref to a drawing using the Bind method makes the xref a
perma- nent part of the drawing and no longer an externally referenced file.
The externally referenced information becomes a block. When the
externally referenced drawing is updated, the bound xref is not updated.
This process binds the entire drawings database, including all of its
dependent symbols. Dependent symbols are named objects such as blocks,
dimension styles, lay- ers, linetypes, and text styles. Binding the xref allows
named objects from the xref to be used in the current drawing.
The Bind method requires only one parameter: bPrefixName. If
bPrefixName is set to TRUE, the symbol names of the xref drawing are
prefixed in the current drawing with <blockname>$x$, where x is an integer
that is automat- ically incremented to avoid overriding existing block
definitions. If the bPrefixName parameter is set to FALSE, the symbol names
of the xref drawing are merged into the current drawing without the prefix.
If duplicate names exist, AutoCAD uses the symbols already defined in the
local drawing. If you are unsure whether your drawing contains duplicate
symbol names, it is rec- ommended that you set bPrefixName to TRUE.
For more information on binding xrefs, see Archive Drawings That Contain
External References (Bind) in the Users Guide.
Bind an xref definition
This example attaches an external reference and then binds the external
reference to the drawing. This example uses the City map.dwg found in the
sample directory. If you do not have this image, or it is located in a different
directory, insert a valid path and file name for the PathName variable below.
Sub Ch10_BindingExternalReference()
On Error GoTo ERRORHANDLER
' Define external reference to be inserted
Dim xrefHome As AcadBlock
Dim xrefInserted As AcadExternalReference
Dim insertionPnt(0 To 2) As Double
Dim PathName As String
insertionPnt(0) = 1
insertionPnt(1) = 1
insertionPnt(2) = 0
PathName = "c:/AutoCAD/sample/City map.dwg"
' Add the external reference
Set xrefInserted = ThisDrawing.ModelSpace. _
AttachExternalReference(PathName, "XREF_IMAGE", _
insertionPnt, 1, 1, 1, 0, False)
ZoomAll
MsgBox "The external reference is attached."
' Bind the external reference definition
ThisDrawing.Blocks.Item(xrefInserted.name).Bind False
MsgBox "The external reference is bound."
Exit Sub
ERRORHANDLER:
MsgBox Err.Description
End Sub
Clip the xref to display a small fraction of it, and a spatial index is saved
in the externally referenced drawing.
Freeze several layers of the xref, and the externally referenced drawing
is saved with a layer index.
0
1
2
3
= no indexes created
= layer index created
= spatial index created
= both spatial and layer indexes created
Sub Ch10_ViewXData()
' Find the selection created in previous example
Dim sset As Object
Set sset = ThisDrawing.SelectionSets.Item("SS1")
' Define the xdata variables to hold xdata information
Dim xdataType As Variant
Dim xdata As Variant
Dim xd As Variant
'Define index counter
Dim xdi As Integer
xdi = 0
' Loop through the objects in the selection set
' and retrieve the xdata for the object
Dim msgstr As String
Dim appName As String
Dim ent As AcadEntity
appName = "MY_APP"
For Each ent In sset
msgstr = ""
xdi = 0
' Retrieve the appName xdata type and value
ent.GetXData appName, xdataType, xdata
' If the xdataType variable is not initialized, there
' was no appName xdata to retrieve for that entity
If VarType(xdataType) <> vbEmpty Then
For Each xd In xdata
msgstr = msgstr & vbCrLf & xdataType(xdi) _
& ": " & xd
xdi = xdi + 1
Next xd
End If
' If the msgstr variable is NULL, there was no xdata
If msgstr = "" Then msgstr = vbCrLf & "NONE"
MsgBox appName & " xdata on " & ent.ObjectName & _
":" & vbCrLf & msgstr
Next ent
End Sub
Develop Applications
with VBA
In this chapter
Forms in VBA
Handle Errors
Encrypt VBA Code
Modules
Run a VBA Macro from a
Toolbar or Menu
Automatically Load a
VBA Project
Automatically Run a
VBA Macro
Automatically Open the
Document
State
Distribute Your
Application
309
Module
Macro
Dialog box
Form
Forms in VBA
Forms are the basic building blocks through which you create your own
custom dialog boxes for your application. Through custom forms you can
provide information to users, get information from users, or have your users
control activity in the application.
Forms are like an artists canvasthey start out blank. To fill your canvas, you
need a palette. In this case, your palette is the control toolbox. You, as the
artist, place selected controls from the toolbox onto the form. You can add
as many controls as you like. At any time you can adjust size and properties
of both the controls and even the form itself. Finally, you add the
functionality (code) to the controls that brings your form to life.
Although Visual Basic supports different types of forms, VBA supports only
the UserForm. This means some forms have been created and exported in
Visual Basic that cannot be imported into VBA.
UserFormsor forms, as they are called in this guidecan be modal or
mod- eless. The ShowModal property of a form determines whether it is
modal or modeless. Modal forms displayed in your running application
must be closed before users can perform any other action in the application.
For more infor- mation about working with modal forms, see Modal
Forms on page 315.
To create a new form in your project
1 Open the Project window of the VBA IDE and select the project you want
to add the form to.
2 From the Insert menu, choose UserForm.
A blank form is created and added to your project.
To create a modeless form in your project
1 Open the Project window of the VBA IDE and select the project you want
to add the form to.
2 From the Insert menu, choose UserForm, and change the
ShowModal property to False.
3 Add the AcFocusCtrl (AcFocusCtrl.dll) to the Toolbox, and drag the
control onto the form.
The AcFocusCtrl keeps the focus on the form during user interaction.
Design
Mode
and
Run
While you are building your form you are working in design mode, where
you can
form
Change the
properties of the
form
form
Add code
module
to the
form
While in design mode there is no interaction among the user, the user interface of AutoCAD, and your form.
Once you run your application, or your user runs your application, the form
is then in run mode. While in run mode you cannot make adjustments to the
Forms in VBA
55
form directly. However, the form is now displayed in the AutoCAD user
inter- face and the user can interact with the form as part of the normal
operation of your application.
Add Controls to a
Form
Adding controls to a form is easy. Simply select a control from the control
toolbox and drag it over to the form. When you release your mouse, a copy
of the control will be placed on the form. Once the control is on the form,
you can change the position and size of the control. You can copy over as
many controls as you like.
In addition to the drag method previously mentioned, there are other ways
of placing controls on a form.
Forms in VBA
57
The form you created is modal by default, so the user will not be able to
inter- act with AutoCAD directly while the form is displayed. For example,
the user cannot select a point or object in the drawing with the form
displayed. To allow the user access to the AutoCAD drawing, use the VBA
Hide method. The Hide method hides the form and allows the user limited
access to AutoCAD. When using the Hide method it is important to
remember the form is not unloaded from memory. It will retain all current
values while hidden.
The Hide method is called in the same manner as the Show method.
Display a form
This example will display the form named UserForm1:
Public Sub MyApplication()
UserForm1.Show
End Sub
The subroutine (and consequently the display of your form) is now callable
as a macro from the VBARUN command or from an AutoCAD menu.
Hide a form
This example hides the form named UserForm1:
Public Sub MyAppHide()
UserForm1.Hide
End Sub
Forms in VBA
59
Use
Show
Hide
Load
Unload
Unloads a form from memory. This can be done explicitly from the
Unload method, or automatically at the termination of the
application.
Modal Forms
When you define a dialog box as modal in AutoCAD VBA, the user must
respond to the dialog box before any other part of the application is
allowed to continue. No subsequent code is executed until the modal
dialog box is closed through either the Hide or Unload method. This
requires that you, as the developer of the application, think carefully about
how and when you implement dialog boxes.
For example, you may have a dialog box that requires the user to select an
object in the AutoCAD drawing. For the user to be able to pick the object
from the AutoCAD Application window you must hide the form by calling
the Hide method. Once the object has been selected you use the Show
method to redisplay the form, with all of its data still current, and
continue with the application.
Note Although other forms in the application are disabled when a modal
dialog box is displayed, other applications are not.
Handle Errors
Most development environments provide default error handling. For VB and
VBA, the default reaction to an error is to display an error message and
terminate the application. While this behavior is adequate during the development phase of your application, it is not productive for your end-user.
There may be errors that you want to ignore, or that you want to provide
special responses to. There may be errors that you will want to suppress the
error message display for, or simply control the message that gets displayed
to the user. In addition, automatically terminating the application is hardly
ever acceptable to the end-user.
In general, error handling is necessary whenever user-input is required and
whenever working with file I/O. Remember, even if you are sure a needed
file is there and available for processing, there may be conditions you
havent thought of that could cause errors.
Forms in VBA
61
Logic errors are the most difficult to find and correct. Symptoms of logic
errors include situations in which there are no compile-time errors and
no runtime errors, but the outcome of your program is still incorrect.
This is what programmers refer to as a bugand a bug can be very easy
or very difficult to track down.
The On Error Resume Next statement is used when you want to ignore
errors. This statement traps the error and instead of displaying an error
message and terminating the program, it simply moves on to the next line
of code and continues processing. For example, if you wanted to create a
sub- routine to iterate through model space and change the color of each
entity, you know that AutoCAD will throw an error if you try to color an
entity on a locked layer. Instead of terminating the program, simply skip
the entity on the locked layer and continue processing the remaining
entities. The On Error Resume Next statement lets you do just that.
The On Error GoTo Label statement is used when you want to write an
explicit error handler. This statement traps the error and instead of displaying an error message and terminating the program, it jumps to a specific
location in your code. Your code can then respond to the error in whatever
manner is appropriate for your application. For example, you can expand the
example above to display a message containing the handle for each entity
on the locked layer.
Handle Errors
61
The On Error GoTo 0 statement cancels the current error handler. The On
Error Resume Next and On Error GoTo Label statements remain in effect
until the subroutine ends, another error handler is declared, or the error
han- dler is canceled with the On Error GoTo 0 statement.
where filename is the name of the project file, modulename is the name of the
module containing the macro to be run, and macroname is the name of the
macro. The file name is only required when the file is not loaded in the current session of AutoCAD. If the file name is provided, the file will be loaded.
For more information on editing menus and toolbars, see Customize Toolbars and Menus.
You can cause a macro to run automatically when VBA loads by naming the
macro AcadStartup. Any macro in your acad.dvb file called AcadStartup
will automatically get executed when VBA loads.
Note To access the Open VBA Project dialog box, enter VBALOAD at the
com- mand line. The dialog box will open and allow you to choose a project to
load. If you do not see the Open VBA Project dialog box, it is most likely
because the system variable FILEDIA is turned off. This system variable turns on
and off the display of dialog boxes. To turn FILEDIA back on, set it to 1.
You must choose a distribution option that is appropriate for your application. Applications that are applicable to the current drawing, and do not
access other drawings, are often embedded in the drawing. By embedding
the application in the drawing, you can always be sure the application is
loaded, and therefore available to the user whenever the drawing is open.
Applications that are used by many people, are updated frequently, need to
open and close other drawings, or are not used frequently you may want to
store in a VBA project file. In this way, there is one central location for the
application, and everyone can be sure to use the latest version.
For more information on embedded projects and VBA project files, see
Understand Embedded and Global VBA Projects on page 12.
In this chapter
Windows
Applications
of the
from
VBA
LISP Applications
323
Note You must set the reference for each VBA project that will use this
Object Model. Setting the reference for one project wont automatically set it
for another project. This is for performance reasons.
To make a reference to another applications object library
1 In the VBA IDE, open the Tools menu and select the References menu
option.
2 Find and select the entry in the list of Available References for the application you want to access.
3 Select OK to close the dialog box with your changes.
After you declare the variable, use the Set statement with the New keyword
to set the variable equal to a running instance of the application. For example, the following Set statement sets the variable declared above equal to
the Excel application. The New keyword starts a new session of Excel.
Set ExcelAppObj = New Excel.Application
Note Some applications allow only one running instance of the application
at a time. Using the New keyword on such an application will establish a
reference to the existing instance and will not launch a new session of the
application.
Program with
Applications
Objects
from
Other
Now that you have referenced the object library and created a new instance
of the application, you can create and manipulate objects in that
application. All the objects, methods, and properties defined by the Object
Model are available to you. For example, using the variable declarations from
the previ- ous section, the following line of code makes the Excel session
visible to the user:
ExcelAppObj.Visible = TRUE
You should familiarize yourself with the Object Model of the application
you are writing code for. You can use the VBA Object Browser or the
applications help file to learn about any Object Model you are referencing.
Note Destroying or going beyond the scope of the object variable does not
necessarily cause the application to terminate. You should always quit the application using the appropriate method to assure proper memory cleanup.
List AutoCAD attributes on an Excel spreadsheet
This subroutine finds all the block references in the current drawing. It then
finds the attributes attached to those block references and lists them in an
Excel spreadsheet. To run this example, do the following:
1 Open a drawing containing block references with attributes. (The
sample drawing sample/activeX/attrib.dwg contains such block references.)
2 Open the VBA IDE using the AutoCAD VBAIDE command.
3 Using the Tools References menu option in the VBA IDE, select
Microsoft Excel 8.0 Object Model.
4 Copy this subroutine into a VBA Code window and run it.
Sub Ch12_Extract()
Dim Excel As Excel.Application
Dim ExcelSheet As Object
Dim ExcelWorkbook As Object
Dim
Dim
Dim
Dim
Dim
RowNum As Integer
Header As Boolean
elem As AcadEntity
Array1 As Variant
Count As Integer
The name of the dynamic link library (DLL) containing the procedure
you want to use
The name of the procedure as it appears in the DLL
The name of the procedure as you want to use it in your application
The parameters the procedure expects to receive
The return value data type (if the procedure you are calling is a function)
You can place the Declare statement in any of your VBA modules. If you
place it in a standard module, the procedure will be available to any module
in your application, unless you limit its scope by using the keyword Private.
If you place the Declare statement in a class or form module, the
procedure will only be available in that module. Once a procedure has been
declared, you can call that procedure as you would any other procedure in
your application.
Getting a Declare statement just right is a difficult skill to learn. Getting a
Declare statement wrong is easy, but it often comes with dire
consequences. Be sure to save any information in active applications before
you try out a new Declare statement.
To help you with your Declare statements, Microsoft provides a file listing
of many of the declarations most commonly used. The file is called
Win32api.txt and comes with Visual Basic and Office. You can search this
file for the procedure you need and copy the Declare statement provided
into your code.
In this chapter
Check Your
Environment
Get Input
Draw the Path Outline
Draw the Tiles
Tie It All Together
Step Through the Code
Execute the Macro
Add a Dialog Box
Interface
331
Notice that as soon as you press ENTER after entering the line Function
dtr(a As Double) As Double, End Function is added automatically.
This ensures that all subroutines and functions have an associated End
state- ment.
Now look at the code. First, the constant pi is defined as the value
3.14159. This allows you to use the word pi instead of typing 3.14159
each time you need to use the value.
Next, you are defining a function called dtr (short for degrees to
radians). The function dtr takes one argument, a, which is the angle in
degrees. The result is obtained by dividing the angle in degrees by 180,
and then mul- tiplying this value by pi. The line that begins with a single
quote is a com- ment; VBA ignores all text on a line after a single quote.
This function can now be used in other subroutines throughout your
project.
4 Save your work. Click File Save Global1. Name the project gardenpath.dvb.
Next, add a function to calculate the distance between points.
Get Input
The Gardenpath macro asks the user where to draw the path, how wide to
make the path, how large the concrete tiles are, and how closely to space
those tiles. You define a subroutine that asks the user for all of these
items and then computes various numbers to use in the rest of the macro.
In this subroutine, you use the user input methods found in the Utility
object.
Declare Variables
The next subroutine uses several variables. All variables must be declared
before the subroutine can access them.
In the VBA IDE, enter the following code in the Code window,
immediately after the line Const pi = 3.14159:
Private
Private
Private
Private
Private
Private
Private
Private
Private
Private
sp(0 To 2) As Double
ep(0 To 2) As Double
hwidth As Double
trad As Double
tspac As Double
pangle As Double
plength As Double
totalwidth As Double
angp90 As Double
angm90 As Double
Now look at the two drop-down lists at the top of the Code window. These
lists are called the Object Box and the Procedure/Event Box and currently
dis- play the terms (General) and (Declarations), respectively. These lists
display the current section of the code you are working in, and enable you
to move quickly to a different section by simply selecting one from the list.
The (Dec- larations) section is the appropriate place to declare variables that
you will use in more than one subroutine.
In the gpuser subroutine, the line Dim varRet As Variant declares the
vari- able varRet. Because this variable is used only in this subroutine, it can
be declared here locally, instead of in the (Declarations) section.
Get Input
79
Get Input
81
To find the corners of the path, use the PolarPoint method. This method
finds a point that is a given angle and distance from a base point. Begin
with the start point (sp) and find the first corner of the path, working in a
coun- terclockwise direction. This corner will be at a distance of half the
width of the path (hwidth) and at 90 degrees from the path angle. Because
you want to draw a closed rectangle for the path, this point becomes the
first and last point in the array. Hence, the X and Y coordinates returned
from the PolarPoint method are moved into the first and last positions in
the points array.
The remaining corners of the path are found in the same manner using the
length and width of the path (plength and width), and the angle of the
path. Every time the PolarPoint method is called, the coordinates returned
(varRet) are copied into the points array.
Once all the corners have been identified in the points array, the AddLightweightPolyline method is called. Notice that this method is called from the
ModelSpace object. If you were to run this macro, you would also notice
that the polyline is not yet visible in AutoCAD. The polyline will not
become visible until you update the display, which you will do later.
' Place one row of tiles the given distance along path
' and possibly offset it
Private Sub drow(pd As Double, offset As Double)
Dim pfirst(0 To 2) As Double
Dim pctile(0 To 2) As Double
Dim pltile(0 To 2) As Double
Dim cir As AcadCircle
Dim varRet As Variant
varRet = ThisDrawing.Utility.PolarPoint( _
sp, pangle, pd)
pfirst(0) = varRet(0)
pfirst(1) = varRet(1)
pfirst(2) = varRet(2)
varRet = ThisDrawing.Utility.PolarPoint( _
pfirst, angp90, offset)
pctile(0) = varRet(0)
pctile(1) = varRet(1)
pctile(2) = varRet(2)
pltile(0) = pctile(0)
pltile(1) = pctile(1)
pltile(2) = pctile(2)
Do While distance(pfirst, pltile) < (hwidth - trad)
Set cir = ThisDrawing.ModelSpace.AddCircle( _
pltile, trad)
varRet = ThisDrawing.Utility.PolarPoint( _
pltile, angp90, (tspac + trad + trad))
pltile(0) = varRet(0)
pltile(1) = varRet(1)
pltile(2) = varRet(2)
Loop
varRet = ThisDrawing.Utility.PolarPoint( _
pctile, angm90, tspac + trad + trad)
pltile(0) = varRet(0)
pltile(1) = varRet(1)
pltile(2) = varRet(2)
Do While distance(pfirst, pltile) < (hwidth - trad)
Set cir = ThisDrawing.ModelSpace.AddCircle( _
pltile, trad)
varRet = ThisDrawing.Utility.PolarPoint( _
pltile, angm90, (tspac + trad + trad))
pltile(0) = varRet(0)
pltile(1) = varRet(1)
pltile(2) = varRet(2)
Loop
End Sub
To understand how these subroutines work, refer to the following illustration. The subroutine drow draws a row of tiles at a given distance along the
path specified by its first argument, and offsets the row perpendicular to the
path by a distance specified by its second argument. You want to offset the
tiles on alternate rows to cover more space and make a more pleasing
arrangement.
TSPAC + 2 * TRAD
30 degrees
60 degrees
The drow subroutine finds the location for the first row by using the
PolarPoint method to move along the path by the distance specified by the
first argument. The subroutine then uses the PolarPoint method again to
move perpendicularly to the path for the offset. The subroutine uses the
While statement to continue to draw circles until the edge of the path is
encountered. The PolarPoint method in the first While statement moves on
to the next tile location by spacing a distance of two tile radii (trad) and one
intertile space (tspac). A second while loop then draws the tiles in the row
in the other direction until the other edge is encountered.
The drawtiles subroutine calls drow repeatedly to draw all the tile rows.
The subroutine While loop steps along the path, calling drow for each row.
Tiles in adjacent rows form equilateral triangles, as shown in the previous
illustra- tion. The edges of these triangles are equal to twice the tile radius
plus the spacing between the tiles. Therefore, by trigonometry, the distance
along the path between rows is the sine of 60 degrees multiplied by this
quantity, and the offset for odd rows is the cosine of 60 degrees multiplied
by this quantity.
The If statement is used in drawtiles to offset every other row. If the
offset is equal to 0, set it to the spacing between the centers of tiles
multiplied by the cosine of 60 degrees, as explained earlier. If the offset is
not equal to 0, set it to 0. This alternates the offset on the rows as you
want.
Save your work.
Tie It All
Together
You are ready to combine the subroutines into the Gardenpath macro. In the
VBA IDE, enter the following code in the Code window, after the drawtiles
subroutine:
' Execute command, calling constituent functions
Sub gardenpath()
Dim sblip As Variant
Dim scmde As Variant
gpuser
sblip = ThisDrawing.GetVariable("blipmode")
scmde = ThisDrawing.GetVariable("cmdecho")
ThisDrawing.SetVariable "blipmode", 0
ThisDrawing.SetVariable "cmdecho", 0
drawout
drawtiles
ThisDrawing.SetVariable "blipmode", sblip
ThisDrawing.SetVariable "cmdecho", scmde
End Sub
The path subroutine calls gpuser to gather the necessary input. The
GetVariable method is then used to obtain the current values of the
BLIPMODE and CMDECHO system variables, and saves these values as sblip
and scmde. The subroutine then uses the SetVariable method to set both of
these system variables to 0, thereby disabling blips and command echoing.
Next, the path is drawn using the drawout and drawtiles subroutines.
Finally, the SetVariable method is used to reset the system variables to their
original values.
You may notice that this is the only subroutine you have entered that did
not begin with a Private keyword, which ensures the subroutine can only
be called from within the current module. Because the gardenpath
subroutine must be available to the user, you should omit the Private
keyword.
Save your work.
You can experiment with the Gardenpath macro by specifying the various
inputs.
One by one, select and drag the following controls from the toolbox
and place them on the user form. You should place two option buttons (
),
three labels (
), three text boxes (
), and two command buttons ( ),
as illustrated on the following form:
1 On the user form, select the OptionButton1 control. On the View menu,
click Properties Window, and change the following properties for
OptionButton1:
(Name) = gp_poly
Caption = Polygon
ControlTipText = Polygon Tile Shape
Accelerator = P
2 On the user form, select the OptionButton2 control. In the Properties window, change the following properties for OptionButton2:
(Name) = gp_circ
Caption = Circle
ControlTipText = Circle Tile Shape
Accelerator = I
To set the properties for the label controls
1 On the user form, select the Label1 control. In the Properties window,
change the following properties for Label1:
(Name) = label_trad
Caption = Radius of tiles
TabStop = True
2 On the user form, select the Label2 control. In the Properties window,
change the following properties for Label2:
(Name) = label_tspac
Caption = Space between tiles
TabStop = True
3 On the user form, select the Label3 control. In the Properties window,
change the following properties for Label3:
(Name) = label_tsides
Caption = Number of sides
TabStop = True
To set the properties for the text box controls
1 On the user form, select the TextBox1 control. In the Properties
window, change the following property for TextBox1:
(Name) = gp_trad
2 On the user form, select the TextBox2 control. In the Properties
window, change the following property for TextBox2:
(Name) = gp_tspac
3 On the user form, select the TextBox3 control. In the Properties
window, change the following property for TextBox3:
(Name) = gp_tsides
To set the properties for the command button controls and the
form window
1 On the user form, select the CommandButton1 control. In the Properties
window, change the following properties for CommandButton1:
(Name) = accept
Caption = OK
ControlTipText = Accept the options
Accelerator = O
Default = True
2 On the user form, select the CommandButton2 control. In the Properties
window change the following properties for CommandButton2:
(Name) = cancel
Caption = Cancel
ControlTipText = Cancel the operation
Accelerator = C
3 Select the user form itself by clicking on the background of the form, away
from any control. In the Properties window, change the following properties for the form:
(Name) = gpDialog
Caption = Garden Path
Your form should now look like this:
trad As Double
tspac As Double
tsides As Integer
tshape As String
'
'
'
'
Updated
Updated
Add
Add
Because the code in the form accesses trad and tspac, you update their
definitions to make them public. Private variables are available only in the
module in which they are defined, so the variables need to be changed to
public. Additionally, you have added tsides for the number of polygon
tile sides and tshape for the users choice of tile shape, which is either
cir- cle or polygon.
3 Go to the gpuser subroutine. Remove the two lines that obtain the
radius of the tiles and the spacing between the tiles, because this
information comes from the form. Specifically, remove the following:
trad = ThisDrawing.Utility. _
GetDistance(sp, "Radius of tiles: ")
tspac = ThisDrawing.Utility. _
GetDistance(sp, "Spacing between tiles: ")
4 Add the lines that load and display the form. Add the following lines in
place of the lines removed in step 3:
Load gpDialog
gpDialog.Show
5 Add a subroutine to the end of the code file that draws either the
circular tiles or the polygon tiles:
'Draw the tile with the designated shape
Sub DrawShape(pltile)
Dim angleSegment As Double
Dim currentAngle As Double
Dim angleInRadians As Double
Dim currentSide As Integer
Dim varRet As Variant
Dim aCircle As AcadCircle
Dim aPolygon As AcadLWPolyline
ReDim points(1 To tsides * 2) As Double
'Branch based on the type of shape to draw
Select Case tshape
Case "Circle"
Set aCircle = ThisDrawing.ModelSpace. _
AddCircle(pltile, trad)
Case "Polygon"
angleSegment = 360 / tsides
currentAngle = 0
For currentSide = 0 To (tsides - 1)
angleInRadians = dtr(currentAngle)
varRet = ThisDrawing.Utility.PolarPoint(pltile, _
angleInRadians, trad)
points((currentSide * 2) + 1) = varRet(0)
points((currentSide * 2) + 2) = varRet(1)
currentAngle = currentAngle + angleSegment
Next currentSide
Set aPolygon = ThisDrawing.ModelSpace. _
AddLightWeightPolyline(points)
aPolygon.Closed = True
End Select
End Sub
' Updated
3 Place your cursor on the Private Sub gp_poly_Click() line and open the
Procedure/Event Box.
You see a list of all the events that you can respond to for the gp_poly
option control. The two subroutines you entered handle the Click
event. You can also add code to respond to the DblClick event that
would auto- matically execute when the user double-clicked the control.
You can add code for any of the events listed. These types of subroutines
are called event handlers.
Look at the code you entered for these two event handlers. The first event
handler responds to the Click event for the gp_poly option control. The
first line of code enables the text box for the number of sides. This text box
is available only for polygons, so it is not enabled unless you select the
Polygon control. The next line of code sets the tshape variable to
Polygon.
The second event handler responds to the Click event for the gp_circ
option control. This handler disables the text box for the number of sides
and sets the tshape variable to Circle.
4 Add the following event handler for the OK button:
Private Sub accept_Click()
If ThisDrawing.tshape = "Polygon" Then
ThisDrawing.tsides = CInt(gp_tsides.text)
If (ThisDrawing.tsides < 3#) Or _
(ThisDrawing.tsides > 1024#) Then
MsgBox "Enter a value between 3 and " & _
"1024 for the number of sides."
Exit Sub
End If
End If
ThisDrawing.trad = CDbl(gp_trad.text)
ThisDrawing.tspac = CDbl(gp_tspac.text)
If ThisDrawing.trad < 0# Then
MsgBox "Enter a positive value for the radius."
Exit Sub
End If
If (ThisDrawing.tspac < 0#) Then
MsgBox "Enter a positive value for the spacing."
Exit Sub
End If
GPDialog.Hide
End Sub
This code tests whether the final choice of shape was polygon. If so, the
code retrieves the number of sides from the gp_tsides control. The value
the user enters is stored in the Text property. Because it is stored as a text
string, you convert the string to the integer equivalent using the Visual
Basic CInt function. Once obtained, the event handler tests the range of
the value to make sure it is between 3 and 1024. If it is not, a message is
displayed and the event handler is exited without further processing. The
result is that a message is displayed and the user is given an opportunity
to change the value. After the OK button is clicked again, this event handler triggers and tests the value again.
The macro obtains radius and spacing values, but these values are
doubles, not integers, and are obtained using the CDbl function. These
values are also tested to make sure they are positive.
After the values are obtained and verified, the gpDialog.Hide statement
hides the form, passing control back to the subroutine that first called the
form.
5 Add the following event handler for the Cancel button:
Private Sub cancel_Click()
Unload Me
End
End Sub
This simple event handler unloads the form and ends the entire macro.
The only thing you havent done is add the initial values for the form.
There is an event called Initialize that applies to the form. It is executed
when the form is first loaded.
6 Add the following event handler for the form initialization:
Private Sub UserForm_Initialize()
gp_circ.Value = True
gp_trad.Text = ".2"
gp_tspac.Text = ".1"
gp_tsides.Text = "5"
gp_tsides.Enabled = False
ThisDrawing.tsides = 5
End Sub
This code sets the initial values for the form and for the tsides
variable. The tsides variable must be set to a positive number greater
than 3, even if the user selects a circle. To understand this, look in the
DrawShape sub- routine that you entered earlier. There is a variable there
called points that is defined using the number of sides for the polygon.
That variable gets memory allocated to it whether or not a polygon
shape has been requested. Because of this, tsides must have a valid
range defined for it. The user is free to change this value during macro
execution.
You can now save and run the macro from AutoCAD.
In this appendix
AutoLISP and
ActiveX/VBA
Comparison
353
+ (addition)
+ (addition operator)
(subtraction)
(subtraction operator)
* (multiplication)
* (multiplication operator)
/ (division)
/ (division operator)
= (equal to)
~ (bitwise not)
Not operator
1+ (increment)
1 (decrement)
abs
Abs function
acad_colordlg
Not provided
acad_strlsort
acad_helpdlg
action_tile
add_list
ads
AutoCAD.Application.ListADS method
alert
MsgBox function
and
And operator
angle
AutoCAD.Application.ActiveDocument.Utility.
AngleFromXAxis method
angtof
AutoCAD.Application.ActiveDocument.Utility.AngleToReal
method
angtos
AutoCAD.Application.ActiveDocument.Utility.
AngleToString method
append
apply
Not provided
arx
AutoCAD.Application.ListARX method
arxload
AutoCAD.Application.LoadARX method
arxunload
AutoCAD.Application.UnloadARX method
ascii
Asc function
assoc
Not provided
atan
Atn function
atof
CDbl Function
atoi
CInt Function
atom
atoms-family
Not provided
autoarxload
Not provided
autoload
Not provided
Boole
boundp
car/cdr
chr
Chr function
client_data_tile
close
AutoCAD.Application.Documents.Close method
command
AutoCAD.ActiveDocument.SendCommand method
cond
cons
cos
Cos function
cvunit
defun
dictadd
AutoCAD.Application.ActiveDocument.Dictionaries.Add
method
dictnext
AutoCAD.Application.ActiveDocument.Dictionaries.Item
method
dictremove
AutoCAD.Application.ActiveDocument.Dictionaries.
Dictionary.Delete method
dictrename
AutoCAD.Application.ActiveDocument.Dictionaries.
Dictionary.Rename method
dictsearch
AutoCAD.Application.ActiveDocument.Dictionaries.
Dictionary.GetName and GetObject methods
distance
distof
Not provided
done_dialog
end_image
end_list
entdel
AutoCAD.Application.ActiveDocument.collection_object.
Delete method
entget
AutoCAD.Application.ActiveDocument.collection_object.
property properties
entlast
AutoCAD.Application.ActiveDocument.Modelspace.
Item(count-1)
entmake
AutoCAD.Application.ActiveDocument.Modelspace.
Add<entityname> method
entmakex
AutoCAD.Application.ActiveDocument.Modelspace.
Add<entityname> method
entmod
entnext
AutoCAD.Application.ActiveDocument.collection.Item
method
entsel
AutoCAD.Application.ActiveDocument.SelectionSets
object/methods/properties
entupd
AutoCAD.Application.ActiveDocument.Modelspace.object.
Update method
eq
Not provided
equal
Eqv operator
*error*
Error object/method/properties
eval
Not provided
exit
AutoCAD.Application.Quit method
exp
Exp function
expand
Not provided
expt
^ (exponentiation operator)
fill_image
findfile
Dir function
fix
float
CDbl Function
foreach
gc
AutoCAD.Application.ActiveDocument.PurgeAll
gcd
Not provided
get_attr
get_tile
getangle
AutoCAD.Application.ActiveDocument.Utility.GetAngle
method
getcfg
AutoCAD.Application.Preferences.property property
getcname
Not provided
getcorner
AutoCAD.Application.ActiveDocument.Utility.GetCorner
method
getdist
AutoCAD.Application.ActiveDocument.Utility.GetDistance
method
getenv
AutoCAD.Application.Preferences.property property
getfiled
getint
AutoCAD.Application.ActiveDocument.Utility.GetInteger
method
getkword
AutoCAD.Application.ActiveDocument.Utility.GetKeyword
method
getorient
AutoCAD.Application.ActiveDocument.Utility.
GetOrientation method
getpoint
AutoCAD.Application.ActiveDocument.Utility.GetPoint
method
getreal
AutoCAD.Application.ActiveDocument.Utility.GetReal
method
getstring
AutoCAD.Application.ActiveDocument.Utility.GetString
method
getvar
AutoCAD.Application.GetVariable method
graphscr
AppActivate AutoCAD.Application.Caption
grclear
Obsolete function
grdraw
Not provided
grread
Not provided
grtext
AutoCAD.Application.ActiveDocument.Utility.Prompt
grvecs
Not provided
handent
AutoCAD.Application.ActiveDocument.ModelSpace.object.
Handle property
help
if
IfThenElse statement
initget
AutoCAD.Application.ActiveDocument.Utility.
InitializeUserInput
inters
AutoCAD.Application.ActiveDocument.Modelspace.object.
IntersectWith
itoa
Str function
lambda
Not provided
last
arrayname(UBound(arrayname))
length
UBound function
list
ReDim statement
listp
IsArray function
load_dialog
load
log
Log function
logand
And function
logior
Or function
lsh
Imp function
mapcar
Not provided
max
Max function
mem
Not provided
member
Use collection
menucmd
AutoCAD.Application.MenuBar object
menugroup
AutoCAD.Application.MenuGroup object
min
Min function
minusp
mode_tile
namedobjdict
AutoCAD.Application.ActiveDocument.Dictionaries
collection
nentsel
AutoCAD.Application.ActiveDocument.SelectionSets.
SelectionSet.SelectAtPoint method
nentselp
AutoCAD.Application.ActiveDocument.SelectionSets.
SelectionSet.SelectAtPoint method
new_dialog
not
nth
null
IsNull function
numberp
TypeName function
open
Open function
or
osnap
polar
AutoCAD.Application.ActiveDocument.Utility.PolarPoint
method
prin1
AutoCAD.Application.ActiveDocument.Utility.Prompt
princ
AutoCAD.Application.ActiveDocument.Utility.Prompt
AutoCAD.Application.ActiveDocument.Utility.Prompt
progn
Not provided
prompt
AutoCAD.Application.ActiveDocument.Utility.Prompt
quit
AutoCAD.Application.Quit method
quote
Not provided
read
Not provided
read-char
Input function
read-line
redraw
AutoCAD.Application.ActiveDocument.Modelspace.object.
Update method
regapp
AutoCAD.Application.ActiveDocument.
RegisteredApplications.Add method
rem
Mod function
repeat
ForEach, While,
reverse
Not provided
rtos
AutoCAD.Application.ActiveDocument.Utility.RealToString
method
set
Set function
set_tile
setcfg
AutoCAD.Application.Preferences.property property
setfunhelp
Not provided
setq
Set function
setvar
AutoCAD.Application.SetVariable method
sin
Sin function
setview
AutoCAD.Application.ActiveDocument.Viewports.Viewport.
SetView method
slide_image
snvalid
Not provided
sqrt
Sqr function
ssadd
AutoCAD.Application.ActiveDocument.SelectionSets.Add
method
ssdel
AutoCAD.Application.ActiveDocument.SelectionSets.
SelectionSet.Delete method
ssget
AutoCAD.Application.ActiveDocument.SelectionSets.
SelectionSet.SelectOnScreen method
ssgetfirst
Not provided
sslength
AutoCAD.Application.ActiveDocument.SelectionSets.
SelectionSet.Count method
ssmemb
ssname
AutoCAD.Application.ActiveDocument.SelectionSets.
SelectionSet.Name property
ssnamex
Not provided
sssetfirst
AutoCAD.Application.ActiveDocument.PickfirstSelectionSet
startapp
Shell function
start_dialog
start_image
start_list
strcase
StrConv function
strcat
& operator
strlen
Len function
subst
Not provided
substr
Mid function
tablet
Not provided
tblnext
AutoCAD.Application.ActiveDocument.collection_object.
Item method
tblobjname
AutoCAD.Application.ActiveDocument.collection_object.
Name method
tblsearch
AutoCAD.Application.ActiveDocument.collection_object.
Name method
term_dialog
terpri
Not provided
textbox
AutoCAD.Application.ActiveDocument.space.object.
GetBoundingBox method
textpage
Not provided
textscr
Not provided
trace
Not provided
trans
AutoCAD.Application.ActiveDocument.Utility.
TranslateCoordinates method
type
TypeName function
unload_dialog
untrace
Not provided
vector_image
ver
AutoCAD.Application.Version property
vports
AutoCAD.Application.ActiveDocument.Viewports collection
wcmatch
Like operator
while
WhileWend
write-char
Print function
write-line
Print function
xdroom
Not provided
xdsize
Not provided
zerop
Use = 0 syntax
Index
2D objects editing,
104 positioning,
249
3D modeling
3DSolid object, 252
Add 3DPoly method , 249 mirroring
(illustration), 255 rectangular arrays
(illustration), 255 rotating
(illustration), 253
solids
analyzing properties (list), 252
combining, 257
methods for creating (list), 252
wireframes, creating, 249
3D polylines, creating, 249
3DMesh object
example code, 249
3DSolid object
defined, 252
example code, 252, 254, 256
A
acad.dvb project file, 13
acad.tlb type library, migrating automation
projects to AutoCAD 2004, 9
ACAD_LAYERSTATE dictionary, 145
ACADProject file, 15
acAttributeModeConstant constant, 292
acAttributeModeInvisible constant, 292
acAttributeModeNormal constant, 292
acAttributeModePreset constant, 293
acAttributeModeVerify constant, 293
acax16enu.tlb type library, migrating automation
projects to AutoCAD 2004, 9
365
110 |
Index
AddDimOrdinate method
example code, 178
ordinate dimensions, 178
AddDimRadial method, 175
example code, 175
radial dimensions, 174
AddDimRotated method, 173, 174
AddEllipse method, 84
AddEllipticalCone method , 252
AddEllipticalCylinder method, 252
AddExtrudedSolid method, 252
AddExtrudedSolidAlongPath method, 252
AddFitPoint method, splines, 127
AddHatch method
creating objects, 90
example code, 92, 129, 131
AddItem method, 94
AddLeader method
creating leader lines, 188
example code, 188, 189
AddLightweightPolyline method
example code, 83, 109
Garden Path tutorial, 338
AddLine method
example code, 120, 123
object hierarchy, 38
AddMenuItem method
creating menu items, 202
example code, 197
AddMInsertBlock method, 7, 288
AddMText method
example code, 162, 163, 189
multiline text, 161
AddPoint method, example code, 85
AddPolyfaceMesh method
creating meshes, 250
example code, 251
AddPViewport method
example code, 269
paper space, 268
AddRaster method
attaching images, 280
example code, 281, 285
AddRegion method, 87
calculating total number of regions, 87
example code, 87, 88
AddRevolvedSolid method, 252
AddSeparator method, using Type property, 202
AddSolid method
creating solids, 252
example code, 86
solid-filled area, 86
AddSphere method, 252
AddSpline method, example code, 84, 128
AddSubMenu method, example code, 204
AddText method
example code, 154
AddTolerance method
example code, 191
geometric tolerance, 191
AddToolbarButton method, 210
creating flyout toolbars, 213
example code, 211, 214
AddTorus method, 252
AddVertex property, polylines, 125
AddWedge method
creating solids, 252
example code, 252
AddXLine method, in 3D, 68
AddXLine object, example code, 68
Alignment property, 158, 294
example code, 159
in text, 159
AltFontFile property, 166
AngleFromXAxis method, 70, 337
AngleToReal method, 70
AngleToString method, 71
angular dimensions
creating, 176
illustration, 170
annotations, and leader lines, 187
AppActivate event, 230
AppDeactivate event, 230
AppendInnerLoop method
boundaries, 91
example code, 129
hatches, 129
AppendOuterLoop method
boundaries, 91
example code, 92, 129, 131
hatches, 129
application level events
declaring objects with events, 232
enabling, 230
events (list), 230
Application object
collections, accessing, 41
declaring objects with events, 232
events (list), 230
example code, 232, 327
root object, accessing, 34
Application window
changing visibility, 34
finding state, 55
finding status, example code, 55
modifying, 34
sizing, 55
Visible property, 56
applications
declaring Windows APIs, 329
distribution options, 322
exchanging data with AutoCAD , 324
instances, creating, 326
object model referencing, 324
applications (continued)
quit methods, 327
referencing application objects, 326
variables, declaring, 326
applicaton-level events
enabling, 231
Arc object creating, 84
Area property, 89
calculating for closed objects, 71
example code, 72, 88
splines, 127
array data, converting to variants, 45
arraying, patterns, 105
ArrayPolar method
attributes, 295
creating arrays, 112
dimension editing, 179
Text object, 161
ArrayRectangular method, 113, 255
attributes, 295
dimension editing, 179
Text object, 161
arrays
polar arrays , 112
rectangular, 113
rectangular arrays , 112
ARXLoaded event, 230
ARXUnloaded event, 230
associative dimensions, defined, 173
AssociativeHatch property, 128
AttachExternalReference method
example code, 300, 302, 303
AttachExternalReference method, changes in
AutoCAD 2004, 7
AttachmentPoint property, 162
AttachToolbarToFlyout method, example code,
214
Attribute object editing,
294 example code,
297
attributes
associating, 292
in blocks (illustration), 292
constants (list), 292
creating references, 292
and definitions, 297 editing
methods (list), 295 editing
properties (list), 294
extracting, 292
and references, 297
for text, 292
visibility, 292
Auto Data Tips, Code window, 26
auto embedding, setting for VBA projects, 18
Auto Indent, Code window, 26
Auto List Member, Code window, 26
Auto Quick Info, Code window, 26
Index
111
B
backslash (\)
in macros, 222
Backward property
attributes, 294
base point, rotating objects, 116
BasePoint property, 68
BatchPlotProgress property, 275
BeginClose event, 234
BeginCommand event, 228, 230, 234
BeginDoubleClick event, 234
BeginFileDrop event
defined, 230
example code, 232
BeginLISP event, 230, 234
BeginModal event, 230
BeginOpen event, 228, 230
BeginPlot event, 230, 234
BeginQuit event, 230
BeginRightClick event, 234
BeginSave event, 230, 234
BeginShortcutMenuCommand event, 234
BeginShortcutMenuDefault event
defined, 234
example code, 237
BeginShortcutMenuEdit event, 234
BeginShortcutMenuGrip event, 234
BeginShortcutMenuOsnap event, 235
Big Font files, 153
BigFontFile property
example code, 154
TextStyle object, 151
Bind method
example code, 305
external references, 304
bitonal images. See raster images
BLIPMODE system variable, 342
Block object
example code, 288, 289
in layouts , 262
Block property, in layouts, 263
block references arrays
and, 288 base
points, 288
exploding, 287, 289
fastener (illustration), 288
iterating, 288
112 |
Index
C
calculations
AddRegion method, 87
performing in drawings, 65
CanonicalMediaName property, 263
cascading menus. See submenus
CELTSCALE system variable, 140
Center property
example code, 270
WCS coordinate, 43
character formatting, example code, 163
CheckInterference method, 257
example code, 257
child object
relation to root object, 43
Circle object, 43
creating, 84
example code, 87, 88, 106
circular references, 25
Clear method
in selection sets, 103
ClipBoundary method, 285
example code, 285
ClippingEnabled property, 283, 285
example code, 285
Close method
Documents collection, 52
Closed property
polylines, 125
splines, 126
CMDECHO system variable, 342
Code window
Garden Path tutorial in, 333
margin indicator bar, 22
Object Box, 335
Procedure/Event Box, 335
resizing, 22
settings, 26
split bar, 22
collections
adding members, 35
Application object, accessing, 41
available in AutoCAD (list), 39
Count Property, 36
defined, 39
Document object, accessing, 40
Documents, 34
Item method, 36
MenuBar, 194
MenuGroup, 194
as object groups, 35
Color property
example code, 94
layers, 137
obsolescence in AutoCAD 2004, 7
raster images, 283
See also TrueColor property
colors
assigning to objects, 138, 141
changing objects' colors, 142
changing, example code, 143
overriding layers' color settings, 143
command line
controlling user input, 75
in zero document state, 321
prompting user, 73
compile time
errors in VBA, 316
object referencing, 43
ConfigName property, 265, 276
construction lines
modifying, 67
rays, 67
xlines, 67
ContourlinesPerSurface property, 252
Contrast property, 284
control codes, text formatting (table), 165
ControlPoints property, splines, 126
controls for forms adding
code, 313 adding to
forms, 312 control
toolbox, 312
formatting in VBA for, 313
modifying, 312
conversion functions, operation methods, 37
converting coordinates, 245
coordinates
converting between systems , 245
Coordinates property
polylines, 125
Copy method, 106, 161, 179, 295
copying
arraying, 105
from one drawing to another, 106, 107
mirroring, 105
multiple objects, 106
objects to other drawings, 106, 107
offsetting, 105
single object, 106
CopyObjects method, 106
example code, 106, 107
Count property, 36
for menus, 200
CreateObject function
migrating automation projects to AutoCAD
2004, 8, 9
CreatePoint object
example code, 85
CreateRegion, example code, 87
CreateSolid object
example code, 86
CreateSpline object
example code, 84
CreateTypedArray method, 45, 71
creating lines
Add Polyline, 83
AddLightweightPolyline method, 83
AddLine method , 83
AddMLine method, 83
creating objects blocks
in, 82 graphical,
36 model space in,
82 nongraphical,
36 paper space in,
82
crosshairs
resizing, 54
Index
113
cursor
restricting with Ortho mode, 66
restricting with Snap mode, 66
cursor menus
adding new items, 225
creating, 199, 200
deleting, 200
on graphics screen, 199
Shortcut menu property, 225
truncating, 199
CursorSize property
crosshairs, resizing, 54
curved objects
arcs, 83
circles, 83
ellipses, 83
spline curves, 83
CustomDictionary property, 167
cylinder, example code for adding, 257
D
DatabasePreferences object
storing options, 54
DCS
converting coordinates, 247
definition, 247
DDIM Annotation dialog box, 180
DDIM Format dialog box, 180
DDIM Geometry dialog box, 180
Deactivate event, 235
Declare statement, 329
Default to Full Module View
Project window, 27 default
VBA project name, 15
Degree property
splines, 127
degrees
converting from radians, 333
Delete method, 61
collections, 117
deleting views, example code, 61
example code, 206
in selection sets, 104
layers, 137
linetypes, 140
DeleteFitPoint method
splines, 127
deleting
collection member, 42
demand loading
and indexes, 306
performance benefits, 306
Description property
example code, 140
linetypes, 140
design mode, VBA environment and, 311
114 |
Index
Detach method
example code, 302
external references, 302
dialog boxes
in modal forms, 315
macro, 16
options for VBA IDE, 26
Save Project, 25
VBA Manager, 13
dialog controls. See controls
DIESEL string expressions, 201
DimAligned object
example code, 180, 186
DimAngular object
example code, 177
DIMASSOC system variable, 173
DIMCLRD system variable, 192
DIMCLRT system variable, 190, 192
dimension lines
illustration, 171
dimension styles
active, 173
Add method, 180
creating dimensions, 180
modifying, 180
parent, 180
dimension styles (illustration), 180
dimension system variables
list, 171, 174
dimensions
and geometry, 187
angular, 170
angular (illustration), 176
annotations, 172
associative, 173
hook lines (illustration), 175, 188
in model space, 187
in paper space, 187
leader lines (illustration), 172, 187
LeaderLength setting, 176
linear, 170
methods, editing, 179
modifying, 173
ordinate (illustration), 177
properties, editing, 179
radial, 170
creating, 174
rotating, 174
text styles, 172
illustration, 172
types of illustration, 170
DIMFIT system variable, 174
DIMGAP system variable , 192
DIMJUST system variable, 171, 174
DIMLFAC system variable, 187
DimOrdinate object
example code, 178
DimRadial object
example code, 175
DIMTAD system variable, 171, 174
DIMTIH system variable, 171, 174
DIMTOFL system variable, 171, 174
DIMTOH system variable, 171, 174
DIMTXSTY system variable, 190
DIMTXT system variable, 190, 192
DIMTXTSTY system variable, 192
DIMUPT system variable, 171, 174
Direction property, 268
example code, 249, 269
DirectionVector property, 68
example code, 68
displacement vector, 115
Display Coordinate System
definition, 247
Display method
in viewports, 267
Display preference, Options dialog box, 53
Display property
example code, 268, 269
DisplayPlotPreview method, 275
DisplayScreenMenu property, 54
DisplayScrollBar property, 54
DistanceToReal method, 71
distributing applications
VB, 322
VBA, 322
Dock method
docking toolbars, 215
example code, 215
document level events
and Document object, 236
coding, 237
declaring objects with events, 236
document- level events
enabling, 233
Document object
ActiveViewport property, 62
as AutoCAD drawing, 34
declaring objects with events, 236
enabling events, 233
events (list), 233
example code, 237, 267, 269
model space, accessing, 34
modifying drawings, 52
paper space, accessing, 34
ZoomAll method, 60
ZoomExtents method, 60
Document window
creating views, 60
Delete method, 61
displaying views, 56
maximizing, 56
minimizing, 56
modifying position, 56
E
editing
2D objects, 104
macros, 17
nongraphical objects, 104
ElevateOrder method
splines, 127
Ellipse object
creating, 84
embedded projects
auto embed feature, 18
ThisDrawing object, 38
Index
115
116 |
Index
exploding
blocks, 123
objects, 123
polylines, 123
Export method, 78
for saved layer settings, 149
extended data
uses of, 36
with graphical objects, 36
external references
attaching, 300
binding, 304
defined, 299
demand loading, 306
detaching, 301
and indexes, 306
overlaying, 301
reloading, 302
unloading, 303
updating, 300
ExternalReference object
example code, 300, 302, 303, 305
F
Fade property, 284
FieldLength property, 295
FileDependencies object, 7
FileDependency object, 7
Files preference, Options dialog box, 53
FILLMODE system variable, 86
filter lists, 95101
example code, 96101
filter types, and DXF codes (table), 95
filtering
example code, 96
selection sets, 95101
FitPoints property
splines, 126
FitTolerance property
splines, 126
Float method
floating toolbars, 215
flyout button, 211
Flyout property
ToolbarItem object, 218
flyout toolbars
AddToolbarButton method, 213
example code, 214
FontFile property, 151, 153
example code, 154
FontFileMap property, 166
fonts
alternative, specifying, 166
and text styles, 166
assigning in drawings, 152
Big Font files, 153
fonts (continued)
exporting in drawings, 153
font mapping tables, 166
SHX fonts, 153
substituting, 166
substitution rules, 166
TEXTFILL system variable, 153
TrueType, 153
Unicode, 153
form controls. See controls
Format menu
VBA IDE, 313
formatting characters
example code, 163
forms
adding controls, 312
control toolbox, 312
displaying, 314
formatting controls in VBA, 313
hiding, 314
hiding in Garden Path tutorial, 352
importing into VBA, 21
loading at runtime, 314
as macros, 314
modal dialog boxes, 315
modal versus modeless, 311
modal, defined, 314
mode, setting, 311
modifying controls, 312
unloading, 314
VBA environment, 311
VBA project component, 20
visibility at runtime, 313
Freeze property, 136
G
Garden Path tutorial
adding dialog boxes, 344
AddLightweightPolyline method, 338
Code window (illustration), 350
creating dialog boxes (illustration), 345
creating new macro, 332
determining corners, 339
determining values, 351
dtr function, 333
entering code, 333
event handling, 351
GetDistance method, 336
GetPoint method, 336
gpuser subroutine, 335
hiding forms, 352
installing VBA environment, 332
locating rows, 341
macro control, 343
Index
117
H
Hatch object
AppendInnerLoop method, 91
AppendOuterLoop method, 91
AssociativeHatch property, 128
associativity, 90, 128
boundaries, 91
Boundary Hatch dialog box, 131
creating, 90
editing, 128, 131
example code, 92, 129, 131
handling islands, 91
patterns, 90, 131
specifying loops, 90
hatches, editing, 128
HatchStyle property
definitions (table), 91
handling islands, 91
Height property, 151, 154, 283, 295
example code, 154, 270
Help, status line
for menus and toolbars, 224
HelpString property
ToolbarItem object, 211, 217
hierarchy
accessing objects in VBA, 38
referencing objects, 38
hook lines
illustration, 188
I
image boundaries, defined, 282
ImageFile property, 281
ImageHeight property, 283
ImageVisibility property, 284
ImageWidth property, 283
Import method
file conversions , 78
for saved layer settings, 149
importing forms,
21 modules,
21
Index property
ToolbarItem object, 217
INDEXCTL system variable, 306
indexes
and demand loading, 306
and external references, 306
InitializeUserInput
example code, 75
InitializeUserInput method, 73, 319
(list), 75
defining keywords, 75
InsertBlock method, 287
example code, 288, 289
118 |
Index
K
keywords
command line, 75
user input keywords, 75
Knots property
splines, 126
L
Label property
accelerator key, 203
Labels for menus
captions, 201
special codes, 201
LAYER command
macros, 222
Layer object
example code, 105, 134, 135
layer properties, saving. See layer settings, saving
Layer property, 142, 268
raster images, 283
layer settings
deleting saved settings
example code, 148
exporting saved settings, 149
example code, 150
importing saved settings, 149
example code, 150
listing saved settings, 145
managing, 146
renaming saved settings
example code, 148
restoring saved settings, 148
Load method
example code, 139, 195
linetypes, 139, 143
MenuGroups collection, 195
loading
ObjectARX applications, 34
VBA projects on startup, 320
loading projects
in AutoCAD, 13
in VBA, 25
Lock property, 136
loops
defining regions, 87
LowerLeftCorner property
illustration, 62
LTSCALE system variable, 140
M
macro libraries, 25
Macro property, 202, 320
ToolbarItem object, 211, 217
macros
and projects, 12 backslash
character, 222 canceling
commands, 222
command handling, 223
creating in tutorial, 332
delays (list), 222
editing, 17
enabling virus protection, 19
ERASE command, 224
guidelines for writing, 218
in menus, 218
in toolbars, 218
in VBA, 18
LAYER command, 222
naming, 16
object selection, single, 223
running, 17
running on startup, 320
SELECT command, 222
setting Break mode, 18
special characters (table), 219
stepping into, 18
terminating, 220
use of repetition, 223
user input, 221
Macros dialog box, 16
VBARUN command, 30
MainDictionary property, 167
matrix
See transformation matrices
maximizing, Document window, 56
MAXSORT system variable, 65
MClose property, 249
menu macros
special characters (table), 219
menu objects
ActiveX (illustration), 194
See also PopupMenu objects
MenuBar collection, 194
inserting menus, 197
object model (illustration), 195
rearranging menus, 198
removing menus, 198
MenuBar object
example code, 198
MenuBar property
example code, 198
MenuGroup object
example code, 195, 196, 197
MenuGroups collection, 194
Load method, 195
modifying (list), 195
new groups, creating, 196
object model (illustration), 194
popup menus and, 194
and toolbars, 194
See also menu objects
menus
assigning menu items, 208
checking, 207
creating submenus, 203
deleting, 205
disabling, 207
enabling, 207
menu macros, special characters, 208
positioning, 207
returning submenus, 208
type of menu item, 208
meshes
density, defined, 249
polyface mesh, creating, 250
rectangular, defined, 249
and solids, 249
and wireframes, 249
methods. See specific method names
migrating automation projects to AutoCAD
2004, 8, 9
minimizing, Document window, 56
MInsertBlock object, 288
Mirror method, 110, 161, 179
example code, 111
illustration, 110
Mirror3D method, 255
example code, 256
mirroring
example code, 111
in 3D, 255
objects, 105
Text objects, 110
with two coordinates, 110
N
Name property
example code, 105
layers, 133
linetypes, 140
O
Object Coordinate System
definition, 246
object level events
and event handlers, 239
and VBA keywords, 238
class modules, 238
enabling, 238
object libraries
AutoCAD as Automation controller, 3
referencing in VBA IDE, 325
object methods, defined, 42
object model
MenuBar collection (illustration), 195
MenuGroups collection (illustration), 194
ObjectAdded event, 235
ObjectARX applications
specific actions, 34
ObjectARXPath property, obsolescence in
AutoCAD 2004, 8
ObjectErased event, 235
ObjectModified event, 235
object-oriented, VBA interface, 3
objects
active, resetting, 65
assigning colors, 138
changing colors, 142
changing layers, 142
objects (continued)
closed
calculating area (illustration), 71
defining from user input points, 71
creating, 82
enabling events, 238
existing, modifying, 104
exploding, 123
extending, 122
for menus, 194
graphical, 36
in ActiveX, 32
in ActiveX (list), 2
moving along a vector, 115
named, specifying, 104
nongraphical, 36
object component, 20
offsetting, 109
open, calculating area (illustration), 71
properties, defined, 42
removing from selection sets, 103
rotating in 3D, 253
scale factor, 118
scaling, 118
ThisDrawing, 17
transforming, 119
trimming, 122
See also specific object names
ObliqueAngle property, 151, 155, 158
obliquing angles, in text
illustration, 155
OCS
converting coordinates, 246
creating polylines, 83
definition, 246
Offset method, 109
creating objects, 43
example code, 109
offsetting, objects, 105
On Error
forms of (list), 317
VBA statement, example code, 318
Open method
Documents collection, 52
example code, 52
Open method, changes in AutoCAD 2004, 8
Open VBA Project dialog box, 321
opening VBA IDE
from command line, 19
from menu bar, 19
OpenSave preference, Options dialog box, 53
operating system
rebooting, 4
options
setting for VBA projects, 18
P
paper space
accessing objects, 35
and model space, switching, 268
creating objects, 82, 272
defined, 262
dimensioning in, 187
editing models, 265
example code, 82
hidden lines, 274
layouts, 262
plotting, 275
referencing in ActiveX code, 82
returning objects, 39
scaling linetypes, 274
scaling views, 272
viewports, floating, 265
zooming (illustration), 274
Paper Space Display Coordinate System
definition, 247
PaperSpace property, 82
PaperUnits property, 263
parent objects
relation to root object, 43
Parent property
ToolbarItem object, 218
PatternAngle property, 131
PatternDouble property, 131
PatternName property, 131
patterns
asssigning hatch patterns, 90
PatternScale property, 131
PatternSpace property, 131
example code, 131
PatternType constants
defined, 91
pausing macros
delays (list), 222
PDMODE system variable
illustration, 84
PDSIZE system variable
illustration, 84
PICKADD system variable, 219
PICKAUTO system variable, 219
Plot object, 275
example code, 276, 277
Plot dialog box, 37
PlotConfiguration object, 263
PlotHidden property, 274
plotting
in model space, 275, 276 in
paper space, 275, 277 layout
input values (list), 263
methods (list), 275
properties (list), 275
PlotToDevice method, 275
example code, 276, 277
PlotToFile method, 275
PlotType property
example code, 276
Point object
controlling appearance of, 84
creating, 84
example code, 85
polar arrays
center point, specifying, 112
creating, 112
example code, 112
reference points, 112
PolarPoint method, 71, 339
PolyfaceMesh object
example code, 251
PolygonMesh object, 249
Polyline object, 125
creating, 83
defining from user input points, 72
polylines
creating in OCS, 83
editing, 125
exploding, 123
fit and spline fit, 125
modifying, 125
PopupMenu object
creating submenus, 203
deleting menu items, 205
example code, 197, 198, 200
InsertInMenuBar method, 197
menu items, ordering (illustration), 201
PopupMenuItem object
accelerator keys, assigning, 203
AddSeparator method, 202
Caption property, 207
projects
.dvb file, 24
automation. See automation projects
circular references, 25
components in VBA, 20
embedded, 12, 14, 29
extracting, 15
global, 12, 29
importing, 21
loading in AutoCAD, 13
migrating to AutoCAD 2004, 8, 9
naming in VBA IDE, 24
referencing, 25
setting options for VBA, 18
unloading, 14
VBA default name, 15
VBA terms defined, 29
prompts for user input
Garden Path tutorial, 332
PromptString property, 295
Properties window
VBA IDE, 24
properties. See specific property names
PSDCS
converting coordinates, 247
definition, 247
PSLTSCALE system variable, 274
pull-down menus
creating, 199
from menu bar, 199
truncating, 199
PurgeAll method
example code, 104
purging, named objects, 104
PViewport object, 265
example code, 268, 269, 270
Q
QuietErrorMode property, 275
Quit method
example code, 327
R
radial dimensions
creating, 174
illustration, 170
TextPosition property, 174
radians
converting degrees, 333
RadiiOfGyration property, 252
raster images
and vector files, 280
attachments, 280
bitonal images, 284
clipping (illustration), 285
RemoveItems method
in selection sets, 103
RemoveMenuFromMenuBar method
from PopupMenus collection, 198
RenderSmoothness property, 252
Require Variable Declaration
Code window, 26
Reverse method
splines, 127
RGB values
assigning colors to objects, 138
changing objects' colors, 142
right-click menu. See cursor menu
root object
accessing, 39
hierarchy, 39
relation to parent object, 43
See also Application object
Rotate method, 116, 161, 179
example code, 117
Rotate3D method, 253
example code, 254
rotating objects, 116
illustration, 116
rotation angles, 155
Rotation property, 158, 162, 179, 295
run mode, in VBA environment, 311
running macros, 17
runtime
error trapping, 317
errors in VBA, 316
object referencing, 43
S
sample code, finding for ActiveX and VBA, 6
SAT files
exporting to, 78
importing, 78
SAVE command
from VBA IDE, 25
Save method
for layer settings, 147
verifying changes, 53
Save Project dialog box
accessing, 25
VBAUNLOAD command, 30
SaveAs method, 52
example code, 196
SaveAs method, changes in AutoCAD 2004, 8
saved layer settings. See layer settings
saving projects, in VBA IDE, 25
scale factor
illustration, 118
object dimensions, 118
ScaleEntity method, 118, 179, 191, 283, 295
example code, 119
T
Tag property, 201
ToolbarItem object, 217
TagString property, 295
attribute references, 297
example code, 297
terminating macros
code examples, 220
terminology in VBA environment (list), 310
Text object
aligning in drawings (illustration), 159
angles, setting, 155
displaying backward, 156
displaying upside down, 156
example code, 154, 156, 159
formatting, 158
height settings, 154
line text, 150
line text, creating, 157
methods (list), 161
mirroring text, 110
modifying, 161
mtext, 150
ObliqueAngle property, 155
properties (list), 158
spell check, 166
text generation flag, 156
used in drawings, 150
text styles
changing properties, 152
creating, 151
current, 151
default, 151
for dimensions, 172
properties (table), 151
TextAlignmentPoint property, 158
example code, 159
TEXTFILL system variable, 153
TextGenerationFlag property, 151, 152, 156,
158
example code, 155, 156
TextOverride property
example code, 180
Toolbars collection
Add method, 209
Name property, 209
transformation matrices
assigning matrix to variable, 120
rotation (table), 121
scaling (table), 121
transforming objects
translation (table), 121
transformation matrix
user coordinate system, 244
world coordinate system , 244
TransformBy method, 119
example code, 120
TranslateCoordinates method, 71
converting coordinates, 245
example code, 244, 247
true colors
assigning to objects, 138 changing
objects' colors, 142 changing,
example code, 143 overriding layers'
color settings, 143
TrueColor property
changing objects' colors, 142
example code, 143
new properties in AutoCAD 2004, 7
See also Color property
TrueType fonts, 153
height settings, 154
tutorial
See Garden Path tutorial
type libraries
adding reference, 43
defined, 43
type libraries, migrating automation projects to
AutoCAD 2004, 9
Type property
example code, 212
ToolbarItem object, 218
TypeName function, 46
U
UCS
converting coordinates, 246
definition, 246
UCSIconAtOrigin property, 244
UCSIconOn property, 244
UCSORG system variable , 244
Unicode fonts, 153
table, 165
uniting regions
Region object, 89
Unload method
example code, 303
external references, 303
unloading
ObjectARX applications, 34
Update method, 123
example code, 64
for text styles, 152
redrawing objects, 104
Text object, 159
UpperRightCorner property
illustration, 62
User Coordinate System
axis location, 244
definition, 246
origin point location, 244
viewports, 244
user input
Garden Path tutorial, 332, 334
user input functions
prompting, 37
user input methods
GetInteger method, 73
GetKeyword , 74
GetPoint, 74
GetPoint method, 73
GetString, 74
GetString method, 73
user input pausing macros, 221
User preference, Options dialog box, 53
UserForm
window
editing forms , 22
UseStandardScale property, 264
Utility object
calculating area, 71
calculation methods (list), 70
example code, 244
functions, 37
TranslateCoordinates method, example
code, 247
user input methods, 73
V
variants
CreateTypedArray method, 45
defined, 44
input arrays , 44
output arrays, 44
polyline editing, 124
Typename function, 46
VarType function, 46
VarType function, 46
VB
ActiveX Automation interface
changed items, 7
new objects, 7
automation projects. See automation
projects
VBA
ActiveX Automation interface
changed items, 7
new objects, 7
automation projects. See automation
projects
VBA environment
accessing applications, 325
application distribution, 322
control toolbox (illustration), 310
design mode, 311
dialog boxes, creating, 310
End statement, 333
forms, 310, 311
installing for tutorial, 332
password protection, 319
referencing object libraries, 325
run mode, 311
running macros, 320
terminology (list), 310
Windows API procedures, accessing, 329
working in a zero document state, 321
VBA Hide method, 314
VBA IDE
"Hello World" exercise, 28
defined, 29
macro execution, 18
opening, 19
opening on project load, 321
Properties window, 24
referencing object libraries, 325
SAVE command, 25
viewing project data, 19
VBA interface
advantages
with ActiveX, 4
with AutoCAD, 3
elements of, 4
environment, 3
implementing in AutoCAD, 3
VB, similarities with, 3
with ActiveX interface, 3
VBA Load method, 314
VBA Manager
creating projects, 15
defined, 30
dialog box, 13
embedding projects, 14
extracting projects, 15
loading projects, 13
saving projects, 15
unloading projects, 14
VBA methods, (table), 315
VBA Object Browser, 325
VBA programming using ActiveX, 4
VBA projects
acad.dvb file, 320
virus protection
enabling for macros, 19
setting for VBA projects, 19
using project code, 14
Visible property, 56 example
code, 214 setting,
example code, 56
Visual Basic, 47
Visual Basic automation projects
migrating to AutoCAD 2004, 8, 9
Visual Basic for Applications. See entries beginning
with VBA
Visual Basic. See VB
Visual LISP
accessing objects, 324
calling methods, 324
retrieving methods, 324
Volume property, 252
W
WBlock method, 287
leader lines, 189
WCS
converting coordinates, 246
definition, 246
wedges
adding, example code, 252
Width property, 151, 283
example code, 270
WindowChanged event, 231, 235
WindowMovedOrResized event, 231, 235
Windows APIs
accessing from VBA, 329
WindowState property, 56
WithEvents
declaring objects with events, 232, 236
enabling objects with events, 239
GetObject, VBA function
example code, 232
VBA Keyword, example code, 232, 236
WMF files
exporting to, 78
World Coordinate System
definition, 246
entering coordinates, 242
X
xdata. See extended data
Xline object, 67
XLOADCTL system variable, 306
XMLDatabase object, removed in AutoCAD
2004, 8
XRefDemandLoad property, 306
xrefs. See external references
Z
zero document state, 321
Zoom Center method
illustration, 59
zoom scale, specifying, 58
Zoom window
example code, 57
ZoomAll method, 59
example code, 60, 83, 85, 86
illustration, 60
ZoomCenter method, 59
example code, 59
ZoomExtents method
example code, 60, 270
illustration, 60
in active viewport, 59
zooming
defined, 57
in paper space (illustration), 274
scale factors, 272
zoom scales, 274
ZoomPickWindow method, 57
example code, 57
ZoomScaled method , 58, 273
example code, 58, 270
ZoomWindow method, 57