Introduction
Introduction

Any task you can perform within AutoCAD Mechanical can be automated with macros, scripts, or custom external programs. This guide shows you how to use Visual Basic for Applications (VBA) macros to control the program, saving time in repetitive or specialized tasks, helping to enforce company standards, and easing collaboration with other AutoCAD Mechanical users.

One mechanism for manipulating AutoCAD Mechanical programmatically from within or outside AutoCAD Mechanical is the AutoCAD Mechanical COM/ActiveX Automation API. This API exposes AutoCAD Mechanical objects (including program features and drawing components) to the outside world. Once these objects are exposed, they can be read and controlled by many different programming languages and environments and by other applications.

AutoCAD Mechanical includes the Visual Basic for Applications integrated development environment (IDE), enabling you to develop macros easily inside AutoCAD Mechanical. You can also leverage the AutoCAD Mechanical COM/ActiveX Automation API from any compatible programming environment, like Visual Studio, or any other program that uses COM/ActiveX, like Microsoft Word or Excel.

Copyright© 2018, Autodesk, Inc. All rights reserved.
What do you think about this topic? Send Feedback


Who Should Read this Guide
Who Should Read this Guide

This AutoCAD Mechanical Developer's Guide is intended to help Visual Basic and Visual Basic for Applications (VBA) developers take advantage of the API (Application Programming Interface) features of AutoCAD Mechanical. It is not intended to be a substitute for the Reference Guide.

To use this guide effectively, you should understand the basics of VBA, AutoCAD ActiveX automation, and drawing in AutoCAD Mechanical. You should also have a general idea of how to work with objects, object models, and components.


Opening the VBA IDE
Opening the VBA IDE

There are three ways to open the VBA IDE:

  • press Alt+F11
  • type VBAIDE at the Command prompt
  • select Visual Basic Editor from the Manage menu


Configuring the VBA IDE
Configuring the VBA IDE

To use API features in the VBA IDE, the IDE needs a reference to find the libraries that include the appropriate objects, methods, etc.

To include a reference to a library in the VBA development environment, open the References dialog box in the VBA IDE (Tools > References)

...and place a check mark next to the relevant library.

About the Libraries

The Autodesk AutoCAD Mechanical 8.0 Type Library (AcadmAuto.dll) is for creating, querying, and manipulating AutoCAD Mechanical-specific constructs, such as the 2D Mechanical Structure.

The Autodesk BRepAuto 2.0 Type Library (BrepAuto.dll) is for querying topological information from a geometric item, when that information is present. AutoCAD solid models are B-rep (boundary representation) solids, which consist of a collection of topological and geometric entities. B-rep data represents the boundary between the inside and outside of a solid. AutoCAD Mechanical VBA interacts with the boundary representation query library, AcBr, to access topological and geometric data. The B-rep data can then be traversed to get connectivity information.

The Autodesk GeAuto 9.0 Type Library (GeAuto.dll) interacts with the geometry library, AcGe, and consists of utility classes for performing common 2D and 3D algebra, such as vectors and matrices. It provides geometric objects such as points, curves, and surfaces. For an example showing the use of the GeAuto library in a VBA application, see the "Working with 2D Mechanical Structure" overview.

The Autodesk SymBBAuto 10.0 Type Library (SymBBAuto[xxx].tlb, where xxx denotes the language version) provides access to the Bill of Materials and symbol standards, and provides symbols-related support. The English language version of this file is called SymBBAutoEnu.tlb, and is typically located in ...\Program Files\Common Files\Autodesk Shared


API Overviews and VBA Sample Code
Topics

This section shows examples of using VBA to manipulate AutoCAD Mechanical, including detailed explanations.


2D Mechanical Structure
Topics
Introduction to 2D Mechanical Structure

Users of 3D modeling software are accustomed to viewing and detailing objects from many viewpoints. A top view might be used for a plan, a front view for an elevation, and so on. The required views can be extrapolated from the 3D model.

But what if you don't want to use, or don't have, a 3D model? You must draw your views manually in the traditional manner, perhaps using third angle projection. Ideally though, a system of grouping and manipulating conceptual components and views would help. This is exactly the purpose of the 2D Mechanical Structure feature of AutoCAD Mechanical. It groups AutoCAD objects sensibly, with the aid of a browser. It emulates many of the advantages of AutoCAD blocks, but without the disadvantages (objects are still editable AutoCAD objects, with no need to use REFEDIT).

In AutoCAD Mechanical, this analogy to the familiar AutoCAD block is called the folder. You can place multiple instances of a folder, with the same economies as that of blocks. However, folders go a step further with a type of folder called a component view. Component views allow multiple named views of a given component. In the following example, a cylinder component is detailed using two views, to show it not only in plan, but also in elevation.

Figure 1

In the preceding figure, notice the Mechanical Browser pane on the left. The component view named elev is highlighted and selected. The corresponding drawing geometry is also highlighted. If the component CYLINDER in the browser were selected, the geometry of both component views would be highlighted. So the component doesn't contain part or assembly geometry directly, but it contains the component views, or folders, that do.

A Look at the 2D Mechanical Structure API

There a many objects in the 2D Mechanical Structure API, as shown in the following figure, but there are several objects and methods that are the key to getting started quickly.

The 2D structure manager object, Mcad2DStructureMgr, provides a host of methods and properties. This object serves to create or provide access to folders, views, component definitions, in fact the majority of the constructs that comprise the 2D mechanical structure. Use the Mcad2DStructureMgr object to obtain the root component definition, and then add new McadComponentDefinition and McadComponentView objects to the collection.

Summary

The core functionality of AutoCAD Mechanical, that which is apparent through use of the 2D Mechanical Structure browser pane, is available to the developer through the AutoCAD Mechanical API library, AcadmAuto. This API library provides a suite of objects, method and properties that allow applications to manipulate the 2D Mechanical Structure, creating and manipulating folders, components, component views and related constructs.


2D Mechanical Structure Sample Code

2D Mechanical Structure Sample Code

This simple example uses the API to perform a similar task to that shown in Figure 1. We'll create an object in AutoCAD Mechanical, and then add it as a component to the mechanical structure, complete with a component view.

Note:
Before running this code, check that the required libraries are referenced in your project. In the VBA editor, go to Tools > References, and if the following type libraries are not checked, check them.

  • Autodesk AutoCAD Mechanical 2.0 Type Library
  • Autodesk GeAuto 8.0 Type Library

Copy Code
Sub MakeCompAndView()
Dim center(0 To 2) As Double
Dim circle1 As AcadCircle

center(0) = 0
center(1) = 0
center(2) = 0

Set circle1 = ThisDrawing.ModelSpace.AddCircle(center, 10)

Dim gObjId As Long
gObjId = circle1.ObjectID

Dim gAcmApp As AcadmApplication
Dim gMgr As Mcad2DStructureMgr

Set gAcmApp = ThisDrawing.Application.GetInterfaceObject("AcadmAuto.AcadmApplication")
Set gMgr = gAcmApp.ActiveDocument.StructureMgr2D

Dim gGeApp As GeApplication
Dim compGeMatrix As GeMatrix
Dim compTranslation As GeVector
Dim startPoint As GePoint
Dim endPoint As GePoint

Set gGeApp = ThisDrawing.Application.GetInterfaceObject("GE.Application")
Set endPoint = gGeApp.Point
Set startPoint = gGeApp.Point
Set compTranslation = gGeApp.Vector
Set compGeMatrix = gGeApp.matrix

endPoint.Set 10, 10, 0
compTranslation.Set startPoint, endPoint
compGeMatrix.SetToTranslation compTranslation

Dim selectedObj As AcadObject
Set selectedObj = ThisDrawing.ObjectIdToObject(gObjId)

If gMgr.IsFreeEntity(selectedObj) = False Then
    Dim selFolder As McadFolder
    Set selFolder = gMgr.GetStructureFromEntity(selectedObj)
    If Not selFolder Is Nothing Then
        MsgBox ("Entity already belongs to a component view!")
        Exit Sub
    End If
End If

Dim compName As String
Dim viewName As String
compName = "MyComponent"
viewName = "FirstView"

Dim compDef As McadComponentDefinition

If gMgr.HasComponentDefinition(compName, compDef) = True Then
    MsgBox compName & " already exists."
    Exit Sub
End If

Dim parentCompDef As McadComponentDefinition
Set compDef = gMgr.AddNewComponentDefinition(compName)
Set parentCompDef = gMgr.RootComponentDefinition

Dim comp As McadComponent
Set comp = parentCompDef.AddComponent(compDef, compGeMatrix)

Dim compView As McadComponentView
Dim compViewDef As McadComponentViewDefinition
Dim targetView As McadComponentView

Dim entities(0) As Long
entities(0) = gObjId

gMgr.AddNewComponentViewDefinition compViewDef, compView, comp, compGeMatrix, , entities, targetView, viewName

ZoomExtents
End Sub

The results of the preceding sample code should appear as follows.

Figure 2


2D Mechanical Structure Sample Code Detailed Explanation
2D Mechanical Structure Sample Code Detailed Explanation

This simple example uses the API to perform a similar task to that shown in Figure 1. We'll create an object in AutoCAD Mechanical, and then add it as a component to the mechanical structure, complete with a component view.

Assuming we start with a clean drawing, the first step is to create a standard AutoCAD object. For the sake of code brevity we'll create a single entity - a circle centered at 0,0,0 with a radius of 10. In reality, each component view would likely be comprised of many entities.

Add the following code to the ThisDrawing code module in the AutoCAD Mechanical VBA editor. This code omits error checking for the sake of clarity. Always check that return values are of the expected type.

Note:
Before running this code, check that the required libraries are referenced in your project. In the VBA editor, go to Tools > References, and if the following type libraries are not checked, check them.

  • Autodesk AutoCAD Mechanical 2.0 Type Library
  • Autodesk GeAuto 8.0 Type Library

Copy Code
Sub MakeCompAndView()
Dim center(0 To 2) As Double
Dim circle1 As AcadCircle

center(0) = 0
center(1) = 0
center(2) = 0

Set circle1 = ThisDrawing.ModelSpace.AddCircle(center, 10)

Dim gObjId As Long
gObjId = circle1.ObjectID

The preceding code obtains the object ID. This isn't strictly necessary here since we are only working with a single object, but ordinarily consider maintaining an array of object IDs to keep persistent links to your entities.

The next step obtains a reference to the AutoCAD Mechanical application object. If you study the object model diagram, you'll see that this is the root object for the entire API. From this we can obtain the active document's Mcad2DStructureMgr object.

Copy Code
Dim gAcmApp As AcadmApplication
Dim gMgr As Mcad2DStructureMgr

Set gAcmApp = ThisDrawing.Application.GetInterfaceObject("AcadmAuto.AcadmApplication")
Set gMgr = gAcmApp.ActiveDocument.StructureMgr2D

The manipulation of AutoCAD objects is frequently eased by using the Geometry API, typically referred to as the AcGe library. This is a non-product-specific API that provides mathematical objects and services, typically used when working with matrices. We'll obtain a reference to this API's root application object too, together with associated point, matrix and vector objects. We'll use these to move the AutoCAD geometry later. The use of matrices greatly simplifies the manipulation of multiple entities.

Copy Code
Dim gGeApp As GeApplication
Dim compGeMatrix As GeMatrix
Dim compTranslation As GeVector
Dim startPoint As GePoint
Dim endPoint As GePoint

Set gGeApp = ThisDrawing.Application.GetInterfaceObject("GE.Application")
Set endPoint = gGeApp.Point
Set startPoint = gGeApp.Point
Set compTranslation = gGeApp.Vector
Set compGeMatrix = gGeApp.matrix

Set the matrix to perform a translation to 10,10. This matrix will be used to position the component view.

Copy Code
endPoint.Set 10, 10, 0
compTranslation.Set startPoint, endPoint
compGeMatrix.SetToTranslation compTranslation

Perform a check on the entity to ensure it is not already part of an existing component view. First, get the AutoCAD entity based on the object Id obtained earlier, and then use the IsFreeEntity method of the Mcad2DStructureMgr object to determine if the entity is already consumed by the mechanical structure. This is a wise check to perform, although here is should not fail as we have only just created the entity from code.

Copy Code
Dim selectedObj As AcadObject
Set selectedObj = ThisDrawing.ObjectIdToObject(gObjId)

If gMgr.IsFreeEntity(selectedObj) = False Then
    Dim selFolder As McadFolder
    Set selFolder = gMgr.GetStructureFromEntity(selectedObj)
    If Not selFolder Is Nothing Then
        MsgBox ("Entity already belongs to a component view!")
        Exit Sub
    End If
End If

When we create the component and view, we'll want to name them.

Copy Code
Dim compName As String
Dim viewName As String
compName = "MyComponent"
viewName = "FirstView"

But first we'll check that a component definition with this name doesn't already exist. The Mcad2DStructureMgr object provides the HasComponentDefinition method for this purpose.

Copy Code
Dim compDef As McadComponentDefinition

If gMgr.HasComponentDefinition(compName, compDef) = True Then
    MsgBox compName & " already exists."
    Exit Sub
End If

Now create two component definition objects. One is the the root component definition to which the new component definition will be added. The second, new component definition object is created with the AddNewComponentDefinition method of the Mcad2DStructureMgr object. Note that we have not yet associated these two objects with each other.

Copy Code
Dim parentCompDef As McadComponentDefinition
Set compDef = gMgr.AddNewComponentDefinition(compName)
Set parentCompDef = gMgr.RootComponentDefinition

Here we actually add the new definition as a component in the mechanical structure. In this instance, the position matrix has no function, since we are not yet adding a component view with associated geometry.

Copy Code
Dim comp As McadComponent
Set comp = parentCompDef.AddComponent(compDef, compGeMatrix)

Now that we have a component defined in the structure, we must add a view containing geometry. For this we'll use the AddNewComponentViewDefinition method of the Mcad2DStructureMgr object. This creates both the view definition and the component view itself. The method populates its arguments with the newly created objects - an McadComponentViewDefinition object and an McadComponentView object, here declared as compViewDef and compView, respectively. If you want to specify a specific parent component view for your new component view, you do so through the targetView argument. Note that AddNewComponentViewDefinition requires that entities for the component view be supplied as an array of object Ids.

Copy Code
Dim compView As McadComponentView
Dim compViewDef As McadComponentViewDefinition
Dim targetView As McadComponentView

Dim entities(0) As Long
entities(0) = gObjId

gMgr.AddNewComponentViewDefinition compViewDef, compView, comp, compGeMatrix, , entities, targetView, viewName

Now all we need to do is zoom to extents to see the results.

Copy Code
ZoomExtents
End Sub

The results of the preceding sample code should appear as follows.

Figure 2


XREFs and 2D Mechanical Structure
Topics
XREFs and 2D Mechanical Structure

AutoCAD users will be familiar with the concept of external references - that is, AutoCAD's ability to incorporate other drawing files into an open document, with behavior similar to block instances. This feature allows re-use of common details or components. Such common files can be updated in a collaborative fashion, with changes reflected in the "parent" or referencing documents.

AutoCAD Mechanical drawings contain a lot of additional information, for example, 2D structure data concerning components and views. If an external drawing file containing 2D structure information is referencing an AutoCAD Mechanical document, how can the 2D structure information in the referenced file be accessed? Can it be "imported" into the referencing (parent) document? Can data in the referencing document be "exported" to the referenced file (the XREF)?

The AutoCAD Mechanical API provides methods to do all these. You can attach an Xref using the base AutoCAD API, and then use the AutoCAD Mechanical API to access the mechanical data and import (or, more accurately, localize) the data into the parent document. So, definitions for folders, component views, and so on can be added to the 2D structure of the parent document and instantiated. The reverse is also true. Structures in the parent document can be exported (externalized) to the Xref.

Once the 2D structure information has been localized or externalized, the Xref is no longer required and can be removed. The folders and components views that have been localized remain in the parent document. Anything externalized to the Xref will remain in that file, independent of any reference links.

A Look at the Mechanical Structure Xrefs API

As with much of the AutoCAD Mechanical API, the key object is the Mcad2DStructureMgr object. When an Xref is attached, its database is made available through the ExternalStructureDatabases property of the Mcad2DStructureMgr object. Once this database is referenced, its 2D Structure data can be accessed, and if required, localized into the parent document.

Several objects in the 2D Structure API provide methods to localize or externalize structure data. These are:

  • McadAnnotationViewDefinition
  • McadComponentViewDefinition
  • McadFolderDefinition

Note that these are all definition objects. Instances of folders and component views contained in the Xref may not be localized directly. Their definitions are localized and then the Mechanical API is used to place instances in the conventional way.


XREFs and 2D Mechanical Structure Sample Code
XREFs and 2D Mechanical Structure API Sample Code

This simple code example attaches one of the tutorial sample files as an external reference. It localizes all of that file's component definitions into the parent document, and adds them to the 2D Mechanical Structure browser.

Add the following code to the ThisDrawing code module in the AutoCAD Mechanical VBA editor. This code omits error checking for the sake of clarity and brevity. Always check that return values are of the expected type.

Copy Code
Private Sub AttachXref()

Dim mApp As AcadmApplication
Dim mGeApp As GeApplication
Dim mMgr As Mcad2DStructureMgr

Set mApp = ThisDrawing.Application.GetInterfaceObject("AcadmAuto.AcadmApplication")
Set mGeApp = ThisDrawing.Application.GetInterfaceObject("GE.Application")
Set mMgr = mApp.ActiveDocument.StructureMgr2D

Dim InsertPoint(0 To 2) As Double
Dim insertedBlock As AcadExternalReference
Dim PathName As String

InsertPoint(0) = 1: InsertPoint(1) = 1: InsertPoint(2) = 0
PathName = "C:/Program Files/Autodesk/Acadm 2007/Acadm/Tutorial/TUT_GRIPPER.dwg"

Set insertedBlock = ThisDrawing.ModelSpace.AttachExternalReference(PathName, "XREF_IMAGE", InsertPoint, 1, 1, 1, 0, False)

Dim dbs As Variant
dbs = mMgr.ExternalStructureDatabases(ThisDrawing.Database)
If UBound(dbs) = -1 Then
MsgBox ("Could not get external dwg database")
Exit Sub
End If

Dim ExtCompDefs As McadComponentDefinitions
Dim db As AcadDatabase

Set db = dbs(0)
Call mMgr.GetComponentDefinitions(ExtCompDefs, False, db)
If ExtCompDefs.Count = 0 Then
MsgBox ("Could not get component definitions from external dwg database")
Exit Sub
End If

Dim extCompDef As McadComponentDefinition
For Each extCompDef In ExtCompDefs
If extCompDef.isFeature = False Then
extCompDef.Localize2DS (True)
Debug.Print "Localized " + extCompDef.Name

Dim compGeMatrix As GeMatrix
Dim parentCompDef As McadComponentDefinition
Dim comp As McadComponent

Set compGeMatrix = mGeApp.matrix
Set parentCompDef = mMgr.RootComponentDefinition
Set comp = parentCompDef.AddComponent(extCompDef, compGeMatrix)

End If

Next extCompDef

insertedBlock.Delete
ZoomExtents

End Sub

Note: Before running this code, check that the required libraries are referenced in your project. In the VBA editor, go to Tools > References, and if the following type libraries are not checked, check them.

  • Autodesk AutoCAD Mechanical 2.0 Type Library
  • Autodesk GeAuto 8.0 Type Library

Figure 1 shows the results of the preceding sample code.

Figure 1

The AutoCAD Mechanical 2D structure browser is now populated with the component definitions localized from the external reference. With these definitions present in the document, component views may now be defined in the normal fashion - or component views may also be localized from the external reference.

Also consider -

This sample demonstrates localization of 2D structure component definitions. With minor changes, the code can also externalize component definitions from the parent document to an external reference. Use the Externalize method of the McadFolderDefinition, McadComponentViewDefinition or McadAnnotationViewDefinition objects.


XREFs and 2D Mechanical Structure Sample Code Detailed Explanation
XREFs and 2D Mechanical Structure API Sample Code - Detailed Explanation

This simple code example attaches one of the tutorial sample files as an external reference. It localizes all of that file's component definitions into the parent document, and adds them to the 2D Mechanical Structure browser.

Add the following code to the ThisDrawing code module in the AutoCAD Mechanical VBA editor. This code omits error checking for the sake of clarity and brevity. Always check that return values are of the expected type.

The first thing to do is set up references to the AutoCAD Mechanical and GE (Geometry) automation objects. These provide access to the API, starting with the Mcad2DStructureMgr and GeApplication objects.

Copy Code
Private Sub AttachXref()

Dim mApp As AcadmApplication
Dim mGeApp As GeApplication
Dim mMgr As Mcad2DStructureMgr

Set mApp = ThisDrawing.Application.GetInterfaceObject("AcadmAuto.AcadmApplication")
Set mGeApp = ThisDrawing.Application.GetInterfaceObject("GE.Application")
Set mMgr = mApp.ActiveDocument.StructureMgr2D

We'll attach the TUT_GRIPPER file from the AutoCAD Mechanical tutorial. If your directory hierarchy is different, you must modify the file path in this code. The insertion point is 1,1,0.

Copy Code
Dim InsertPoint(0 To 2) As Double
Dim insertedBlock As AcadExternalReference
Dim PathName As String

InsertPoint(0) = 1: InsertPoint(1) = 1: InsertPoint(2) = 0
PathName = "C:/Program Files/Autodesk/Acadm 2007/Acadm/Tutorial/TUT_GRIPPER.dwg"

Now we have the file path, name, and insertion point, use the AttachExternalReference method of the AutoCAD API to attach the sample drawing as an Xref. If successful, this method returns an object of type AcadExternalReference.

Copy Code
Set insertedBlock = ThisDrawing.ModelSpace.AttachExternalReference(PathName, "XREF_IMAGE", InsertPoint, 1, 1, 1, 0, False)

With any Xrefs attached that contain 2D mechanical structure data, the ExternalStructureDatabases property of the Mcad2DStructureMgr object will return references to new databases. If this fails, for example, if the Xrefs do not contain any AutoCAD Mechanical data, then we can go no further, so exit the code.

Copy Code
Dim dbs As Variant
dbs = mMgr.ExternalStructureDatabases(ThisDrawing.Database)
If UBound(dbs) = -1 Then
MsgBox ("Could not get external dwg database")
Exit Sub
End If

Now we can obtain the collection of component definitions, but first we must reference the external database as type AcadDatabase. Here the code just assumes that the first item in the collection of external databases is the one we want, but in reality you would probably want to iterate through the collection. If the database has no component definitions, exit the code.

Copy Code
Dim ExtCompDefs As McadComponentDefinitions
Dim db As AcadDatabase

Set db = dbs(0)
Call mMgr.GetComponentDefinitions(ExtCompDefs, False, db)
If ExtCompDefs.Count = 0 Then
MsgBox ("Could not get component definitions from external dwg database")
Exit Sub
End If

Now that we have the collection of component definitions, we can iterate through them, localizing each in turn. If the type of definition is a feature the localization will fail, so check for this.

Copy Code
Dim extCompDef As McadComponentDefinition
For Each extCompDef In ExtCompDefs
If extCompDef.isFeature = False Then
extCompDef.Localize2DS (True)
Debug.Print "Localized " + extCompDef.Name

The preceding code segment debug-prints the name of each definition to the VBA IDE. In the case of the TUT_GRIPPER sample file, the list is a follows:

  • Localized GRIPPER
  • Localized CLAMP
  • Localized STROKE
  • Localized CYLINDER
  • Localized LEVER
  • Localized JOINT

We want to add each definition to the AutoCAD Mechanical 2D Structure browser, using the AddComponent method of the root McadComponentDefinition. This method expects a locating matrix, but in this case the argument is required but not used, so the matrix need not be set to anything meaningful.

Adding each definition to the root component definition means that these definitions, localized from the Xref, now populates the 2D Structure browser of the parent document.

Copy Code
Dim compGeMatrix As GeMatrix
Dim parentCompDef As McadComponentDefinition
Dim comp As McadComponent

Set compGeMatrix = mGeApp.matrix
Set parentCompDef = mMgr.RootComponentDefinition
Set comp = parentCompDef.AddComponent(extCompDef, compGeMatrix)

End If

Loop to the next component definition in the collection.

Copy Code
Next extCompDef

Now that all the definitions have been localized, the Xref can be removed. Here we also perform a zoom extents to clean up the graphics area.

Copy Code
insertedBlock.Delete
ZoomExtents

End Sub

Note: Before running this code, check that the required libraries are referenced in your project. In the VBA editor, go to Tools > References, and if the following type libraries are not checked, check them.

  • Autodesk AutoCAD Mechanical 2.0 Type Library
  • Autodesk GeAuto 8.0 Type Library

Figure 1 shows the results of the preceding sample code.

Figure 1

The AutoCAD Mechanical 2D structure browser is now populated with the component definitions localized from the external reference. With these definitions present in the document, component views may now be defined in the normal fashion - or component views may also be localized from the external reference.

Also consider

This sample demonstrates localization of 2D structure component definitions. With minor changes, the code can also externalize component definitions from the parent document to an external reference. Use the Externalize method of the McadFolderDefinition, McadComponentViewDefinition or McadAnnotationViewDefinition objects.


Attaching Data to Mechanical Structure
Topics
Introduction to Attributes in AutoCAD Mechanical Structures

AutoCAD Mechanical can apply attributes to structures and definitions. It uses this internally for parts lists and BOM data. Some attributes cannot be edited, while others can be overridden. Of more interest to the programmer is the ability to add your own custom attributes.

You may want to add data that is specific to your environment or application. You can add fields of various types including strings, numbers, or identifiers for other objects. The Utility object of the AutoCAD Mechanical API provides access to methods for creating and manipulating attributes. Additionally, you can work with attribute classes (define classes of attribute fields for a specific use) through methods supported by the AcadmApplication object.

A Look at the Attributes API

The API for reading and writing attributes is quite straightforward. First, determine the following:

  • What data types are required?
  • What is your naming convention?
  • Will you use an existing attribute class or create your own?
  • What objects will you attach the attribute to?

A number of objects allow attributes to be attached to them. These include McadCurve, McadArc, McadAugmentedLine, McadComponent, McadComponentDefinition, McadEllipse, McadLine, McadPolyline, and McadSpline. If you intend to use your own attribute class, first use the AddAttributeClass method of the AcadmApplication object.


Attaching Data to Mechanical Structure, Code Sample 1
Attaching Data to Mechanical Structure - Code Sample 1
Private Sub AddAttrib()
  Dim gApp As AcadmApplication
  Dim gMgr As Mcad2DStructureMgr
  Dim gUtil As McadUtility
  Set gApp = ThisDrawing.Application.GetInterfaceObject("AcadmAuto.AcadmApplication")
  Set gMgr = gApp.ActiveDocument.StructureMgr2D
  Set gUtil = gApp.ActiveDocument.Utility
  Dim gCompDefs As McadComponentDefinitions
  Dim compDef As McadComponentDefinition
  gMgr.GetComponentDefinitions gCompDefs, False
  Set compDef = gCompDefs.Item(1)
  Dim newAttrName As String
  Dim newAttrValue As String
  Dim attrType As McadFieldType
  newAttrName = "test_attrib"
  newAttrValue = "Pete"
  attrType = mcString
  Dim newAttr As McadAttribute
  Set newAttr = gUtil.CreateSystemAttribute(newAttrName, attrType)
  newAttr.FieldValue(1) = newAttrValue
  compDef.AddAttribute newAttr
  Debug.Print "Added attribute " + newAttrName + " with value " + newAttrValue
End Sub


Attaching Data to Mechanical Structure, Code Sample 2
Attaching Data to Mechanical Structure - Code Sample 2
Private Sub ListAttrib()
  Dim gApp As AcadmApplication
  Dim gMgr As Mcad2DStructureMgr
  Dim gUtil As McadUtility
  Set gApp = ThisDrawing.Application.GetInterfaceObject("AcadmAuto.AcadmApplication")
  Set gMgr = gApp.ActiveDocument.StructureMgr2D
  Set gUtil = gApp.ActiveDocument.Utility
  Dim gCompDefs As McadComponentDefinitions
  Dim compDef As McadComponentDefinition
  gMgr.GetComponentDefinitions gCompDefs, False
  Set compDef = gCompDefs.Item(1)
  Dim attrs As McadAttributes
  Set attrs = compDef.GetAttributes
  Dim attr As McadAttribute
  For Each attr In attrs
    Debug.Print attr.FieldValue(0)
    Debug.Print attr.FieldValue(1)
    Debug.Print "============="
  Next attr
End Sub


Attaching Data to Mechanical Structure Sample Code Detailed Explanation
Attaching Data to Mechanical Structure - Detailed Explanation

These simple examples demonstrate use of attributes to store non-graphical data. The first routine shows the addition of an attribute and attribute value to a component definition, while the second routine shows how that same data can be extracted.

Note: Before running this code, check that the required libraries are referenced in your project. In the VBA editor, go to Tools > References, and if the following type libraries are not checked, check them.

  • Autodesk AutoCAD Mechanical 1.0 Type Library
  • Autodesk GeAuto 2.0 Type Library

Writing Attributes (Code Sample 1)

Open an existing drawing containing one or more components. Add the following code to the ThisDrawing code module in the AutoCAD Mechanical VBA editor. This code omits error checking for the sake of clarity and brevity. Always check that return values are of the expected type.

The first thing to do is set up references to the AutoCAD Mechanical automation object. This provides access to the API, starting with the Mcad2DStructureMgr and Utility objects.

Copy Code
Private Sub AddAttrib()
  Dim gApp As AcadmApplication
  Dim gMgr As Mcad2DStructureMgr
  Dim gUtil As McadUtility
  Set gApp = ThisDrawing.Application.GetInterfaceObject("AcadmAuto.AcadmApplication")
  Set gMgr = gApp.ActiveDocument.StructureMgr2D
  Set gUtil = gApp.ActiveDocument.Utility

Once we have the Mcad2DStructureMgr object, we can get the McadComponentDefinitions collection. For the purposes of this sample, we are not concerned about which component definition to use, so we'll use the first one in the collection.

Copy Code
  Dim gCompDefs As McadComponentDefinitions
  Dim compDef As McadComponentDefinition
  gMgr.GetComponentDefinitions gCompDefs, False
  Set compDef = gCompDefs.Item(1)

Now let's set up the name, data type and value for the new attribute. Here we'll use type mcString, one of the possible values of the McadFieldType enumerator.

Copy Code
  Dim newAttrName As String
  Dim newAttrValue As String
  Dim attrType As McadFieldType
  newAttrName = "test_attrib"
  newAttrValue = "Pete"
  attrType = mcString

Now we're ready to declare and create a new McadAttribute using the CreateSystemAttribute method of the Utility object. We can use a system attribute because we are not creating a new attribute class, otherwise we would use the CreateAttribute method.

Copy Code
  Dim newAttr As McadAttribute
  Set newAttr = gUtil.CreateSystemAttribute(newAttrName, attrType)

The new attribute object exists but does not yet have a value, so assign the value using its FieldValue method.

Copy Code
  newAttr.FieldValue(1) = newAttrValue

At this point, the attribute exists in isolation. It is not yet attached to any AutoCAD Mechanical structure. We are going to attach it to a component definition, so use the AddAttribute method of the ComponentDefinition object obtained earlier. Also, debug-print pertinent information to the immediate window of the VBA IDE (use the View menu to enable this if it is turned off).

Copy Code
  compDef.AddAttribute newAttr
  Debug.Print "Added attribute " + newAttrName + " with value " + newAttrValue
End Sub

When run, the preceding code will add a single attribute to the first component definition found in the currently open drawing, and will print the following:

Copy Code
Added attribute test_attrib with value Pete
Reading Attributes (Code Sample 2)

Adding attributes isn't very useful unless we can retrieve them again. The following code, when run after the preceding sample, will find and print details of the new attribute. Again, the first thing to do is set up references to the AutoCAD Mechanical automation object. This provides access to the API, starting with the Mcad2DStructureMgr and Utility objects.

Copy Code
Private Sub ListAttrib()
  Dim gApp As AcadmApplication
  Dim gMgr As Mcad2DStructureMgr
  Dim gUtil As McadUtility
  Set gApp = ThisDrawing.Application.GetInterfaceObject("AcadmAuto.AcadmApplication")
  Set gMgr = gApp.ActiveDocument.StructureMgr2D
  Set gUtil = gApp.ActiveDocument.Utility

To ensure we use the same component definition previously used to store the attribute, we'll obtain the definition with the same code. As before, once we have the Mcad2DStructureMgr object, we can get the McadComponentDefinitions collection.

Copy Code
  Dim gCompDefs As McadComponentDefinitions
  Dim compDef As McadComponentDefinition
  gMgr.GetComponentDefinitions gCompDefs, False
  Set compDef = gCompDefs.Item(1)

Now we can use the GetAttributes method of the ComponentDefinition object. This will obtain the collection of McadAttribute objects associated with this definition.

Copy Code
  Dim attrs As McadAttributes
  Set attrs = compDef.GetAttributes

Now we can iterate through the collection of McadAttribute objects, debug-printing relevant information. Note that, depending on what drawing you use when running these samples, the component definition may already have a number of attributes attached, especially if your drawing contains BOM and parts list data.

Copy Code
  Dim attr As McadAttribute
  For Each attr In attrs
    Debug.Print attr.FieldValue(0)
    Debug.Print attr.FieldValue(1)
    Debug.Print "============="
  Next attr
End Sub

The results of the preceding sample code should look similar to this:

DESCR
=<PART:NAME>
=============
MATERIAL
CST 11
=============
BOM_UNITS
ea
=============
TEST_ATTRIB
Pete
=============

Note the last attribute, with the name "test_attrib" and value "Pete," is the newly created one.

Also consider

If you intend to work with BOM data and parts lists, but do not intend to create custom attributes, you may find you only need to work with the BOM API and not the attributes API.


Structure Migration
Topics
Structure Migration

To alter a complex standard part (a screw connection or part feature), it is necessary to migrate the structure of that part to a 2D structure. The AutoCAD Mechanical API uses the 2D Structure Manager class to select, analyze, and migrate complex standard parts to 2D structure.


Structure Migration Sample Code
Structure Migration Sample Code
Copy Code
Public Sub MigrateComplexStdPart()
    ' Reference to AcadmApplication
    Dim mcad As AcadmApplication
    Set mcad = ThisDrawing.Application.GetInterfaceObject("AcadmAuto.AcadmApplication")

    ' Get Mcad2DStructureMgr
    Dim structMgr As Mcad2DStructureMgr
    Set structMgr = mcad.ActiveDocument.StructureMgr2D

    ' Create Mcad2dComplexStdPartCompGroupDescriptor
    Dim compGroup As Mcad2dComplexStdPartCompGroupDescriptor
    Set compGroup = structMgr.Create2dComplexStdPartCompGroupDescriptor

    ' Get component views of complex standard parts that need to be migrated to structure
    Dim powViews() As McadPowObjViewGroupDescriptor
    powViews = structMgr.GetComplexStdPartViewsForMigr

    ' Migrate complex standard part to Structure
    Dim view As Variant
    Dim powView As McadPowObjViewGroupDescriptor
    For Each view In powViews
        If TypeOf view Is McadPowObjViewGroupDescriptor Then
            Set powView = view
            compGroup.AddView powView
        End If
    Next

    compGroup.MigrateTo2DStructure

End Sub


Structure Migration Sample Code Detailed Explanation
Structure Migration Sample Code - Detailed Explanation

This example is included in the AutoCAD Mechanical installation when you choose to install samples. The file name is MigrateComplexStdPart.dvb.

To use this example:

  1. Load the ScrewConn_ACADM6.dwg sample drawing file.
  2. Load the VBA Manager by typing VBAMAN.
  3. Load MigrateComplexStdPart.dvb.
  4. Select the ACADProject entry that corresponds to MigrateComplexStdPart.dvb.
  5. Click Macros.
  6. Run the MigrateComplexStdPart macro.

Looking into the code, you can see that this example is relatively simple. The initial section is common to many VBA macros, setting up a reference to the application and the drawing.

Copy Code
Public Sub MigrateComplexStdPart()
    ' Reference to AcadmApplication
    Dim mcad As AcadmApplication
    Set mcad = ThisDrawing.Application.GetInterfaceObject("AcadmAuto.AcadmApplication")

The next section creates a variable (structMgr) of type Mcad2DStructureMgr and sets it equal to the current drawing's 2D structure manager setting.

Copy Code
    ' Get Mcad2DStructureMgr
    Dim structMgr As Mcad2DStructureMgr
    Set structMgr = mcad.ActiveDocument.StructureMgr2D

This section creates a variable (compGroup) of type Mcad2dComplexStdPartCompGroupDescriptor and sets it equal to the current drawing's Create2dComplexStdPartCompGroupDescriptor setting. This enables the script to manipulate complex parts, which include screw connections and part features.

Copy Code
    ' Create Mcad2dComplexStdPartCompGroupDescriptor
    Dim compGroup As Mcad2dComplexStdPartCompGroupDescriptor
    Set compGroup = structMgr.Create2dComplexStdPartCompGroupDescriptor

The script must manipulate the views of complex objects, so it sets a variable (powViews) of type McadPowObjViewGroupDescriptor. This variable points to the array of Power Object view group descriptors in this drawing.

Copy Code
    ' Get component views of complex standard parts that need to be migrated to structure
    Dim powViews() As McadPowObjViewGroupDescriptor
    powViews = structMgr.GetComplexStdPartViewsForMigr

The next section sets up the variables used to migrate the complex standard part to 2D structure. First, it sets up a variable (view) as a variant to hold each view in the complex standard part as it is being processed. The variable powView (not the array powViews) holds a single view group descriptor.

Copy Code
    ' Migrate complex standard part to Structure
    Dim view As Variant
    Dim powView As McadPowObjViewGroupDescriptor

The For Each loop traverses the powViews array, assigning each view group descriptor to the variable view. It then checks the type of view to make sure it is a Power Object view group descriptor. If not, the script ignores that value for view and moves to the next entry in the powViews array.

If view is a Power Object view group descriptor, the script copies its value to powView and then adds it to the array compGroup.

Copy Code
    For Each view In powViews
        If TypeOf view Is McadPowObjViewGroupDescriptor Then
            Set powView = view
            compGroup.AddView powView
        End If
    Next

Finally, the script uses MigrateTo2DStructure on the array compGroup to complete the process.

Copy Code
    compGroup.MigrateTo2DStructure
End Sub


Bill of Materials (BOM)
Topics
Introduction to Bill of Materials (BOM)

One of the features of AutoCAD Mechanical is its ability to tabulate and maintain a parts list, based on a bill of materials (BOM) database generated directly from the attributes on parts in the drawing. It will create a table that includes parts, references, descriptions, materials, standards, and item count. "BOM" typically refers to the main BOM database, but it is also possible to create BOMs for subassemblies.

Structure of the BOM API

The McadSymbolBBMgr object, which is the root object for the Symbol, BOM, and Balloon APIs, provides access to the BOM manager object (McadBOMMgr) through its BOMMgr property. The McadBOMMgr object provides a suite of APIs that facilitate the manipulation of the BOM database.

The McadSymbolBBMgr object also provides access to the McadStandardMgr object through its StandardMgr property. This gives access to standards-based BOM and parts list definitions.


BOM Sample Code 1
Note: Before running this code, check that the required libraries are referenced in your project. In the VBA editor, go to Tools > References, and if the following type libraries are not checked, check them.

  • Autodesk AutoCAD Mechanical 2.0 Type Library
  • Autodesk SymBBAuto 4.0 Type Library

Working with the BOM - Sample 1

This simple example creates a BOM using a defined standard. It then iterates through the BOM, changing material type to Diamond where applicable. It then adds a parts list table to the drawing.

Open an existing drawing containing parts. In this example we'll use the TUT_PTS_LIST.dwg file found in the â€¦/Autodesk/Acadm 2007/Acadm/Tutorial directory. Add the following code to the ThisDrawing code module in the AutoCAD Mechanical VBA editor. This code omits error checking for the sake of clarity and brevity. Always check that return values are of the expected type.

Copy Code
Sub CreatePList()

    Dim symbb As McadSymbolBBMgr
    Dim bommgr As McadBOMMgr
    Dim stdmgr As McadStandardMgr
    Dim util As AcadUtility

    Set symbb = ThisDrawing.Application.GetInterfaceObject("SymBBAuto.McadSymbolBBMgr")
    Set bommgr = symbb.bommgr
    Set stdmgr = symbb.StandardMgr
    Set util = ThisDrawing.Utility

    Dim standard As McadStandard
    Dim BOMstd As McadBOMStandard
    Dim plistStd As McadPartListStandard

    Set standard = stdmgr.GetStandard("ISO")
    Set BOMstd = standard.BOMStandard
    Set plistStd = BOMstd.PartListStandard

    Dim target As AcadBlock
    Dim BOM As McadBOM
    Dim name As String

    Set target = ThisDrawing.ModelSpace
    If bommgr.BOMTableExists(target) Then
        Set BOM = bommgr.GetBOMTable(target, name)
    Else
        Set BOM = bommgr.AddBOMTable("test", target)
    End If

    Dim matData(0 To 0, 0 To 1) As String
    matData(0, 0) = "MATERIAL"
    matData(0, 1) = "Diamond"

    Dim item As McadBOMItem
    Dim data As Variant
    For Each item In BOM.Items
      data = item.data
      For i = LBound(data) To UBound(data)
        If data(i, 0) = "MATERIAL" Then item.data = matData
      Next
    Next

    Dim plist As McadPartList
    Set plist = ThisDrawing.ModelSpace.AddCustomObject("AcmPartList")
    plist.BOM = BOM

    Dim pt(2) As Double
    pt(0) = 0#
    pt(1) = 0#
    plist.Origin = pt

    ThisDrawing.Application.Update
End Sub
Also consider

Internally, AutoCAD Mechanical uses attributes in the 2D Structure environment to store BOM data. An API is available to facilitate manipulation of attributes, however in most cases the BOM API should be used when working with BOM and parts list data.


BOM Sample Code 1 Detailed Explanation
Note: Before running this code, check that the required libraries are referenced in your project. In the VBA editor, go to Tools > References, and if the following type libraries are not checked, check them.

  • Autodesk AutoCAD Mechanical 2.0 Type Library
  • Autodesk SymBBAuto 4.0 Type Library

BOM Sample Code 1 Detailed Explanation

First, the code sets up the root objects such as the McadSymbolBBMgr, McadBOMMgr, McadStandardMgr, and AcadUtility objects.

Copy Code
Sub CreatePList()

    Dim symbb As McadSymbolBBMgr
    Dim bommgr As McadBOMMgr
    Dim stdmgr As McadStandardMgr
    Dim util As AcadUtility

    Set symbb = ThisDrawing.Application.GetInterfaceObject("SymBBAuto.McadSymbolBBMgr")
    Set bommgr = symbb.bommgr
    Set stdmgr = symbb.StandardMgr
    Set util = ThisDrawing.Utility

We'll base our new BOM on a standard, so get the AutoCAD Mechanical standards object McadStandard, from which we can obtain the BOMStandard object conforming to the ISO standard. Other standards supported include ANSI, BSI, CSN, DIN, GB and JIS.

Copy Code
    Dim standard As McadStandard
    Dim BOMstd As McadBOMStandard
    Dim plistStd As McadPartListStandard

    Set standard = stdmgr.GetStandard("ISO")
    Set BOMstd = standard.BOMStandard
    Set plistStd = BOMstd.PartListStandard

Next we'll create a new BOM database, or use an existing one if found. We must check in AutoCAD's modelspace environment, which for the purposes of programming is considered a block, to see if a BOM exists. If one is found, get a reference to it. Otherwise, create one named "test."

Copy Code
    Dim target As AcadBlock
    Dim BOM As McadBOM
    Dim name As String

    Set target = ThisDrawing.ModelSpace
    If bommgr.BOMTableExists(target) Then
        Set BOM = bommgr.GetBOMTable(target, name)
    Else
        Set BOM = bommgr.AddBOMTable("test", target)
    End If

We're almost ready to iterate through the BOM data to change material values, but first we must prepare the new value. This is a simple two dimensional array, with the first item of the second array corresponding to the table column name, with the second item containing the new value. Preparing this array now makes it much easier to substitute the value because is conforms to the data type returned by the data property of each BOM item.

Copy Code
    Dim matData(0 To 0, 0 To 1) As String
    matData(0, 0) = "MATERIAL"
    matData(0, 1) = "Diamond"

Now we can iterate through the data of each item in the BOM, looking for a column type MATERIAL. If found, substitute the new array, complete with new material value; in this case, a very futuristic Diamond.

Copy Code
    Dim item As McadBOMItem
    Dim data As Variant
    For Each item In BOM.Items
      data = item.data
      For i = LBound(data) To UBound(data)
        If data(i, 0) = "MATERIAL" Then item.data = matData
      Next
    Next

Once this is complete, we can add the table to the drawing as a new parts list table. AutoCAD Mechanical parts lists are custom AutoCAD objects of type AcmPartList, so we'll use the AutoCAD AddCustomObject API to insert one into model space. At this point, the parts list is not populated, so we must assign out BOM database to the parts list.

Copy Code
    Dim plist As McadPartList
    Set plist = ThisDrawing.ModelSpace.AddCustomObject("AcmPartList")
    plist.BOM = BOM

Now we can move our table to the appropriate location relative to our drawing border. In this case, we set the location to an arbitrary 0,0.

Copy Code
    Dim pt(2) As Double
    pt(0) = 0#
    pt(1) = 0#
    plist.Origin = pt

All that's left is to update the drawing to reflect the changes.

Copy Code
    ThisDrawing.Application.Update
End Sub

The preceding code results in something like the table depicted in figure 1, with any material specifications changed to the new value.

Figure 1


BOM Sample Code 2
Note: Before running this code, check that the required libraries are referenced in your project. In the VBA editor, go to Tools > References, and if the following type libraries are not checked, check them.

  • Autodesk AutoCAD Mechanical 2.0 Type Library
  • Autodesk SymBBAuto 4.0 Type Library

Iterating through BOM data - Sample 2

This example shows how to iterate through the BOM data array, printing out the table to the immediate window in the VBA IDE (use the View menu to enable this if it is turned off).

Copy Code
Sub DumpBOM()

    Dim symbb As McadSymbolBBMgr
    Dim bommgr As McadBOMMgr
    Set symbb = ThisDrawing.Application.GetInterfaceObject("SymBBAuto.McadSymbolBBMgr")
    Set bommgr = symbb.bommgr

    Dim target As AcadBlock
    Set target = ThisDrawing.ModelSpace

    If Not bommgr.BOMTableExists(target) Then
        Exit Sub
    End If

    Dim BOM As McadBOM
    Dim name As String
    Set BOM = bommgr.GetBOMTable(target, name)

    Debug.Print "BOM database " + name + " data:" + vbCrLf

    Dim data As Variant
    Dim i As Long

    data = BOM.data
    For i = LBound(data) To UBound(data)
        Debug.Print vbTab + data(i, LBound(data, 2)) + vbTab + vbTab + vbTab + data(i, UBound(data, 2)) + vbCrLf
    Next

    Dim item As McadBOMItem
    For Each item In BOM.Items

        Debug.Print "BOM item number " + item.ItemNumber + vbCrLf
        If item.IsExpandable Then
            Debug.Print vbTab + "Item is expandable and is "
            If Not item.Expanded Then Debug.Print "not "
            Debug.Print "expanded." + vbCrLf
        Else
            Debug.Print vbTab + "Item is not expandable." + vbCrLf
        End If
        Debug.Print vbTab + "Item quantity is " + Str(item.Quantity) + "." + vbCrLf

        Debug.Print vbTab + "Item data:" + vbCrLf

        data = item.data
        For i = LBound(data) To UBound(data)

            Debug.Print vbTab + vbTab + data(i, LBound(data, 2)) + vbTab + vbTab + vbTab + data(i, UBound(data, 2)) + vbCrLf
        Next
    Next
End Sub


BOM Sample Code 2 Detailed Explanation
Note: Before running this code, check that the required libraries are referenced in your project. In the VBA editor, go to Tools > References, and if the following type libraries are not checked, check them.

  • Autodesk AutoCAD Mechanical 2.0 Type Library
  • Autodesk SymBBAuto 4.0 Type Library

Iterating through BOM data - Sample 2

This example shows how to iterate through the BOM data array, printing out the table to the immediate window in the VBA IDE (use the View menu to enable this if it is turned off).

First we must set up the root McadSymbolBBMgr and McadBOMMgr objects.

Copy Code
Sub DumpBOM()

    Dim symbb As McadSymbolBBMgr
    Dim bommgr As McadBOMMgr
    Set symbb = ThisDrawing.Application.GetInterfaceObject("SymBBAuto.McadSymbolBBMgr")
    Set bommgr = symbb.bommgr

As with Sample Code 1, we must check in AutoCAD's modelspace environment to see if a BOM exists. If one is found, get a reference to it and print its name. Otherwise, exit the routine.

Copy Code
    Dim target As AcadBlock
    Set target = ThisDrawing.ModelSpace

    If Not bommgr.BOMTableExists(target) Then
        Exit Sub
    End If

    Dim BOM As McadBOM
    Dim name As String
    Set BOM = bommgr.GetBOMTable(target, name)

    Debug.Print "BOM database " + name + " data:" + vbCrLf

Get the BOM data. Before we iterate through each BOM item, print out the general BOM data.

Copy Code
    Dim data As Variant
    Dim i As Long

    data = BOM.data
    For i = LBound(data) To UBound(data)
        Debug.Print vbTab + data(i, LBound(data, 2)) + vbTab + vbTab + vbTab + data(i, UBound(data, 2)) + vbCrLf
    Next

Now iterate through each item in the BOM, printing its item number, quantity, and whether the item is expandable (whether BOM data may obtained from subassemblies).

Copy Code
    Dim item As McadBOMItem
    For Each item In BOM.Items

        Debug.Print "BOM item number " + item.ItemNumber + vbCrLf
        If item.IsExpandable Then
            Debug.Print vbTab + "Item is expandable and is "
            If Not item.Expanded Then Debug.Print "not "
            Debug.Print "expanded." + vbCrLf
        Else
            Debug.Print vbTab + "Item is not expandable." + vbCrLf
        End If
        Debug.Print vbTab + "Item quantity is " + Str(item.Quantity) + "." + vbCrLf

        Debug.Print vbTab + "Item data:" + vbCrLf

Get the array of data associated with each BOM item. Loop through the data, printing all the contents.

Copy Code
        data = item.data
        For i = LBound(data) To UBound(data)

            Debug.Print vbTab + vbTab + data(i, LBound(data, 2)) + vbTab + vbTab + vbTab + data(i, UBound(data, 2)) + vbCrLf
        Next
    Next
End Sub

For the last BOM item defined in Sample1, this code prints out something similar to the following:

BOM item number 6
  Item is not expandable.
  Item quantity is  3.
  Item data:
    BOM_UNITS     ea
    MATERIAL      Diamond
    GUPI      G3V<></AMSTD/ISO/FSTN/NUT/POLY/IS0802><AmValTable.RID="G_20">
    DESCR     Hex Nut
    NAME      Hex Nut - ISO 4034 - M6
    STANDARD      ISO 4034 - M6


Data Provider
Topics
Introduction to Data Provider

AutoCAD Mechanical allows the user to add attributes to standard parts such that the attributes can be evaluated to numeric or string values, for example to use in notes, hole charts, parts lists or a bill of materials. Many objects can contain formulas, also termed expressions, which can be evaluated to numeric or textual content. Formulas can automate the population of lists, notes and charts, performing current-context calculations similar to those in a spreadsheet application.

Formulas always begin with the equal sign (=), and formulas that evaluate to a text value are always enclosed in angle brackets (< >). The following are examples of formulas.

These examples return a numeric result.

=(10+20)*40
=QTY*PRICE
=PI()*RADIUS

These return a textual result:

=<(10+20)*40>
=<QTY> at a cost of <PRICE> each
=Perimeter of part <ITEM> is <PI()*RADIUS>
=This is screw number <ITEM>
=<NAME>

To learn more about formulas, refer to the About Formulas conceptual topic in the AutoCAD Mechanical online user help.

Formulas in the AutoCAD Mechanical API - Data Providers

A Data Provider refers to a facility provided by the API to enable programmatic means of adding attributes containing formulas. The term Data Provider can be thought of as a label for a set of attributes.

The main API object is the McadFormulaEvaluator available from the AcadmApplication object. This provides a set of method and properties for manipulating Data Providers and their attributes, and for evaluating formulas.

Summary

The AcadmApplication object provides access to the McadFormulaEvaluator object, which provides a suite of properties and methods for adding data providers, and for manipulating attributes and evaluating expressions. Any number of data providers can be added to a standard part, with the data provider acting as a label. Different applications can work with identically named attributes by using their own named data provider.


Data Provider Sample Code
Sample Code - Using the API to Add, Edit and Evaluate Expressions

This sample code employs two control loops which prompt the user to choose an action. The primary purpose of the outer control loop is to add a data provider. The inner control loop provides a number of options for adding, resetting, and querying formulas in attributes.

Copy Code
Sub FormulaEvaluator()
Dim mapp As AcadmApplication
Set mapp = ThisDrawing.Application.GetInterfaceObject("AcadmAuto.AcadmApplication")
Dim evaluator As McadFormulaEvaluator

Dim entity As Object
Dim pickPnt As Variant
ThisDrawing.Utility.GetEntity entity, pickPnt, vbNewLine & "Select entity (Standard part only): "
If Err <> 0 Then
MsgBox "Selection cancelled.", vbInformation
End If
On Error GoTo EndSub
Set evaluator = mapp.GetFormulaEvaluator(entity)
If Err <> 0 Then
MsgBox "Error GetFormulaEvaluator.", vbInformation
End If
On Error GoTo EndSub

Dim continue1 As Boolean
continue1 = True
While continue1
Dim keywordList As String
keywordList = "Add allData aTtribute Evaluate eXit"
ThisDrawing.Utility.InitializeUserInput 1, keywordList
Dim returnString As String
returnString = ThisDrawing.Utility.GetKeyword(vbNewLine & "Choose operation [Add/allData/aTtribute/Evaluate/eXit]: ")
If Err <> 0 Then
MsgBox "Invalid input", vbInformation
End If
On Error GoTo EndSub

If StrComp(returnString, "eXit") = 0 Then
continue1 = False

ElseIf StrComp(returnString, "Add") = 0 Then

ThisDrawing.Utility.GetEntity entity, pickPnt, vbNewLine & "Select entity for Additional data provider (Standard part only): "
If Err <> 0 Then
MsgBox "Selection cancelled.", vbInformation
End If
On Error GoTo EndSub

Dim stat As Boolean
stat = evaluator.SetDataProvider(entity)
If Err <> 0 Then
MsgBox "Error SetDataProvider", vbInformation
End If
On Error GoTo EndSub

If stat = False Then
MsgBox "The Data Provider is not properly added"
End If

ElseIf StrComp(returnString, "allData") = 0 Then

Dim ArrayStr
ArrayStr = evaluator.GetAllAttribs

If Err <> 0 Then
MsgBox "Error GetAllAttribs", vbInformation
End If
On Error GoTo EndSub

Dim Str As Variant
Dim idx As Integer
idx = 0
For Each Str In ArrayStr
idx = idx + 1
ThisDrawing.Utility.prompt vbNewLine & "Expression" & idx & " :" & Str
Next

ElseIf StrComp(returnString, "aTtribute") = 0 Then

Dim attName As String

attName = ThisDrawing.Utility.GetString(False, vbNewLine & "Enter attribute name: (a space or terminates input): ")
If Err <> 0 Then
MsgBox "invalid input.", vbInformation
End If
On Error GoTo EndSub

stat = evaluator.Exist(attName)

If Err <> 0 Then
MsgBox "Error Exist", vbInformation
End If
On Error GoTo EndSub

If stat = False Then
Dim keys As String
keys = "Yes No"
ThisDrawing.Utility.InitializeUserInput 1, keys
returnString = ThisDrawing.Utility.GetKeyword(vbNewLine & "Attribute doesn't exist. Would you like to create it? [Yes/No]:")

If StrComp(returnString, "Yes") = 0 Then
Dim attData As String
attData = ThisDrawing.Utility.GetString(True, vbNewLine & "Enter attribute expression:")
If Err <> 0 Then
MsgBox "invalid input.", vbInformation
End If
On Error Resume Next
Call evaluator.SetData(attName, attData)
If Err <> 0 Then
MsgBox "Error SetData", vbInformation
End If
On Error GoTo EndSub
stat = True
End If
End If

If stat Then
Dim continue2 As Boolean
continue2 = True
While continue2
Dim prompt As String
prompt = vbNewLine & "Edit mode for attribute '" & attName & "'"
ThisDrawing.Utility.prompt (prompt)
keys = "isEditable Get reSet Info All eXit"
ThisDrawing.Utility.InitializeUserInput 1, keys
returnString = ThisDrawing.Utility.GetKeyword(vbNewLine & "Choose operation [isEditable/Get/reSet/Info/All/eXit]:")
If Err <> 0 Then
MsgBox "Invalid input.", vbInformation
End If
On Error Resume Next

If StrComp(returnString, "isEditable") = 0 Then
stat = evaluator.IsEditable(attName)
On Error GoTo EndSub
If stat Then
ThisDrawing.Utility.prompt vbNewLine & "Editable - Yes"
Else
ThisDrawing.Utility.prompt vbNewLine & "Editable - No"
End If

ElseIf StrComp(returnString, "Get") = 0 Then
attData = evaluator.GetData(attName)
ThisDrawing.Utility.prompt vbNewLine & "Attribute data:" & attData

ElseIf StrComp(returnString, "reSet") = 0 Then
attData = ThisDrawing.Utility.GetString(True, vbNewLine & "Enter attribute expression:")
If Err <> 0 Then
MsgBox "invalid input.", vbInformation
End If
On Error Resume Next
Call evaluator.SetData(attName, attData)
If Err <> 0 Then
MsgBox "Error SetData", vbInformation
End If
On Error GoTo EndSub

ElseIf StrComp(returnString, "Info") = 0 Then
Dim attValue As String
Dim isE As Boolean
stat = evaluator.GetAllAttribsData(attName, attData, attValue, isE)
If stat Then
ThisDrawing.Utility.prompt vbNewLine & "Information about attribute:" & attName & "':"
ThisDrawing.Utility.prompt vbNewLine & "Evaluate expression: " & attValue
ThisDrawing.Utility.prompt vbNewLine & "Expression: " & attData
If isE Then
ThisDrawing.Utility.prompt vbNewLine & "Is editable: Yes "
Else
ThisDrawing.Utility.prompt vbNewLine & "Is editable: No "
End If
End If

ElseIf StrComp(returnString, "All") = 0 Then
ArrayStr = evaluator.GetAllAttribValues(attName)
If Err <> 0 Then
MsgBox "Error GetAllAttribs", vbInformation
End If
On Error GoTo EndSub
idx = 0
For Each Str In ArrayStr
idx = idx + 1
ThisDrawing.Utility.prompt vbNewLine & "Expression" & idx & " :" & Str
Next

ElseIf StrComp(returnString, "eXit") = 0 Then
continue2 = False
End If
Wend
End If

ElseIf StrComp(returnString, "Evaluate") = 0 Then
Dim Formula As String
ThisDrawing.Utility.prompt "Enter expression for evaluation. Expression must start with '='. "
Formula = ThisDrawing.Utility.GetString(True, vbNewLine & "Enter expression: (a space or terminates input): ")
If Err <> 0 Then
MsgBox "Selection cancelled.", vbInformation
End If
On Error GoTo EndSub
Dim EvalStr As String
EvalStr = evaluator.Evaluate(Formula)
If Err <> 0 Then
MsgBox "Error Evaluate", vbInformation
End If
On Error GoTo EndSub
ThisDrawing.Utility.prompt vbNewLine & EvalStr
End If
Wend
EndSub:
End Sub


Data Provider Sample Code Detailed Explanation
Sample Code - Using the API to Add, Edit and Evaluate Expressions

The following example code has been dividing into meaningful chunks to aid understanding. The code employs two control loops which prompt the user to choose an action. The primary purpose of the outer control loop is to add a data provider, while the inner control loop provides a number of options for adding, resetting, and querying formulas in attributes. Figure 1 shows a high-level overview of the structure of the sample code, with the inner and outer control loops represented in yellow and green respectively.

Figure 1 - Structure of sample

This sample code may be cut and pasted into the AutoCAD Mechanical VBA editor. Make sure all sections are present. Immediately before each section is text describing that section's purpose and operation.

Working through the sample code

The first thing to do in our code is initialize the AutoCAD Mechanical API environment, and then declare an object of type McadFormulaEvaluator - but we're not yet ready to initialize this object.

Copy Code
Sub FormulaEvaluator()
Dim mapp As AcadmApplication
Set mapp = ThisDrawing.Application.GetInterfaceObject("AcadmAuto.AcadmApplication")
Dim evaluator As McadFormulaEvaluator

Now we need to pick an entity (a standard part) to which we'll add attributes, or edit existing attributes. When a valid entity is selected, we can use the GetFormulaEvaluator property of the AcadmApplication object to obtain the McadFormularEvaluator.

Copy Code
Dim entity As Object
Dim pickPnt As Variant
ThisDrawing.Utility.GetEntity entity, pickPnt, vbNewLine & "Select entity (Standard part only): "
If Err <> 0 Then
MsgBox "Selection cancelled.", vbInformation
End If
On Error GoTo EndSub
Set evaluator = mapp.GetFormulaEvaluator(entity)
If Err <> 0 Then
MsgBox "Error GetFormulaEvaluator.", vbInformation
End If
On Error GoTo EndSub

The sample contains two control loops. Now we're ready to enter the main outer prompt loop of the sample. At this level, there are five options.

  • Add - Add a Data Provider
  • allData - View all attribute data from all Data Providers
  • aTtribute - Enter attribute edit mode
  • Evaluate - Enter and evaluate a formula.
  • eXit - Exit the sample
Copy Code
Dim continue1 As Boolean
continue1 = True
While continue1
Dim keywordList As String
keywordList = "Add allData aTtribute Evaluate eXit"
ThisDrawing.Utility.InitializeUserInput 1, keywordList
Dim returnString As String
returnString = ThisDrawing.Utility.GetKeyword(vbNewLine & "Choose operation [Add/allData/aTtribute/Evaluate/eXit]: ")
If Err <> 0 Then
MsgBox "Invalid input", vbInformation
End If
On Error GoTo EndSub
Main control loop - Exit case

If the user presses X, the control variable for this loop (continue1) is set to false, so the application will exit.

Copy Code
If StrComp(returnString, "eXit") = 0 Then
continue1 = False
Main control loop - Add Data Provider case

This section will add a new data provider, but first we need to pick a standard part to which the attributes will be applied. If this fails, and error message is issued and the application will exit.

Copy Code
ElseIf StrComp(returnString, "Add") = 0 Then

ThisDrawing.Utility.GetEntity entity, pickPnt, vbNewLine & "Select entity for Additional data provider (Standard part only): "
If Err <> 0 Then
MsgBox "Selection cancelled.", vbInformation
End If
On Error GoTo EndSub

Dim stat As Boolean
stat = evaluator.SetDataProvider(entity)
If Err <> 0 Then
MsgBox "Error SetDataProvider", vbInformation
End If
On Error GoTo EndSub

If stat = False Then
MsgBox "The Data Provider is not properly added"
End If
Main control loop - View all attribute data from all Data Providers

Option D, for view all Data, will invoke the GetAllAttribs property of the McadFormulaEvaluator, returning an array of strings. We next iterate through the array, printing out the value of each attribute.

Copy Code
ElseIf StrComp(returnString, "allData") = 0 Then

Dim ArrayStr
ArrayStr = evaluator.GetAllAttribs

If Err <> 0 Then
MsgBox "Error GetAllAttribs", vbInformation
End If
On Error GoTo EndSub

Dim Str As Variant
Dim idx As Integer
idx = 0
For Each Str In ArrayStr
idx = idx + 1
ThisDrawing.Utility.prompt vbNewLine & "Expression" & idx & " :" & Str
Next
Main control loop - Get name of attribute for Attribute Edit mode

Here we effectively enter attribute edit mode, but before we prompt the user for an action to take, we must first determine what attribute to work with. This code prompts the user for an attribute name, and uses the Exist method of the McadFormulaEvaluator object to determine of the attribute exists.

Copy Code
ElseIf StrComp(returnString, "aTtribute") = 0 Then

Dim attName As String

attName = ThisDrawing.Utility.GetString(False, vbNewLine & "Enter attribute name: (a space or terminates input): ")
If Err <> 0 Then
MsgBox "invalid input.", vbInformation
End If
On Error GoTo EndSub

stat = evaluator.Exist(attName)

If Err <> 0 Then
MsgBox "Error Exist", vbInformation
End If
On Error GoTo EndSub

If the attribute does not exist, the user is given the option of creating a new attribute with this name. At this time, the attribute data will be prompted for and added too.

Copy Code
If stat = False Then
Dim keys As String
keys = "Yes No"
ThisDrawing.Utility.InitializeUserInput 1, keys
returnString = ThisDrawing.Utility.GetKeyword(vbNewLine & "Attribute doesn't exist. Would you like to create it? [Yes/No]:")

If StrComp(returnString, "Yes") = 0 Then
Dim attData As String
attData = ThisDrawing.Utility.GetString(True, vbNewLine & "Enter attribute expression:")
If Err <> 0 Then
MsgBox "invalid input.", vbInformation
End If
On Error Resume Next
Call evaluator.SetData(attName, attData)
If Err <> 0 Then
MsgBox "Error SetData", vbInformation
End If
On Error GoTo EndSub
stat = True
End If
End If
Inner control loop

Now that we have an attribute we can enter the second of the two control loops. This is the inner prompt loop, for editing attributes. At this level, there are six options.

  • isEditable - query whether attribute is editable.
  • Get - Query attribute expression.
  • reSet - Reset attribute with a new expression.
  • Info - Report attribute information.
  • All - Show all attribute expressions from all Data Providers.
  • eXit - Exit attribute edit mode.
Copy Code
If stat Then
Dim continue2 As Boolean
continue2 = True
While continue2
Dim prompt As String
prompt = vbNewLine & "Edit mode for attribute '" & attName & "'"
ThisDrawing.Utility.prompt (prompt)
keys = "isEditable Get reSet Info All eXit"
ThisDrawing.Utility.InitializeUserInput 1, keys
returnString = ThisDrawing.Utility.GetKeyword(vbNewLine & "Choose operation [isEditable/Get/reSet/Info/All/eXit]:")
If Err <> 0 Then
MsgBox "Invalid input.", vbInformation
End If
On Error Resume Next
Inner loop - query whether attribute is editable

This option simple calls the isEditable property of the attribute. Some attributes cannot be edited - for example, those maintained by AutoCAD Mechanical itself.

Copy Code
If StrComp(returnString, "isEditable") = 0 Then
stat = evaluator.IsEditable(attName)
On Error GoTo EndSub
If stat Then
ThisDrawing.Utility.prompt vbNewLine & "Editable - Yes"
Else
ThisDrawing.Utility.prompt vbNewLine & "Editable - No"
End If
Inner loop - Query attribute expression

This option will print the expression contained in the attribute. Note that the expression will not be evaluated.

Copy Code
ElseIf StrComp(returnString, "Get") = 0 Then
attData = evaluator.GetData(attName)
ThisDrawing.Utility.prompt vbNewLine & "Attribute data:" & attData
Inner loop - Reset attribute with a new expression

Here we use the SetData method of the McadFormulaEvaluator to reset the expression contained in the attribute. If this fails, exit the application.

Copy Code
ElseIf StrComp(returnString, "reSet") = 0 Then
attData = ThisDrawing.Utility.GetString(True, vbNewLine & "Enter attribute expression:")
If Err <> 0 Then
MsgBox "invalid input.", vbInformation
End If
On Error Resume Next
Call evaluator.SetData(attName, attData)
If Err <> 0 Then
MsgBox "Error SetData", vbInformation
End If
On Error GoTo EndSub
Inner loop - Report attribute information

This option uses the GetAllAttribsData method of the McadFormulaEvaluator object, which performs the same operations as several related methods combined. The code will print the attribute name, evaluated expression, expression, and editable status.

Copy Code
ElseIf StrComp(returnString, "Info") = 0 Then
Dim attValue As String
Dim isE As Boolean
stat = evaluator.GetAllAttribsData(attName, attData, attValue, isE)
If stat Then
ThisDrawing.Utility.prompt vbNewLine & "Information about attribute:" & attName & "':"
ThisDrawing.Utility.prompt vbNewLine & "Evaluate expression: " & attValue
ThisDrawing.Utility.prompt vbNewLine & "Expression: " & attData
If isE Then
ThisDrawing.Utility.prompt vbNewLine & "Is editable: Yes "
Else
ThisDrawing.Utility.prompt vbNewLine & "Is editable: No "
End If
End If
Inner loop - Show all attribute expressions from all Data Providers

The GetAllAttribValues method will get the value of all attributes with the specified name, regardless of the data provider. The values are returned in a string array, which we then iterate through, printing each expression.

Copy Code
ElseIf StrComp(returnString, "All") = 0 Then
ArrayStr = evaluator.GetAllAttribValues(attName)
If Err <> 0 Then
MsgBox "Error GetAllAttribs", vbInformation
End If
On Error GoTo EndSub
idx = 0
For Each Str In ArrayStr
idx = idx + 1
ThisDrawing.Utility.prompt vbNewLine & "Expression" & idx & " :" & Str
Next
Inner loop - Exit attribute edit mode

If the user presses X, the control variable for the inner loop (continue2) is set to false, so control will be passed back to the outer control loop. Attribute Edit Mode will no longer be in effect, but the main data provider options will again be available.

Copy Code
ElseIf StrComp(returnString, "eXit") = 0 Then
continue2 = False
End If
Wend
End If
Main control loop - Enter and evaluate a formula

It is possible to use the formula evaluator to evaluate an expression not contained in an attribute. This is useful for an application gathering data, for example, or for testing purposes. The McadFormulaEvaluator object provides the Evaluate method, which returns a string containing the result of the evaluated expression.

Copy Code
ElseIf StrComp(returnString, "Evaluate") = 0 Then
Dim Formula As String
ThisDrawing.Utility.prompt "Enter expression for evaluation. Expression must start with '='. "
Formula = ThisDrawing.Utility.GetString(True, vbNewLine & "Enter expression: (a space or terminates input): ")
If Err <> 0 Then
MsgBox "Selection cancelled.", vbInformation
End If
On Error GoTo EndSub
Dim EvalStr As String
EvalStr = evaluator.Evaluate(Formula)
If Err <> 0 Then
MsgBox "Error Evaluate", vbInformation
End If
On Error GoTo EndSub
ThisDrawing.Utility.prompt vbNewLine & EvalStr
End If
Wend
EndSub:
End Sub
Summary

The AcadmApplication object provides access to the McadFormulaEvaluator object, which provides a suite of properties and methods for adding data providers, and for manipulating attributes and evaluating expressions. Any number of data providers can be added to a standard part, with the data provider acting as a label. Different applications can work with identically named attributes by using their own named data provider.


Hide Situation
Topics
Introduction to Hide Situations

3D CAD systems can typically produce hidden-line views. That is, views where obscured parts of components do not appear or are shown with dashed lines. AutoCAD Mechanical can produce the same type of views in its 2D structure, using the AMSHIDE command. In the absence of Z-coordinate data to establish a hierarchy of visible components, AutoCAD Mechanical allows you to indicate which objects in a given view represent foreground or background objects. It is then able to maintain the correct hidden line appearance in all applicable views by breaking lines, removing lines, or changing line types where necessary. These named hide situations are added to the 2D structure browser, and are intelligent and associative; hidden line views will be recalculated as needed, for example, if an object is moved (unless the hide situation is suppressed or simplified).

Hide Situations through the API

The API provides functionality similar to that of the AMSHIDE command. The API employs the concept of simple and complex hide situations, where complex hide situations are comprised of a number of simple hide situations. Which simple hide situations are used, and their order in a complex hide, allow the required complex representations to be generated for a given view.

Hide situations are represented by two API objects; McadHideSituation and McadComplexHideSituation. The following objects allow the creation of hide situations through the AcadHideSituation or AddComplexHideSituation methods:

  • McadAnnotationViewDefinition
  • McadComponentViewDefinition
  • McadFolderDefinition
Summary

The AutoCAD Mechanical API proves mechanisms for adding simple and complex hide situations to the 2D structure hierarchy. Entities constituting foreground and background objects are used to construct simple hide situations. Complex hides are comprised of a number of simple hides, the order of which determines the appearance of the complex hide. Hide situations are dynamic - changes to the 2D structure will automatically cause the hide situations to be recalculated.


Hide Situation Sample Code 1
Hide Situation Sample Code 1
Copy Code
Public Sub CreateSimpleHide(name As String, newHide As McadHideSituation, rootDef As McadFolderDefinition)
    On Error Resume Next
    Dim app As AcadmApplication
    Dim mgr As Mcad2DStructureMgr
    Set app = ThisDrawing.Application.GetInterfaceObject("AcadmAuto.AcadmApplication")
    Set mgr = app.ActiveDocument.StructureMgr2D

    Dim ssetObj As AcadSelectionSet
    Set ssetObj = ThisDrawing.SelectionSets.Add(name)
    Call ssetObj.Clear
    ThisDrawing.Utility.prompt "Select foreground entity or entities."
    Call ssetObj.SelectOnScreen
    Dim ssFg() As Long
    ReDim ssFg(ssetObj.Count - 1) As Long
    Dim index As Integer
    For index = 0 To ssetObj.Count - 1
    'Use  ObjectID   for 32bit
    '     ObjectID32 for 64bit
      ssFg(index) = ssetObj.Item(index).ObjectID
    Next

    Call ssetObj.Clear
    ThisDrawing.Utility.prompt "Select background entity or entities."
    Call ssetObj.SelectOnScreen
    Dim ssBg() As Long
    ReDim ssBg(ssetObj.Count - 1) As Long
    For index = 0 To ssetObj.Count - 1
    'Use  ObjectID   for 32bit
    '     ObjectID32 for 64bit
      ssBg(index) = ssetObj.Item(index).ObjectID
    Next

    Dim trnObj As McadTransaction
    Set trnObj = mgr.StartTransaction

    Call rootDef.AddHideSituation(name, newHide, ssFg, ssBg)
End Sub


Hide Situation Sample Code 1 Detailed Explanation
Hide Situation Sample Code 1 - Detailed Explanation

To demonstrate the effects of different hide situations, this example uses an AutoCAD Mechanical drawing comprised of four top component views, each a simple circle overlapping the other three. See figure 1.

Figure 1

Here we define a Sub to create simple hide situations. This Sub will be called multiple times to create the simple hides required to construct a complex hide situation. The first step is to get the application object, and from that we can obtain the 2D Structure manager object. We will be adding hide situations to the 2D structure.

Copy Code
Public Sub CreateSimpleHide(name As String, newHide As McadHideSituation, rootDef As McadFolderDefinition)
    On Error Resume Next
    Dim app As AcadmApplication
    Dim mgr As Mcad2DStructureMgr
    Set app = ThisDrawing.Application.GetInterfaceObject("AcadmAuto.AcadmApplication")
    Set mgr = app.ActiveDocument.StructureMgr2D

The next step is to prompt the user to select the foreground entities. We will later need the ObjectIDs (ObjectID32 on the 64bit platform) in the form of an array, so loop through the selection set, adding IDs to an array of Longs. In this example, select just one of the circles.

Copy Code
    Dim ssetObj As AcadSelectionSet
    Set ssetObj = ThisDrawing.SelectionSets.Add(name)
    Call ssetObj.Clear
    ThisDrawing.Utility.prompt "Select foreground entity or entities."
    Call ssetObj.SelectOnScreen
    Dim ssFg() As Long
    ReDim ssFg(ssetObj.Count - 1) As Long
    Dim index As Integer
    For index = 0 To ssetObj.Count - 1
    'Use  ObjectID   for 32bit
    '     ObjectID32 for 64bit
      ssFg(index) = ssetObj.Item(index).ObjectID
    Next

The next prompt is to select the background entities. Note that when using the AMSHIDE command, background entities are implied from the context and typically do not require selection. However, you can use the dialog to select them if necessary, in the same manner as the API. In this example, select the remaining three circles not selected as foreground entities. Again, we use ObjectIDs to build an array of Longs.

Copy Code
    Call ssetObj.Clear
    ThisDrawing.Utility.prompt "Select background entity or entities."
    Call ssetObj.SelectOnScreen
    Dim ssBg() As Long
    ReDim ssBg(ssetObj.Count - 1) As Long
    For index = 0 To ssetObj.Count - 1
    'Use  ObjectID   for 32bit
    '     ObjectID32 for 64bit
      ssBg(index) = ssetObj.Item(index).ObjectID
    Next

Lastly, call the AddHideSituation method to create a simple hide situation. In this case, it will be added to the root McadFolderDefinition. However, before doing this, start a new transaction. While our own transaction is present, dynamic updates of mechanical structure will be suspended, providing better performance.

Hide situations can also be added to McadComponentViewDefinition or McadAnnotationViewDefinition objects. The foreground and background object IDs are passed as arrays of Longs.

Copy Code
    Dim trnObj As McadTransaction
    Set trnObj = mgr.StartTransaction

    Call rootDef.AddHideSituation(name, newHide, ssFg, ssBg)
End Sub

Figure 2 shows what the drawing would look like after one simple hide situation has been created. The topmost circle was picked as the foreground entity, therefore the remaining three background circles are broken and hidden where they pass "behind" the foreground circle.

Figure 2 - simple hide


Hide Situation Sample Code 2
Hide Situation Sample Code 2
Copy Code
Public Sub CreateComplexHide()
Dim app As AcadmApplication
Dim util As McadUtility
Dim mgr As Mcad2DStructureMgr
Set app = ThisDrawing.Application.GetInterfaceObject("AcadmAuto.AcadmApplication")
Set mgr = app.ActiveDocument.StructureMgr2D
Set util = app.ActiveDocument.Utility

Dim rootDef As McadFolderDefinition
Set rootDef = mgr.RootViewDefinition(ThisDrawing.Database)
Dim subHides As McadHideSituations
Set subHides = util.CreateCollection(mcHideSituations)

Dim index As Integer
For index = 0 To 3
Dim tmpHide As McadHideSituation
Dim sname As String
sname = "shide" + CStr(index)
Call CreateSimpleHide(sname, tmpHide, rootDef)
Call subHides.Add(tmpHide)
Next

Dim trnObj As McadTransaction
Set trnObj = mgr.StartTransaction

Dim name As String
name = "ComplexHide"
Dim complexHide As McadComplexHideSituation
Call rootDef.AddComplexHideSituation(name, subHides, complexHide)
End Sub


Hide Situation Sample Code 2 Detailed Explanation
Hide Situation Sample Code 2 - Detailed Explanation

Now to define another Sub. This one builds a complex hide situation by repeatedly calling the CreateSimpleHide Sub previously defined. The new complex hide is named ComplexHide, and is placed in the root folder definition (so the hide situation will appear off the root in the browser window). This complex hide demonstrates the use of simple hides, in a specific order, to create the desired effect as shown in figure 3.

As with the previous code, the first step is to get the application object, and from that we can obtain the 2D Structure manager object. In addition, we'll also get the Utility object from the active document. This will be used later when defining the collection of sub hides (simple hides) to comprise the complex hide.

Copy Code
Public Sub CreateComplexHide()
Dim app As AcadmApplication
Dim util As McadUtility
Dim mgr As Mcad2DStructureMgr
Set app = ThisDrawing.Application.GetInterfaceObject("AcadmAuto.AcadmApplication")
Set mgr = app.ActiveDocument.StructureMgr2D
Set util = app.ActiveDocument.Utility

Next, obtain the root folder definition from the current drawing database. Our complex hide situation will be added at this level. Also, at this point we'll use the Utility object to create a collection object ready to contain our simple hides (a collection of objects of type mcHideSituations).

Copy Code
Dim rootDef As McadFolderDefinition
Set rootDef = mgr.RootViewDefinition(ThisDrawing.Database)
Dim subHides As McadHideSituations
Set subHides = util.CreateCollection(mcHideSituations)

We're ready to call our previously defined Sub, CreateSimpleHide. In this example we'll call it four times. Each pass will prompt for foreground and background entities. To create the desired effect, pick a different foreground entity, then select the remaining three as background entities, on each of the four passes. Four simple hides will be created, named shide0 to shide3. Each will be added to the collection of hide situations.

Copy Code
Dim index As Integer
For index = 0 To 3
Dim tmpHide As McadHideSituation
Dim sname As String
sname = "shide" + CStr(index)
Call CreateSimpleHide(sname, tmpHide, rootDef)
Call subHides.Add(tmpHide)
Next

It was necessary to use the Utility object to create a collection of this type in order to pass the simple hides as an ordered group to the AddComplexHideSituation method of the root folder definition. This we can now do; create a complex hide named ComplexHide. This method will add the new named complex hide to the 2D structure browser, defining an object of type McadComplexHideSituation.

Note the creation of a new transaction object. As before, while our own transaction is present, dynamic updates of mechanical structure will be suspended, providing better performance.

Use the redraw command in AutoCAD - the result should be something like figure 3. Note the ordered application of each of the simple hides to create the complex hide.

Copy Code
Dim trnObj As McadTransaction
Set trnObj = mgr.StartTransaction

Dim name As String
name = "ComplexHide"
Dim complexHide As McadComplexHideSituation
Call rootDef.AddComplexHideSituation(name, subHides, complexHide)
End Sub

Figure 3 - complex hide

To demonstrate the intelligence behind this hide situation, try moving one of the circle components. The affected components are updated automatically, with lines re-broken or restored as appropriate. In the structure browser, right-click on the hide situation named ComplexHide. In the context menu, select Display Hidden Lines. This will result in something like figure 4, where hidden lines are shown with a dashed line type. Again, try moving one or more of the circle components to see the effect on the hide situation.

Figure 4 - hidden lines


Parts Lists and Balloons
Topics
Introduction to Parts Lists and Balloons

AutoCAD Mechanical maintains an internal database of parts used in your design. Depending on your chosen standard, this Bill of Materials (BOM) database may contain part numbers, item count, material, manufacturer, cost, and so on. At any stage in the design process, a report or parts list can be generated. AutoCAD Mechanical can place a dynamic parts list table in your drawing (see Bill of Materials API). AutoCAD Mechanical is able to automatically keep track of parts in this way only when Mechanical Structure is enabled.

AutoCAD Mechanical also provides a way to manually identify points and geometry for entry in the BOM. An intermediate object can act as an anchor for your part reference. This AcmPartRef part reference object allows AutoCAD Mechanical to keep track of the parts in your drawing in much the same way it would if Mechanical Structure were enabled. It's even possible to add part references to an empty drawing, effectively creating a drawing that is little more than a BOM and a parts list.

An essential element of a parts list is the label, usually enclosed in a balloon with a leader pointing to the relevant part. Balloons can be round, polygonal, or custom, and typically contain part number labels that match the corresponding part number in the parts list. If more than one label points to the same part, balloons can be clustered together in a line.

Figure 1 - An example of balloons containing part numbers.

A Look at the API

The balloon part of the BOM/parts list API is straightforward. An McadBalloons object is accessed from the McadBOMItem object. The McadBalloons object contains a collection of McadBalloon objects.

Figure 2 - Relevant part of the API object diagram.

The graphical representation of a balloon is an acmBalloon custom object, with properties accessible through the McadBalloon API object. Once an acmBalloon is added to your drawing, you can set its type, location, scale, color, leader properties, linkage to a BOM, and so on.

Also consider -

The AutoCAD Mechanical API provides access to various Standards settings. If you wish your parts list and balloon labelling to conform to a known or custom standard, use the McadBOMStandard and McadBalloonStandard objects to set preferences, then apply the standard, for example using the Standard property of the McadBalloon object.


Parts Lists and Balloons Sample Code
Parts Lists and Balloons Sample Code

The following sample demonstrates how to use the API to add a part reference with associated balloon and label. It also adds a parts list table, showing the data entered into the BOM by the addition of the part reference. This sample can be cut and pasted into your own VBA project. To use it, open a new drawing in AutoCAD Mechanical, start the VBA IDE, and paste all the code segments into the editor. We can use an empty drawing because we'll add our own part reference, but the code is very similar to that required when using 2D Mechanical Structure.

This code omits error checking for the sake of clarity and brevity. Always check that returned values are of the expected type.

Note: Before running this code, check that the required libraries are referenced in your project. In the VBA editor, go to Tools > References, and if the following type library is not checked, check it:
Autodesk SymBBAuto 4.0 Type Library
Copy Code
  Dim oSymBB As McadSymbolBBMgr
  Dim oPartRef As McadPartReference

  On Error Resume Next
  Set oSymBB = ThisDrawing.Application.GetInterfaceObject("SymBBAuto.McadSymbolBBMgr")
  Set oPartRef = ThisDrawing.ModelSpace.AddCustomObject("AcmPartRef")

  Dim pt(0 To 2) As Double
  pt(0) = 0: pt(1) = 0: pt(2) = 0
  oPartRef.Origin = pt

  Dim partData(0 To 3, 0 To 1) As String
  partData(0, 0) = "NAME"
  partData(0, 1) = "Some Part"
  partData(1, 0) = "MATERIAL"
  partData(1, 1) = "Steel"
  partData(2, 0) = "NOTE"
  partData(2, 1) = "A test"
  partData(3, 0) = "VENDOR"
  partData(3, 1) = "ACME"

  Dim oBOMMgr As McadBOMMgr
  Set oBOMMgr = oSymBB.BOMMgr
  Call oBOMMgr.SetPartData(oPartRef, partData)

  Dim oBOM As McadBOM
  If oBOMMgr.BOMTableExists("testBOM") Then
    Set oBOM = oBOMMgr.GetBOMTable(ThisDrawing.ModelSpace, "testBOM")
      Else
    Set oBOM = oBOMMgr.AddBOMTable("testBOM", ThisDrawing.ModelSpace)
  End If

  Dim oItem As McadBOMItem
  Set oItem = oBOM.AddItem(oPartRef.ObjectID, oBOM.Items.Count + 1)

  Dim oBalloon As McadBalloon
  Set oBalloon = ThisDrawing.ModelSpace.AddCustomObject("AcmBalloon")

  Dim points(0 To 5) As Double
  points(0) = 0: points(1) = 0: points(2) = 0
  points(3) = 2: points(4) = 1: points(5) = 0

  oBalloon.AppendBOMItem oItem
  oBalloon.BalloonType = sbCircularBalloon
  oBalloon.Origin = pt
  oBalloon.AddLeader points
  oBalloon.[Scale] = 1

  Dim plist As McadPartList
    Set plist = ThisDrawing.ModelSpace.AddCustomObject("AcmPartList")
    plist.BOM = oBOM

    pt(0) = -1#
    pt(1) = 0#
    plist.Origin = pt

  ThisDrawing.Application.Update
  ZoomExtents


Parts Lists and Balloons Sample Code Detailed Explanation
Parts Lists and Balloons Sample Code - Detailed Explanation

The following sample demonstrates how to use the API to add a part reference with associated balloon and label. It also adds a parts list table, showing the data entered into the BOM by the addition of the part reference. This sample can be cut and pasted into your own VBA project. To use it, open a new drawing in AutoCAD Mechanical, start the VBA IDE, and paste all the code segments into the editor. We can use an empty drawing because we'll add our own part reference, but the code is very similar to that required when using 2D Mechanical Structure.

First, we need to get the top-level McadSymbolBBMgr object. The rest of the BOM/Symbol API is accessible through this object. Also, we'll add an AcmPartRef object to the drawing. This lets AutoCAD Mechanical enter the relevant information into the BOM, and helps it keep track of the parts list.

Copy Code
  Dim oSymBB As McadSymbolBBMgr
  Dim oPartRef As McadPartReference

  On Error Resume Next
  Set oSymBB = ThisDrawing.Application.GetInterfaceObject("SymBBAuto.McadSymbolBBMgr")
  Set oPartRef = ThisDrawing.ModelSpace.AddCustomObject("AcmPartRef")

Now we have a part reference object in the drawing, let's move it to the desired location. Also, we'll create a data array and add some data, meaningful in the context of a BOM. This data will later be added to the BOM and will populate the parts list.

Copy Code
  Dim pt(0 To 2) As Double
  pt(0) = 0: pt(1) = 0: pt(2) = 0
  oPartRef.Origin = pt

  Dim partData(0 To 3, 0 To 1) As String
  partData(0, 0) = "NAME"
  partData(0, 1) = "Some Part"
  partData(1, 0) = "MATERIAL"
  partData(1, 1) = "Steel"
  partData(2, 0) = "NOTE"
  partData(2, 1) = "A test"
  partData(3, 0) = "VENDOR"
  partData(3, 1) = "ACME"

Now we can get the McadBOMMgr object, and assign the part reference and part data to it. Note however that it is not yet associated with a specific BOM, as one has not yet been created.

Copy Code
  Dim oBOMMgr As McadBOMMgr
  Set oBOMMgr = oSymBB.BOMMgr
  Call oBOMMgr.SetPartData(oPartRef, partData)

Since we now have some useful data, we can add a BOM table to the drawing. Trying to add a table that already exists will cause an error, so it is good practice to check to see if it exists. If it does, we can use it, otherwise we'll creat it. Here, we'll create a BOM table named 'testBOM'. Note though that we haven't yet associated our part reference with this table - we've just created the BOM object.

Copy Code
  Dim oBOM As McadBOM
  If oBOMMgr.BOMTableExists("testBOM") Then
    Set oBOM = oBOMMgr.GetBOMTable(ThisDrawing.ModelSpace, "testBOM")
      Else
    Set oBOM = oBOMMgr.AddBOMTable("testBOM", ThisDrawing.ModelSpace)
  End If

Now we can go ahead and associate our part reference with the BOM by adding an item to the BOM. The AddItem method adds a BOM item at a specific index, so we use the BOM item count plus one to add to the items instead of possibly overwriting an existing one. This means that if you run this code more than once, new items will continue to be added to the BOM.

Copy Code
  Dim oItem As McadBOMItem
  Set oItem = oBOM.AddItem(oPartRef.ObjectID, oBOM.Items.Count + 1)

We're ready to add a balloon to the drawing, but at this point it will not be associated with any BOM item.

Copy Code
  Dim oBalloon As McadBalloon
  Set oBalloon = ThisDrawing.ModelSpace.AddCustomObject("AcmBalloon")

Now we can associate the balloon with our BOM item, and also set some properties. We'll set the balloon type to circular, move it to where the part reference is, set its scale to 1, and add a leader (arrow) between the specified points.

Copy Code
  Dim points(0 To 5) As Double
  points(0) = 0: points(1) = 0: points(2) = 0
  points(3) = 2: points(4) = 1: points(5) = 0

  oBalloon.AppendBOMItem oItem
  oBalloon.BalloonType = sbCircularBalloon
  oBalloon.Origin = pt
  oBalloon.AddLeader points
  oBalloon.[Scale] = 1

At this point, in our drawing we have a part reference, label, balloon and leader, but no table to reference. We'll add a parts list table, and associate it with our BOM.

Copy Code
Dim plist As McadPartList
    Set plist = ThisDrawing.ModelSpace.AddCustomObject("AcmPartList")
    plist.BOM = oBOM

Now we can move our table to an appropriate location. Usually this would be relative to our drawing border. The table can be left or right justified and so on, but in this case, we'll set the location to an arbitrary -1,0.

Copy Code
    pt(0) = -1#
    pt(1) = 0#
    plist.Origin = pt

All that is left is to perform an update, and zoom to the drawing extents to ensure everything is visible.

Copy Code
  ThisDrawing.Application.Update
  ZoomExtents

The preceding code should produce a drawing that looks something like Figure 3. Note that the balloon and label references the line in the parts list table, which in turn contains the data we assigned. The API provides control over various aspects of the balloon and table appearance, including color, linetype, and so on.

Figure 3 - A part reference, balloon, and parts list table.


Revision Line
Topics
Revision Line

The AutoCAD Mechanical API uses the Revision Manager to set, read, and manipulate revisions and the Revision Line Manager to set, read, and manipulate revision lines.

These APIs are exposed in the SymBBAuto type library.


Revision Line Sample Code

Revision Line Sample Code

Copy Code
    Public Sub modifyRevLine()
      Dim acadApp As AcadApplication = System.Runtime.InteropServices.Marshal.GetActiveObject("AutoCAD.Application.18")
      Dim ThisDrawing As AcadDocument = acadApp.ActiveDocument
      Dim symbb As McadSymbolBBMgr = ThisDrawing.Application.GetInterfaceObject("SymBBAuto.McadSymbolBBMgr")
      Dim revListMgr As McadRevisionMgr = symbb.RevisionListMgr

      'retrieve the revision list collection object
      Dim revLists As McadRevisionLists = revListMgr.RevisionLists
      If revLists.Count = 0 Then
        Exit Sub
      End If

      'retrieve the particular revision list which is the first one in the collection object
      Dim revList As McadRevisionList = revLists.Item(0)
      If revList.Count = 0 Then
        Exit Sub
      End If

      'retrieve the attributes of the first item in the revision list
      Dim attributesMap As Object = revList.Item(0)
      For i = LBound(attributesMap) To UBound(attributesMap)
        If (attributesMap(i, 0) = "GEN-REV-NAME") Then
          attributesMap(i, 1) = "YourName"
        End If
      Next i

      'update the attributes of the item in the revision list
      Call revList.Set(0, attributesMap)
    End Sub


Revision Line Sample Code Detailed Explanation
Revision Line Sample Code - Detailed Explanation

This example retrieves and updates the first revision of a drawing.

The first section sets up variables, including a pointer to the application (acadApp), the current drawing (ThisDrawing), the symbol interface object (symbb), and the revision list manager (revListMgr).

Copy Code
Sub modifyRevLine()
      Dim acadApp As AcadApplication = System.Runtime.InteropServices.Marshal.GetActiveObject("AutoCAD.Application.18")
      Dim ThisDrawing As AcadDocument = acadApp.ActiveDocument
      Dim symbb As McadSymbolBBMgr = ThisDrawing.Application.GetInterfaceObject("SymBBAuto.McadSymbolBBMgr")
      Dim revListMgr As McadRevisionMgr = symbb.RevisionListMgr

The next section retrieves the revision list collection into the array variable revLists.

Copy Code
      'retrieve the revision list collection object
      Dim revLists As McadRevisionLists = revListMgr.RevisionLists

If there is no revision list (i.e. this drawing has no revisions stored), the script ends.

Copy Code
      If revLists.Count = 0 Then
        Exit Sub
      End If

This code declares the variable revList, which points to the first revision list item from the array revLists.

Copy Code
      'retrieve the particular revision list which is the first one in the collection object
      Dim revList As McadRevisionList = revLists.Item(0)

If there is no revision list, the script exits.

Copy Code
      If revList.Count = 0 Then
        Exit Sub
      End If

The object attributesMap gets the attributes of the first revision.

Copy Code
      'retrieve the attributes of the first item in the revision list
      Dim attributesMap As Object = revList.Item(0)

The For loop traverses the attributes in attributesMap, comparing the values to the string "GEN-REV-NAME." If this string is found, the code adds the string "YourName" to the revision list pointed to by attributesMap.

Copy Code
      For i = LBound(attributesMap) To UBound(attributesMap)
        If (attributesMap(i, 0) = "GEN-REV-NAME") Then
          attributesMap(i, 1) = "YourName"
        End If
      Next i

Finally, the code updates the attributes in the original revision list.

Copy Code
      'update the attributes of the item in the revision list
      Call revList.Set(0, attributesMap)
End Sub


Section Line
Topics
Section Line

The section line APIs provide functionality for the AMSECTIONLINE command to create and edit section lines. These APIs also enable configuring the symbol standard.

These APIs are exposed in SymBBAuto type library.


Section Line Sample Code
Section Line Sample Code
Copy Code
        Public Sub createSectionLine()
            Dim sectionline As McadSectionLine = ThisDrawing.ModelSpace.AddCustomObject("AmdtSectionSym")

            ' Set properties
            sectionline.ArrowVisibility = True
            sectionline.PlaneSymbolsVisibility = True
            sectionline.LineVisibility = McadLineVisibility.sbBetweenPlanes

            ' Set vertexes of section line
            Dim points(0 To 11) As Double

            points(0) = 12 : points(1) = 13 : points(2) = 0
            points(3) = 14 : points(4) = 10 : points(5) = 0
            points(6) = 13 : points(7) = 8 : points(8) = 0
            points(9) = 16 : points(10) = 6 : points(11) = 0

            Dim ArcPoints(0 To 2) As Double
            ArcPoints(0) = 13.5 : ArcPoints(1) = 9 : ArcPoints(2) = 0

            ' Set segment type of section line
            Dim segmentTypes(0 To 3) As McadSectionLineSegmentType
            segmentTypes(0) = McadSectionLineSegmentType.sbLineSegment
            segmentTypes(1) = McadSectionLineSegmentType.sbArcSegmentCenter
            segmentTypes(2) = McadSectionLineSegmentType.sbLineSegment
            segmentTypes(3) = McadSectionLineSegmentType.sbLineSegment

            sectionline.SetSectionPoints(points, ArcPoints, segmentTypes)

            ' Section side
            Dim sidePoint(0 To 2) As Double
            sidePoint(0) = 12 : sidePoint(1) = 10 : sidePoint(2) = 0
            sectionline.SectionSide = sidePoint

            ' Set label name
            sectionline.LabelName = "D"

            ' Get the number of label names
            Dim noOfNames As Integer
            noOfNames = sectionline.LabelNamesCount

            Dim labelPoint(0 To 2) As Double
            labelPoint(0) = 16 : labelPoint(1) = 11 : labelPoint(2) = 0
            ' Set origin of section view. This function must be invoked after posting section line to database.
            sectionline.SetSectionViewOrigin(labelPoint)

            sectionline.Update()

        End Sub


Section Line Sample Code Detailed Explanation

Section Line Sample Code - Detailed Explanation This code sample manipulates several aspects of a section line.

First, it creates the variable sectionLine and makes it a pointer to a custom McadSectionLine object.

Copy Code
        Public Sub createSectionLine()
            Dim sectionline As McadSectionLine = ThisDrawing.ModelSpace.AddCustomObject("AmdtSectionSym")

This section changes visibility properties of the section line, including the arrow visibility, plane symbols visibility, and line visibility.

Copy Code
            ' Set properties
            sectionline.ArrowVisibility = True
            sectionline.PlaneSymbolsVisibility = True
            sectionline.LineVisibility = McadLineVisibility.sbBetweenPlanes

The next three sections set up the values that will populate a SetSectionPoints call. This method requires information about a section line's points, arc points (x, y, and z points), and line segment types.

This section sets 12 vertexes of the section line. First, it creates a 12-element array of doubles (points), then it assigns values to each of the elements.

Copy Code
            ' Set vertexes of section line
            Dim points(0 To 11) As Double

            points(0) = 12 : points(1) = 13 : points(2) = 0
            points(3) = 14 : points(4) = 10 : points(5) = 0
            points(6) = 13 : points(7) = 8 : points(8) = 0
            points(9) = 16 : points(10) = 6 : points(11) = 0

This section creates a 3-element array of doubles (ArcPoints) and assigns values to each of the elements.

Copy Code
            Dim ArcPoints(0 To 2) As Double
            ArcPoints(0) = 13.5 : ArcPoints(1) = 9 : ArcPoints(2) = 0

The code then creates a 4-element array of line segment types (segmentTypes) and assigns values to each element.

Copy Code
            ' Set segment type of section line
            Dim segmentTypes(0 To 3) As McadSectionLineSegmentType
            segmentTypes(0) = McadSectionLineSegmentType.sbLineSegment
            segmentTypes(1) = McadSectionLineSegmentType.sbArcSegmentCenter
            segmentTypes(2) = McadSectionLineSegmentType.sbLineSegment
            segmentTypes(3) = McadSectionLineSegmentType.sbLineSegment

The code assigns values from the points, ArcPoints, and segmentTypes arrays to the sectionline object with the SetSectionPoints method.

Copy Code
            sectionline.SetSectionPoints(points, ArcPoints, segmentTypes)

The next section assigns values to the SectionSide element of the sectionline object. It creates a 3-element array (sidePoint) and assigns values to each element, then copies those values into sectionline.SectionSide.

Copy Code
            ' Section side
            Dim sidePoint(0 To 2) As Double
            sidePoint(0) = 12 : sidePoint(1) = 10 : sidePoint(2) = 0
            sectionline.SectionSide = sidePoint

The next part of the code sets the label name in sectionline.

Copy Code
            ' Set label name
            sectionline.LabelName = "D"

This segment shows how to count the label names and assign that value to a variable (noOfNames).

Copy Code
            ' Get the number of label names
            Dim noOfNames As Integer
            noOfNames = sectionline.LabelNamesCount

This section defines a 3-element array (labelPoint) and assigns values to it. This array is then used to populate the SetSectionViewOrigin property of the sectionline method.

Copy Code
            Dim labelPoint(0 To 2) As Double
            labelPoint(0) = 16 : labelPoint(1) = 11 : labelPoint(2) = 0
            ' Set origin of section view. This function must be invoked after posting a section line to the database.
            sectionline.SetSectionViewOrigin(labelPoint)

Finally, the code updates the section line.

Copy Code
            sectionline.Update()
        End Sub


Symbols
Topics
Introduction to the Symbols API

AutoCAD Mechanical eases the creation and maintenance of common mechanical drawing notation symbols. Symbols may include notation for datum targets, feature control frames, surface textures, datum and feature identifiers, welding, edge, taper and slope, note and detail. AutoCAD implements these graphics symbols with the custom objects listed in Table 1. Properties and methods affecting the content and display characteristics of these symbols are exposed through the corresponding API object.

Object - Symbol | API Class Name - Custom Object
McadSymbol | AcmSymbol
McadBalloon | AcmBalloon
McadDatumTarget | AcmDatumTarget
McadFeatureControlFrame | AcmFCF
McadDatumIdentifier | AcmDatumId
McadFeatureIdentifier | AcmFeatId
McadSurfaceTexture | AcmSurfaceTexture
McadWelding | AcmWelding
McadPartList | AcmPartList
McadPartListFilter | AcmPListfilter
McadEdge | AmdtEdge
McadTaper | AcmTaper
McadNote | AmdtNote
McadDetailSymbol | AmdtDetailSym
McadDetailSymbolLabel | AmdtDetailSymLabel

Table 1 - Custom object class names For example, a feature control frame symbol is added to the drawing by calling ModelSpace.AddCustomObject with the acmFCF class name. Properties of this instance of the graphical symbol can then be accessed through the McadFeatureControlFrame object of the API. For some symbols, graphics include a leader line. The API provides methods for adding, moving and removing leaders and leader nodes.

Figure 1 - Symbols API Object Diagram

Also consider -

When symbols notation needs to be consistent and to a standard, make use of the various standards APIs. Instead of setting the options on each symbol API object to determine the symbol appearance and behavior, set the common values on the appropriate standard, and apply that standard to your symbols by setting their Standard property. For example, with Welding symbols, use the McadWeldingStandard object to set common values such as prefix strings, text height, color, arrow type, and so on. The following diagram shows how to access the standards objects for available symbols.

Figure 2 - Standards API Object Diagram


Symbols Sample Code - Adding a Feature Control Frame Symbol
Symbols Sample Code - Adding a Feature Control Frame Symbol

The following code will add a Feature Control Frame graphic symbol to the drawing. Once the custom object is added, we obtain a reference to the corresponding McadFeatureControlFrame object, with which we can set various properties of the symbol. Here, we set key values, including tolerance values. A single leader line is added from 10,10,0 to 11,11,0. Following the code is an example of a Feature Control Frame symbol with notation values set. These code samples omit error checking for the sake of clarity and brevity. Always check that return values are of the expected type.

Copy Code
Dim symbb As McadSymbolBBMgr
Set symbb = ThisDrawing.Application.GetInterfaceObject("SymBBAuto.McadSymbolBBMgr")
Dim points(0 To 5) As Double
points(0) = 10#: points(1) = 10#: points(2) = 0#
points(3) = 11#: points(4) = 11#: points(5) = 0#
Dim fcf As McadFeatureControlFrame
Set fcf = ThisDrawing.ModelSpace.AddCustomObject("AcmFCF")
fcf.color = 2
fcf.DatumIDValue = "DATUM ID Value"
fcf.DatumPrimaryValue = "A"
fcf.IsAllAround = False
fcf.symbol = sbPerpendicularity
fcf.ToleranceBValue = "0.02"
fcf.ToleranceValue = "0.01"
fcf.AddLeader points
fcf.LeaderColor = 2
fcf.LeaderArrowType = sbArrowDot
ZoomExtents


Symbols Sample Code - Adding a Datum Target Symbol
Symbols Sample Code - Adding a Datum Target Symbol

The following code will add a Datum Target graphic symbol to the drawing. In a similar manner to the preceding example, once the custom object is added, we obtain a reference to the corresponding McadDatumTarget object, with which we can set various properties of the symbol. Here we set the datum values, as well properties affecting the appearance of the symbol such as color and whether a target line is drawn. A single leader line is added from 10,10,0 to 11,11,0. Following the code is an example of a Datum Target symbol with datum values set.

Copy Code
Dim symbb As McadSymbolBBMgr
Set symbb = ThisDrawing.Application.GetInterfaceObject("SymBBAuto.McadSymbolBBMgr")
Dim points(0 To 5) As Double
points(0) = 10#: points(1) = 10#: points(2) = 0#
points(3) = 11#: points(4) = 11#: points(5) = 0#
Dim datumtarget As McadDatumTarget
Set datumtarget = ThisDrawing.ModelSpace.AddCustomObject("AcmDatumTarget")
datumtarget.color = 2
datumtarget.DatumValue = "A"
datumtarget.DimensionValue = 0.01
datumtarget.TargetType = sbLine
datumtarget.DrawLine = True
datumtarget.AddLeader points
ZoomExtents


Symbols Sample Code - Adding a Surface Texture Symbol
Symbols Sample Code - Adding a Surface Texture Symbol

The following code will add a Surface Texture graphic symbol to the drawing. This code differs from preceding examples in that the code prompts the user for the location of the symbol. This is because the symbol origin point typically only makes sense in the paper units of a surface texture, relative to the lower-left corner of the media edge. So, these units must be translated to world coordinates in order to add the custom object. Once the custom object is added, we obtain a reference to the corresponding McadSurfaceTexture object, with which we can set relevant properties of the symbol. Here, we set key values, including production values. A leader line is not added. Following the code is an example of a Surface Texture symbol with notation values set.

Copy Code
Dim symbb As McadSymbolBBMgr
Set symbb = ThisDrawing.Application.GetInterfaceObject("SymBBAuto.McadSymbolBBMgr")
Dim surftext As McadSurfaceTexture
Set surftext = ThisDrawing.ModelSpace.AddCustomObject("AcmsurfaceTexture")
Dim pt As Variant
pt = ThisDrawing.Utility.GetPoint(, "Location for Surface Texture symbol: ")
pt = ThisDrawing.Utility.TranslateCoordinates(pt, acUCS, acWorld, False)
surftext.Origin = pt
surftext.AllowanceValue = 0.01
surftext.AutomaticAdjust = True
surftext.color = 1
surftext.CommentValue = "This is a comment"
surftext.CutoffValue = "2"
surftext.LayDirection = sbCircularRelativeToCenter
surftext.LayDirectionValue = 0.1
surftext.OtherMinimumValue = 0.2
surftext.OtherValue = 1
surftext.ProductionValue = 3
surftext.Production2Value = 4
surftext.RaMaximumValue = 6
surftext.RaMinimumValue = 5.5
surftext.MaximumSpacingValue = 0.5
surftext.ReferenceValue = 3.5
surftext.SamplingLengthValue = 10
surftext.WavinessValue = 2.05


Symbols Sample Code - Adding a Welding Symbol
Symbols Sample Code - Adding a Welding Symbol

The following code will add a Welding graphic symbol to the drawing. Once the acmWelding custom object is added, we obtain a reference to the corresponding McadWelding object, with which we set relevant properties of the symbol. Here, we set key values, including the weld type (bevel groove), length and spacing values. A leader line is added from 10,10,0 to 11,11,0. Following the code is an example of a Welding symbol with notation values set.

Copy Code
Dim symbb As McadSymbolBBMgr
Set symbb = ThisDrawing.Application.GetInterfaceObject("SymBBAuto.McadSymbolBBMgr")
Dim points(0 To 5) As Double
points(0) = 10#: points(1) = 10#: points(2) = 0#
points(3) = 11#: points(4) = 11#: points(5) = 0#
Dim weldsym As McadWelding
Set weldsym = ThisDrawing.ModelSpace.AddCustomObject("AcmWelding")
weldsym.AreaType = sbBevelGrooveWeld
weldsym.ClosedTail = True
weldsym.FieldWeld = True
weldsym.LengthValue = 10
weldsym.NotesValue = "A"
weldsym.NumberValue = 12
weldsym.SpacingValue = 4
weldsym.Type = sbBevelGrooveWeld
weldsym.AddLeader points
ZoomExtents


Symbols Sample Code - Adding an Edge Symbol
Symbols Sample Code - Adding an Edge Symbol

The following code will add an Edge graphic symbol to the drawing. Once the amdtEdge custom object is added, we obtain a reference to the corresponding McadEdge object, with which we set relevant properties of the symbol. Here, we set key values, including the minimum and maximum figures. A leader line is added from 10,10,0 to 11,11,0. Following the code is an example of an Edge symbol with notation values set.

Copy Code
Dim symbb As McadSymbolBBMgr
Set symbb = ThisDrawing.Application.GetInterfaceObject("SymBBAuto.McadSymbolBBMgr")
Dim points(0 To 5) As Double
points(0) = 10#: points(1) = 10#: points(2) = 0#
points(3) = 11#: points(4) = 11#: points(5) = 0#
Dim edgesym As McadEdge
Set edgesym = ThisDrawing.ModelSpace.AddCustomObject("amdtedge")
edgesym.AllAround = True
edgesym.MinValue = "1"
edgesym.MaxValue = "2"
edgesym.Majority = False
edgesym.AddLeader points
ZoomExtents


Symbols Sample Code - Adding a Taper and Slope Symbol
Symbols Sample Code - Adding a Taper and Slope Symbol

The following code will add a Taper and Slope graphic symbol to the drawing. Once the acmTaper custom object is added, we obtain a reference to the corresponding McadTaper object, with which we set relevant properties of the symbol. Here, we set key values, including the symbol subtype, oreientation and display string. A leader line is added from 10,10,0 to 50,50,0. Following the code is an example of a Taper and slope symbol with notation values set.

Copy Code
Dim symbb As McadSymbolBBMgr
Set symbb = ThisDrawing.Application.GetInterfaceObject("SymBBAuto.McadSymbolBBMgr")
Dim points(0 To 5) As Double
points(0) = 10#: points(1) = 10#: points(2) = 0#
points(3) = 50#: points(4) = 50#: points(5) = 0#
Dim tapersym As McadTaper
Set tapersym = ThisDrawing.ModelSpace.AddCustomObject("acmTaper")
tapersym.AboveCurve = True
tapersym.DisplayString = "1:5"
tapersym.Orientation = sbRightSide
tapersym.SubType = sbTaperThruRefLn
tapersym.AddLeader points
ZoomExtents


Symbols Sample Code - Adding a Note Symbol
Symbols Sample Code - Adding a Note Symbol

The following code will add a Note graphic symbol to the drawing. Once the amdtNote custom object is added, we obtain a reference to the corresponding McadNote object, with which we set relevant properties of the symbol. Here, we set key values, including the orientation, text alignment, and note text. A leader line is added from 10,10,0 to 20,30,0. Following the code is an example of a Note symbol with note text set.

Copy Code
Dim symbb As McadSymbolBBMgr
Set symbb = ThisDrawing.Application.GetInterfaceObject("SymBBAuto.McadSymbolBBMgr")
Dim points(0 To 5) As Double
points(0) = 10#: points(1) = 10#: points(2) = 0#
points(3) = 20#: points(4) = 30#: points(5) = 0#
Dim notesym As McadNote
Set notesym = ThisDrawing.ModelSpace.AddCustomObject("amdtnote")
notesym.AddLeader points
notesym.IsLeftOriented = False
notesym.TextAlignment = sbLeft
notesym.LeaderAttachPoint = sbTopLineRefLine
notesym.CreateNoteText ("Refer to spec")
notesym.Landing = True
ZoomExtents


Symbols Sample Code - Adding a Detail Symbol and Label
Symbols Sample Code - Adding a Detail Symbol and Label

The following code will add two graphic symbols to the drawing - a Detail symbol and an associated label. Once the amdtdetailsym custom object is added, we obtain a reference to the corresponding McadDetailSymbol object, with which we set relevant properties of the symbol. Here, we set key values, including the radius of the detail, the label name, the scale for the detail, and whether the border is visible. The code calls the CreateLabelEntity method to create the associated McadDetailSymbolLabel label object (custom object type AmdtDetailSymLabel). A leader line is added from 10,10,0 to 10,30,0. Following the code is an example of an McadDetailSymbol and McadDetailSymbolLabel pair.

Copy Code
Dim symbb As McadSymbolBBMgr
Set symbb = ThisDrawing.Application.GetInterfaceObject("SymBBAuto.McadSymbolBBMgr")
Dim ori(0 To 2) As Double
ori(0) = 50#: ori(1) = 10#: ori(2) = 0#
Dim detailsym As McadDetailSymbol
Set detailsym = ThisDrawing.ModelSpace.AddCustomObject("amdtdetailsym")
Dim center(0 To 2) As Double
center(0) = 10#: center(1) = 10#: center(2) = 0#
Dim cir As AcadCircle
Set cir = ThisDrawing.ModelSpace.AddCircle(center, 10)
Call detailsym.SetSourceGeometry(cir)
detailsym.IsAssociativeDetail = False
detailsym.LabelName = "Y"
detailsym.Radius = 10
detailsym.DetailScale = 2
detailsym.ShowAnnotationLeader = False
detailsym.ShowBorder = True
detailsym.CreateLabelEntity ori
ZoomExtents


Titles and Borders
Topics
Introduction to Titles and Borders

AutoCAD Mechanical provides a number of templates for standard drawing borders and title blocks. These are AutoCAD blocks containing text attributes, inserted at a certain position and scale, according to the desired standard. The use of text attributes makes it simple to add or modify labeled data contained within the title block, and also makes it simple for new, custom title blocks to be designed to suit customer needs. The AutoCAD Mechanical command AMTITLE enables the insertion of a border and title block, with the option of populating certain attributes automatically.

A Look at the Titles and Borders API

The Titles and Borders API provides functionality similar to the user interface. Although title block text attributes may be modified through the standard AutoCAD user interface or AutoCAD APIs, the AutoCAD Mechanical API provides an intuitive and streamlined mechanism for doing so, in addition to placement of borders and title blocks. The object model is shown in figure 1.

Figure 1

The McadTitleBorderMgr object provides access to a collection of McadTitleBorder objects. These in turn provide information about the settings associated with that border and title (the McadTitleBorderContext object) and the actual data presented by the border and title (the McadTitleBorderDescriptor object, and hence also the McadBorder and McadTitle objects).

The existing McadStandardObject has been modified to enable access to the new McadTitleBorderStandard object. This object exposes methods and properties listing available paper formats, revision lists, titles and title blocks, corresponding to the standard templates provided.

Many lists in this API take the form of arrays of string pairs, thus providing a convenient way of referencing or specifying data via keywords. For example, to specify the text for the scale box in a title block, you would search the attributes associated with that title block for the string pair whose first element contains the identifier "GEN-TITLE-SCA", and then modify the content of the second element - say to "1:20" or whatever value is required. This will then be reflected in the updated title block.

Sample Code

These two sample VBA code listings may be cut and pasted into the AutoCAD Mechanical VBA editor. Make sure all grayed sections are present. Immediately before each section is text describing that section's purpose and operation - do not copy this text into the editor. The code omits error checking for the sake of clarity and brevity. In your code, always check that return values are of the expected type.

Note: Ensure that the Autodesk SymBBAuto 3.0 Type Library is available in your project. In the Visual Basic Editor, pick Tools > References, and check the appropriate reference.

Sample Code 1 - Updating Title Block Attributes Sample Code 2 - Updating Title Block Attributes

Common Title Block Element Keywords

The following table lists common array element keywords, corresponding to title block attribute tags.

Element Keyword | Title Block Box
GEN-TITLE-DWG | File name
GEN-TITLE-SCA | Scale
GEN-TITLE-DAT | Draft date
GEN-TITLE-NAME | Drawn by
GEN-TITLE-DES1 | Drawing title
GEN-TITLE-DES2 | Drawing subtitle
GEN-TITLE-NR | Drawing number
GEN-TITLE-DACT | Design activity
GEN-TITLE-FSCM | FSCM number
GEN-TITLE-APPM | Approved by
GEN-TITLE-APPD | Approval date
GEN-TITLE-ISSM | Issued by
GEN-TITLE-ISSD | Issue Date
GEN-TITLE-SIZ | Size
GEN-TITLE-CHKM | Checked by
GEN-TITLE-CTRN | Contract number
GEN-TITLE-SHEET | Sheet number
GEN-TITLE-REV | Revision
GEN-TITLE-WT | Weight

Table 1

Summary

The Titles and Borders API provides a simple mechanism for the placement of standards-based drawing borders incorporating title block data. If the supplied border title templates are not suitable, they may be modified or new ones created since they are implemented as standard AutoCAD blocks with attributes, with the attribute tags corresponding to the list of element keywords described in Table 1. The API provides access to general border and title settings as well as specific title block content.


Titles and Borders Sample Code 1
Titles and Borders Sample Code 2 - Adding a Border and Title Block

The first code sample below will run in a new drawing. It will insert an ANSI standard border, paper format A at half scale. The title block text attributes will be partly populated with the name of the drawing issuer and the issued date.

Copy Code
Sub CreateTitleBorder()
    Dim symbb As McadSymbolBBMgr
    Set symbb = ThisDrawing.Application.GetInterfaceObject("SymBBAuto.McadSymbolBBMgr")

    Dim tiBrdMgr As McadTitleBorderMgr
    Set tiBrdMgr = symbb.TitleBorderMgr

    Dim tiBrdDesc As McadTitleBorderDescriptor
    Set tiBrdDesc = tiBrdMgr.NewDescriptor

    Dim tiBrdContext As McadTitleBorderContext
    Set tiBrdContext = tiBrdMgr.NewContext

    Dim brd As McadBorder
    Set brd = tiBrdDesc.Border
    brd.Name = "ANSI_A"

    Dim titl As McadTitle
    Set titl = tiBrdDesc.Title
    titl.Name = "ANSI_TITLEA"

    tiBrdDesc.TitleBorderScale = 0.5

    Dim pos(0 To 2) As Double
    pos(0) = 100
    pos(1) = 200
    pos(2) = 0
    tiBrdDesc.Position = pos

    If IsEmpty(titl.Attributes) Then
        Dim attr(1, 1) As String
        attr(0, 0) = "GEN-TITLE-ISSD"
        attr(0, 1) = "11/11/07"
        attr(1, 0) = "GEN-TITLE-ISSM"
        attr(1, 1) = "Prof Woodpecker"
        titl.Attributes = attr
    End If

    Dim tiBrd As McadTitleBorder
    Set tiBrd = tiBrdMgr.CreateTitleBorder(tiBrdDesc, tiBrdContext)

End Sub

Figure 2


Titles and Borders Sample Code 1 - Detailed Explanation
Titles and Borders Sample Code 2 - Adding a Border and Title Block - Detailed Explanation

The first code sample below will run in a new drawing. It will insert an ANSI standard border, paper format A at half scale. The title block text attributes will be partly populated with the name of the drawing issuer and the issued date.

The first task is to obtain the root McadSymbolBBMgr object. Other symbol or bill of materials objects are accessed through this object, but we are only interested in the border and title APIs, so as noted in the preceding object model diagram, we can get the McadTitleBorderMgr object.

Copy Code
Sub CreateTitleBorder()
    Dim symbb As McadSymbolBBMgr
    Set symbb = ThisDrawing.Application.GetInterfaceObject("SymBBAuto.McadSymbolBBMgr")

    Dim tiBrdMgr As McadTitleBorderMgr
    Set tiBrdMgr = symbb.TitleBorderMgr

Create new McadTitleBorderDescriptor and McadTitleBorderContext objects. In this sample, we need only modify the former from its default, but we need both in order to add a new McadtitleBorder to the McadtitleBorders collection later.

Copy Code
    Dim tiBrdDesc As McadTitleBorderDescriptor
    Set tiBrdDesc = tiBrdMgr.NewDescriptor

    Dim tiBrdContext As McadTitleBorderContext
    Set tiBrdContext = tiBrdMgr.NewContext

Obtain the McadBorder object from the descriptor in order to set its name identifier, in this case ANSI_A (it could just as easily be ISO_A3 and so on).

Copy Code
    Dim brd As McadBorder
    Set brd = tiBrdDesc.Border
    brd.Name = "ANSI_A"

Obtain the McadTitle object from the descriptor in order to set its name identifier, in this case ANSI_TITLEA (it could just as easily be ANSI_TITUS or ISO_TITLEA and so on).

Copy Code
    Dim titl As McadTitle
    Set titl = tiBrdDesc.Title
    titl.Name = "ANSI_TITLEA"

Set the scale of the title border. This specifies the insert scale of the border block. This is not the same as the scale box in the title box. For example, if you intend to draw at a 1:2 scale, the insert value would be 0.5 in order to have the drawing, title block and border plot to the correct scale.

Copy Code
    tiBrdDesc.TitleBorderScale = 0.5

Set the insert position of the border block, in this case at 100, 200, 0. This corresponds to the bottom left corner of the border.

Copy Code
    Dim pos(0 To 2) As Double
    pos(0) = 100
    pos(1) = 200
    pos(2) = 0
    tiBrdDesc.Position = pos

The code will populate attributes for a new title block, so there should not be any existing values, but it's good to check. Then create an array of string pairs, each containing a keyword and an appropriate value. Other common keywords are listed in Table 1. Here we provide values for the Issued Date and Issued By attributes - 11/11/07 and Prof Woodpecker respectively. The Attributes property of the McadTitle object is updated with the new array of values.

Copy Code
    If IsEmpty(titl.Attributes) Then
        Dim attr(1, 1) As String
        attr(0, 0) = "GEN-TITLE-ISSD"
        attr(0, 1) = "11/11/07"
        attr(1, 0) = "GEN-TITLE-ISSM"
        attr(1, 1) = "Prof Woodpecker"
        titl.Attributes = attr
    End If

Now we can add the new McadTitleBorder object to the collection, referencing the unchanged default McadTitleBorderContext object and the updated McadTitleBorderDescriptor object.

Copy Code
    Dim tiBrd As McadTitleBorder
    Set tiBrd = tiBrdMgr.CreateTitleBorder(tiBrdDesc, tiBrdContext)

End Sub

When run, the code will insert the border and title block, with the updated values present in the title block, as shown in figure 2. Note that several other attributes of the title block already have values not explicitly set by the sample code. AutoCAD Mechanical is able to update certain attributes automatically, such as the drawing file name. These values can be overwritten if necessary.

Figure 2


Titles and Borders Sample Code 2
Titles and Borders Sample Code 2 - Updating Title Block Attributes

The following VBA code sample demonstrates how to modify the value of existing attributes in a title block.

Copy Code
Sub UpdateAtt()
Dim symbb As McadSymbolBBMgr
Set symbb = ThisDrawing.Application.GetInterfaceObject("SymBBAuto.McadSymbolBBMgr")

Dim titlBrdMgr As McadTitleBorderMgr
Set titlBrdMgr = symbb.TitleBorderMgr

Dim titlBrds As McadTitleBorders
Set titlBrds = titlBrdMgr.TitleBorders

Dim titlBrd As McadTitleBorder
Set titlBrd = titlBrds.Item(0)

Dim titlBrdDesc As McadTitleBorderDescriptor
Set titlBrdDesc = titlBrd.Descriptor

Dim titl As McadTitle
Set titl = titlBrdDesc.Title

Dim attr() As String
attr = titl.Attributes
For i = LBound(attr) To UBound(attr)
If (attr(i, 0) = "GEN-TITLE-DWG") Then
attr(i, 1) = "Main Clamp"
ElseIf (attr(i, 0) = "GEN-TITLE-SCA") Then
attr(i, 1) = "2:1"
ElseIf (attr(i, 0) = "GEN-TITLE-NR") Then
attr(i, 1) = "33 /2"
End If
Next i titl.Attributes = attr

Dim titlBrdContext As McadTitleBorderContext
Set titlBrdContext = titlBrdMgr.NewContext

Dim ret As Boolean
ret = titlBrd.Modify(titlBrdContext)

End Sub

Figure 3


Titles and Borders Sample Code 2 Detailed Explanation
Titles and Borders Sample Code 2 - Updating Title Block Attributes - Detailed Explanation

The following VBA code sample demonstrates how to modify the value of existing attributes in a title block. The first part is much the same as the previous sample, except this time we obtain an existing McadTitleBorder object from the McadTitleBorders collection.

Copy Code
Sub UpdateAtt()
Dim symbb As McadSymbolBBMgr
Set symbb = ThisDrawing.Application.GetInterfaceObject("SymBBAuto.McadSymbolBBMgr")

Dim titlBrdMgr As McadTitleBorderMgr
Set titlBrdMgr = symbb.TitleBorderMgr

Dim titlBrds As McadTitleBorders
Set titlBrds = titlBrdMgr.TitleBorders

Dim titlBrd As McadTitleBorder
Set titlBrd = titlBrds.Item(0)

We will modify attribute (data) values by updating the McadTitle object, obtained through the McadTitleBorderDescriptor object.

Copy Code
Dim titlBrdDesc As McadTitleBorderDescriptor
Set titlBrdDesc = titlBrd.Descriptor

Dim titl As McadTitle
Set titl = titlBrdDesc.Title

Get the array of attributes using the Attributes property. Iterate through the attributes, checking each string pair for the keyword of the data we wish to change - in this case the drawing file name, the scale, and the drawing number. Update the second element of each pair with the new value. Reassign the updated string array to the Attributes property of the McadTitle object.

Copy Code
Dim attr() As String
attr = titl.Attributes
For i = LBound(attr) To UBound(attr)
If (attr(i, 0) = "GEN-TITLE-DWG") Then
attr(i, 1) = "Main Clamp"
ElseIf (attr(i, 0) = "GEN-TITLE-SCA") Then
attr(i, 1) = "2:1"
ElseIf (attr(i, 0) = "GEN-TITLE-NR") Then
attr(i, 1) = "33 /2"
End If
Next i titl.Attributes = attr

Although no changes we made to the title order border settings (context) a new McadTitleBorderContext must be used to update the McadTitleBorder in order to reflect any changes, including those made to the title block.

Copy Code
Dim titlBrdContext As McadTitleBorderContext
Set titlBrdContext = titlBrdMgr.NewContext

Dim ret As Boolean
ret = titlBrd.Modify(titlBrdContext)

End Sub

When focus is returned to AutoCAD Mechanical from the VBA editor, the title block should appear something like figure 3. Note the updated drawing number, scale, and file name boxes.

Figure 3


Sample Code Disclaimer

The sample code provided in this Help system and in the AutoCAD Mechanical Software Developers Kit is intended as an aid for learning application development techniques for AutoCAD Mechanical and as such is provided "as-is". The sample code is covered by the relevant sections of the Autodesk AutoCAD Mechanical license agreement, repeated below.

AUTODESK, INC. LICENSE AGREEMENT NOTICE TO USER:

AUTODESK IS WILLING TO LICENSE THE ACCOMPANYING SOFTWARE TO YOU ONLY UPON THE CONDITION THAT YOU ACCEPT ALL OF THE TERMS CONTAINED IN THIS LICENSE AGREEMENT AND ANY SUPPLEMENTARY OR UNIQUE LICENSE TERMS INCLUDED HEREWITH ("AGREEMENT").

YOUR USE OF THE SOFTWARE INDICATES YOUR ASSENT TO BE BOUND BY THE LICENSE TERMS SET FORTH BELOW.

This Autodesk, Inc. ("Autodesk") License Agreement accompanies an Autodesk software product and related explanatory materials ("Software"). The term "Software" shall also include any upgrades, modified versions or updates of the Software licensed to you by Autodesk.

Autodesk grants to you a nonexclusive limited license to use and copy the Software, provided that you agree to the following:

1. USE OF THE SOFTWARE.

You may install the Software in a single location on a single hard disk or other storage device; post and make available the Software on a network file server for the purpose of installation onto hard disks or other storage devices or use of the Software over such network; and make backup copies of the Software. You may make unlimited copies of the Software and give copies to other persons or entities, including downloading the Software from the Internet or similar on-line source, so long as all such copies contain this Agreement and the same copyright and other proprietary notices that appear on or in the Software.

2. COPYRIGHT/PROPRIETARY RIGHTS.

The Software is owned by Autodesk and its suppliers, and its structure, organization and code are the valuable trade secrets of Autodesk and its suppliers. The Software is also protected by copyright law and international treaty provisions. You may use trademarks only to identify printed output produced by the Software, in accordance with accepted trademark practice, including identification of trademark owner's name. Such use of any trademark does not give you any rights of ownership in that trademark. Except as stated above, this Agreement does not grant you any intellectual property rights in the Software.

3. RESTRICTIONS.

You agree not to rent, lease, modify, adapt, translate, reverse engineer, decompile, or disassemble the Software or otherwise attempt to discover the source code of the Software except to the extent permitted by law where this is indispensable to obtain the information necessary to achieve interoperability of an independently created program with the Software or with another program and such information is not readily available from Autodesk or elsewhere. You may not decompile the Software if such information is available by licensing any Autodesk Software Developer's Kit or other Autodesk software product through an Authorized Autodesk Reseller or a local Autodesk office.

You understand and acknowledge that this Agreement provides for the copying and distribution of the Software in its entirety and does not allow for partial distribution of any of the components (.dlls or other files) that make up the Software. Creating derivatives of the Software is strictly prohibited. Redistribution of: (i) the Software that is integrated with other technology as a component or standalone product and does not provide end user access to the complete install process; (ii) incomplete, modified, reverse engineered, or otherwise altered copies of the Software, is not permitted and will result in termination of this Agreement.

COPYING THE SOFTWARE EXCEPT AS PERMITTED BY THIS END USER LICENSE AGREEMENT IS COPYRIGHT INFRINGEMENT UNDER THE LAWS OF YOUR COUNTRY. IF YOU COPY THE SOFTWARE IN VIOLATION OF THIS END USER LICENSE AGREEMENT THEN YOU ARE VIOLATING THE LAW. YOU MAY BE LIABLE TO AUTODESK FOR DAMAGES AND YOU MAY BE SUBJECT TO CRIMINAL PENALTIES.

4. NO WARRANTY.

The Software is provided to you "AS IS," and you acknowledge that it may contain errors. Autodesk disclaims any warranty or liability obligations to you of any kind.

AUTODESK AND ITS SUPPLIERS DO NOT AND CANNOT WARRANT THE PERFORMANCE OR RESULTS YOU MAY OBTAIN BY USING THE SOFTWARE OR DOCUMENTATION. AUTODESK AND ITS SUPPLIERS MAKE NO WARRANTIES, EXPRESS OR IMPLIED, AS TO NONINFRINGEMENT OF THIRD PARTY RIGHTS, MERCHANTABILITY, OR FITNESS FOR ANY PARTICULAR PURPOSE. IN NO EVENT WILL AUTODESK OR ITS SUPPLIERS BE LIABLE TO YOU FOR ANY CONSEQUENTIAL, INCIDENTAL OR SPECIAL DAMAGES, INCLUDING ANY LOST PROFITS OR LOST SAVINGS, EVEN IF AN AUTODESK REPRESENTATIVE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES, OR FOR ANY CLAIM BY ANY THIRD PARTY.

Some states or jurisdictions do not allow the exclusion or limitation of incidental, consequential or special damages, or the exclusion of implied warranties or limitations on how long an implied warranty may last, so the above limitations may not apply to you.

5. DISCLAIMER.

COMPUTER-AIDED DESIGN SOFTWARE AND OTHER TECHNICAL SOFTWARE ARE TOOLS INTENDED TO BE USED BY TRAINED PROFESSIONALS ONLY. THEY ARE NOT SUBSTITUTES FOR YOUR PROFESSIONAL JUDGMENT. COMPUTER-AIDED DESIGN SOFTWARE AND OTHER TECHNICAL SOFTWARE ARE INTENDED TO ASSIST WITH PRODUCT DESIGN AND ARE NOT SUBSTITUTES FOR INDEPENDENT TESTING OF PRODUCT STRESS, SAFETY AND UTILITY. DUE TO THE LARGE VARIETY OF POTENTIAL APPLICATIONS FOR THE SOFTWARE, THE SOFTWARE HAS NOT BEEN TESTED IN ALL SITUATIONS UNDER WHICH IT MAY BE USED. AUTODESK SHALL NOT BE LIABLE IN ANY MANNER WHATSOEVER FOR THE RESULTS OBTAINED THROUGH THE USE OF THE SOFTWARE. PERSONS USING THE SOFTWARE ARE RESPONSIBLE FOR THE SUPERVISION, MANAGEMENT AND CONTROL OF THE SOFTWARE. THIS RESPONSIBILITY INCLUDES, BUT IS NOT LIMITED TO, THE DETERMINATION OF APPROPRIATE USES FOR THE SOFTWARE AND THE SELECTION OF THE SOFTWARE AND OTHER PROGRAMS TO ACHIEVE INTENDED RESULTS. PERSONS USING THE SOFTWARE ARE ALSO RESPONSIBLE FOR ESTABLISHING THE ADEQUACY OF INDEPENDENT PROCEDURES FOR TESTING THE RELIABILITY AND ACCURACY OF ANY PROGRAM OUTPUT, INCLUDING ALL ITEMS DESIGNED BY USING THE SOFTWARE.

6. LIMITATION OF LIABILITY.

IN NO EVENT WILL AUTODESK BE LIABLE FOR ANY LOSS OR DAMAGES OF ANY KIND, INCLUDING LOSS OF DATA, LOST PROFITS, COST OF COVER OR OTHER SPECIAL, INCIDENTAL, CONSEQUENTIAL OR INDIRECT DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE SOFTWARE OR DOCUMENTATION, HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY. THIS LIMITATION WILL APPLY EVEN IF AUTODESK HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSS OR DAMAGE. YOU ACKNOWLEDGE THAT THE NO CHARGE LICENSE FEE REFLECTS THIS ALLOCATION OF RISK.

7. GOVERNING LAW AND GENERAL PROVISIONS.

This Agreement will be governed by the laws of the country in which you acquired the Software, excluding the application of its conflicts of law rules. This Agreement will not be governed by the United Nations Convention on Contracts for the International Sale of Goods, the application of which is expressly excluded. If any part of this Agreement is found void and unenforceable, it will not affect the validity of the balance of the Agreement, which shall remain valid and enforceable according to its terms. You agree that the Software will not be shipped, transferred or exported into any country or used in any manner prohibited by the United States Export Administration Act or any other applicable export control law, restriction or regulation. This Agreement shall automatically terminate upon failure by you to comply with its terms. This Agreement may only be modified in writing signed by an authorized officer of Autodesk.

8. NOTICE TO GOVERNMENT END USERS.

If this product is acquired under the terms of a GSA contract -- Use, reproduction or disclosure is subject to the restrictions set forth in the applicable ADP Schedule contract; DOD contract -- Use, duplication or disclosure by the Government is subject to restrictions as set forth in subparagraph (c)(1)(ii) of 252.227-7013; Civilian agency contract -- Use, reproduction or disclosure is subject to 52.227-19(a) through (d) and restrictions set forth in the accompanying end user agreement.


Comparing the VBA IDE Operation in 32-bit and 64-bit Environments
Comparing VBA IDE Operation in 32-bit and 64-bit Environments

Microsoft's VBA IDE is a 32-bit application. When running in a 32-bit environment, VBA applications run inside the AutoCAD memory space (see Figure 1). In a 64-bit environment, VBA applications run outside of AutoCAD's memory space.

Figure 1

Add-ins always run within the AutoCAD memory space, while ActiveX and other external applications always run outside of the AutoCAD memory space.

If your application does extensive, repetitive processing and runs in a 64-bit environment, consider writing it as an add-in rather than a VBA application. Because add-ins run inside the AutoCAD 64-bit memory space, they can run significantly faster and using less processing power.


Getting Started with the C++ API
Topics
The AutoCAD Mechanical C++ API

Most of this developer guide covers general principles for working with key parts of the AutoCAD Mechanical COM API. However, in addition to the COM API, a C++ API is also provided. This overview and subsections will walk through the steps necessary to configure Visual Studio to build a C++ project into an ObjectARX (AutoCAD Runtime Extension) file, and to use the ObjectARX wizards to generate template code.

First, install the AutoCAD Mechanical SDK. This is a superset of the AutoCAD ObjectARX SDK. Installation of the SDK will result in the creation of three directories; acadmapi, mcadapi, and objectarx at the install location. These directories contain the following:

  • acadmapi - this directory contains header files, documentation and samples, 32-bit and 64-bit versions of the API libraries, including symbols, title border and scale area functionality.
  • mcadapi - this directory contains header files, documentation, samples, and 32-bit and 64-bit versions of API libraries for Mechanical 2D Structure, and some miscellaneous utility functions.
  • objectarx - this directory contains the AutoCAD ObjectARX SDK, including libraries, samples, utility tools and documentation. The most recent version may also be downloaded from the Autodesk website.

The AutoCAD Mechanical C++ API builds on and extends the AutoCAD ObjectARX API, so some familiarity with ObjectARX is assumed. The ObjectARX utility tools for Visual Studio greatly ease the creation of skeletal code templates when starting a project. The objectarx\utils\ObjARXWiz directory contains an MSI file (ARXWizards.msi) that will install the relevant wizards and register them with your Visual Studio installation.


Your First AutoCAD Mechanical C++ Application
Your First AutoCAD Mechanical C++ Application

  1. Install the AutoCAD Mechanical SDK and the ObjectARX wizard described here.
  2. Start a new project in Visual Studio. In the New Project dialog, navigate to the Visual C++ -> ObjectARX templates, and select ObjectARX/DBX Project.
  3. Complete the dialog (project and solution name etc). Typically, accept the defaults for the remaining dialogs (COM options etc) unless you intend to use one or more of the available options.
  4. The wizard will create the project files and configure the project appropriately.
  5. Currently, the project is unaware of the AutoCAD Mechanical SDK libraries and header files, so these directories must be added to the project properties in Visual Studio. In the Project -> Properties dialog, under the Configuration Properties -> C/C++ -> General - > Additional Include Directories topic, add the inc directories found under the acadmapi and mcadapi directories. Also, add the appropriate inc-win32 or inc-x64 directory, depending on your target system (but not both).
  6. In the Project -> Properties dialog, under the Configuration Properties -> Linker - > General -> Additional Library Directories topic, add the library directories found under the acadmapi and mcadapi directories. Add either the lib-win32 or lib-x64 directories, depending on your target system (but not both).
  7. In the Project -> Properties dialog, under the Configuration Properties -> Linker - > Input -> Additional Dependencies topic, add the following libraries: mcadapi_crx.lib, acmsymbb_crx.lib and acad.lib.
  8. AutoCAD and AutoCAD Mechanical use the UNICODE character set.
    1. Ensure the correct option is selected under Configuration Properties -> General -> character Set.
    2. In the Configuration Properties -> C/C++ -> Preprocessor tab, add "AD_UNICODE" to the Preprocessor Definitions. "AD_UNICODE" is the Unicode-specific symbol defined by ObjectARX in "AdAChar.h"
    3. In the Configuration Properties -> C/C++ -> Language tab, set wchar_t as the built-in type.
    4. In the Configuration Properties -> Linker -> Input tab, ensure the AutoCAD libraries are the correct version ("21" to "22"). For example, change "acge21.lib" to "acge22.lib", "acdb21.lib" to "acdb22.lib".


Adding a New Command to AutoCAD Mechanical
Adding a new Command to AutoCAD Mechanical

  1. Add a command to your code. The a> button on the new ObjectARX toolbar in Visual Studio will invoke an ObjectARX Commands wizard to help with this.
  2. Right-click in the ARX Command list area of the ObjectARX Commands dialog, and select New. This will populate the dialog with default values (see Figure 1). Either accept these values or change the command name from MyCommand1 to something more meaningful. When you click OK, the wizard will add the necessary code to the project to add a command to AutoCAD Mechanical.

Figure 1 - ObjectARX Commands dialog box

  3. View the acrxEntryPoint.cpp source file. The wizard has added a comment to indicate where you need to add your implementation code. In this example, the comment reads "// Add your code for command PETEHArxProject1._MyCommand1 here". This is where you add your application code. The rest of this overview describes the process of adding some functional AutoCAD Mechanical API code to the project.


Adding AutoCAD Mechanical C++ API Code
Adding AutoCAD Mechanical C++ API code

Before adding more code, decide where to put it. Very small applications with few lines of code can be placed in the acrxEntryPoint.cpp file noted above, underneath the "// Add your code for command PETEHArxProject1._MyCommand1 here" comment added by the wizard. However, in the majority of cases, it will make more sense to divide your source code amongst new cpp files. In this case, we'll add a new file to the project. In this example the file is called myAcmCode.cpp, and we'll call it from acrxEntryPoint.cpp.

  1. Right-click the Source Files topic in the Visual Studio Solution Explorer (the tree view listing the project files). Click Add -> New Item.
  2. In the Add New Item dialog, click on the Code topic, then click on the C++ File (.cpp) template.
  3. Enter a name for the file, for example myAcmCode.cpp, then click Add.
  4. Repeat steps 1 to 3 above, except add a new header file to the Include Files topic called myAcmCode.h (or substitute your chosen name).
  5. Open the new myAcmCode.h file and add the following line:
Copy Code
void folder_main();

This declaration will enable the compiler to find the main function in the new source code file.

  6. Add a reference to the new header file somewhere. A good place is in the StdAfx.h file generated by the wizard. Add the following line at the end of the file:
Copy Code
#include "myAcmCode.h"
  7. Add the following line to acrxEntryPoint.cpp underneath the "// Add your code for command PETEHArxProject1._MyCommand1 here" comment.
Copy Code
folder_main();

This will call the code in the new myAcmCode.cpp source file.

  8. Now you are ready to add the AutoCAD Mechanical C++ API code to the new myAcmCode.cpp source file. Open the file in Visual Studio, and paste in the code listed at the end of this overview. Ensure you copy everything, from the #include lines to the final closing curly brace }. You will notice a function definition void folder_main() - this is the function that will be called when your command is invoked in AutoCAD Mechanical.


Compiling and Running
Compiling and Running

  1. The project is ready to compile. In Visual Studio, select Build -> Build ArxProject1 (or the project name you chose if it is different).
  2. After a successful build, you will find a win32\debug directory (or possibly a winx64 or a release directory if you changed the target settings) in your project directory. It will contain a number of files including one with the file name extension .arx or .crx - this is the built application. It is a renamed DLL that can be loaded and executed in AutoCAD's memory space.
  3. All that remains is to load the application in AutoCAD Mechanical and run the command. The easiest way to load an arx or crx file in AutoCAD is to drag and drop the file into the main AutoCAD window. Alternatively, use the Tools -> Load Application... dialog available from the AutoCAD menu to select the arx or crx file to load.
  4. With the arx or crx file loaded, the new command is available to run. Referring to figure 1, this example defined a command named MyCommand1. Type MyCommand1 (or the command name you chose) at the AutoCAD Mechanical command prompt to run the application.


What Does it Do?
What does it do?

  1. The sample code provided in this overview exercises some of the mechanical structure folder functionality of the API.
  2. If your AutoCAD Mechanical view does not currently include the Mechanical Browser panel, turn it on via the WSCURRENT command (set to "Structure").
  3. When you run the arx or crx, it will:
    1. Add a rectangle and a circle.
    2. Add a new folder to the mechanical structure (Folder 1).
    3. Add the rectangle and circle to the folder.
    4. Add a second instance of the folder.
    5. Add two diagonal lines to the rectangles.
    6. Add a nested folder containing a smaller circle with an orthogonal line.
    7. Add a second nested folder, with the small circle/line combination rotated. See Figure 2 for the resulting entities and mechanical browser view.

Figure 2 - Folders created

  4. Next, the application will:
    1. Prompt the user to select a folder.
    2. Report the name and full occurrence path of the folder (see Figure 3).

Figure 3 - Output


Sample Code
Sample Code
Copy Code
#include "micomp.h"
#include "adslib.h"
#include "dbents.h"
#include "dbapserv.h"
#include "math.h"

Acad::ErrorStatus postToDb(AcDbEntity* ent, AcDbObjectId& objId);
void folder_main();

Adesk::Boolean createFolders(
  AcDbObjectId *&circleObjId,
  AmiFolderKey *&newFolder1,
  AmiFolderKey *&pNewFolder2);

Adesk::Boolean modifyFolders(
  AcDbObjectId *&circleObjId,
  AmiFolderKey *&pNewFolder1);

Adesk::Boolean nestFolders(
  AmiFolderKey *&pNewFolder1,
  AmiFolderKey *&pNewFolder2,
  AmiFolderDefKey *&pNewFolder3Def,
  AmiFolderKey *&pNewFolder3);

Adesk::Boolean selectionMode(
  AmiFolderKey *&newFolder1,
  AmiFolderDefKey *&newFolder3Def,
  AmiFolderKey *&newFolder3);

//  the main function
//
void folder_main()
{
  acutPrintf(_T("Folder Tutorial\n-------------"));

  AcDbObjectId *circleObjId = new AcDbObjectId();
    AmiFolderKey *pNewFolder1 = new AmiFolderKey();
    AmiFolderKey *pNewFolder2 = new AmiFolderKey();
    createFolders(circleObjId, pNewFolder1, pNewFolder2);
  modifyFolders(circleObjId, pNewFolder1);

  AmiFolderDefKey *pNewFolder3Def = new AmiFolderDefKey();
  AmiFolderKey *pNewFolder3 = new AmiFolderKey();
  nestFolders(pNewFolder1, pNewFolder2, pNewFolder3Def, pNewFolder3);

  Adesk::Boolean es;
  es=selectionMode(pNewFolder1, pNewFolder3Def, pNewFolder3);
  if (!es) acutPrintf(_T("Operation canceled!"));
}

// --------------- create folders ---------------
Adesk::Boolean createFolders(
    AcDbObjectId *&circleObjId,
    AmiFolderKey *&pNewFolder1,
  AmiFolderKey *&pNewFolder2) {

  AcDbObjectId rectangleObjId;

  AcDbObjectIdArray entities;
  AmiFolderDefKey *pNewFolder1Def;
  AcGePoint3d center = AcGePoint3d(30,30,0);
  double radius = 10;
  AcDbCircle *pCircle1 = new AcDbCircle();

  AcGePoint3dArray ptArr;
  ptArr.setLogicalLength(4);
  ptArr[0].set(10, 50, 0.0);
  ptArr[1].set(50, 50, 0.0);
  ptArr[2].set(50, 10, 0.0);
  ptArr[3].set(10, 10, 0.0);
  AcDb2dPolyline *pRectangle1 = new AcDb2dPolyline(AcDb::k2dSimplePoly, ptArr, 0.0, Adesk::kTrue);

  AcGeMatrix3d newFolder1GeMatrix;
  AcGeVector3d newFolder1Translation;

  // Step 1
  // create circle
  pCircle1->setCenter(center);
  pCircle1->setRadius(radius);
  postToDb(pCircle1, *circleObjId);
  entities.append(*circleObjId);

  // create rectangle
  pRectangle1->makeClosed();
  postToDb(pRectangle1, rectangleObjId);
  entities.append(rectangleObjId);

  // Step 2
  // set translations
  newFolder1Translation.set(10,10,00);
  newFolder1GeMatrix.setTranslation(newFolder1Translation);

  // create folder
  ami2DSCreateFolderDef(
    pNewFolder1Def,
    pNewFolder1,
    entities,
    NULL,
    newFolder1GeMatrix,
    NULL,
    _T("Folder1"));

  // Step 3
  // set translations
  newFolder1Translation.set(60,10,00);
  newFolder1GeMatrix.setTranslation(newFolder1Translation);

  // add new instance
  ami2DSInstanceFolder(
    pNewFolder1Def,
    NULL,
    newFolder1GeMatrix,
    pNewFolder2);

  return Adesk::kTrue;
}

// --------------- modify folders ---------------
Adesk::Boolean modifyFolders(
  AcDbObjectId *&circleObjId,
  AmiFolderKey *&pNewFolder1) {

  AcDbObjectIdArray entities;
  AcDbObjectId diagonal1ObjId;
  AcDbObjectId diagonal2ObjId;

  AcDbLine *pDiagonal1 = new AcDbLine();
  AcDbLine *pDiagonal2 = new AcDbLine();

  AcDbDatabase *pWorkingDb = acdbHostApplicationServices()->workingDatabase();
  AmiFolderKey *pEditTarget = new AmiFolderKey();
  AmiFolderKey *pActiveTarget = NULL;

  // Step 1
  // remove the circle entity from newFolder
  entities.append(*circleObjId);
  amiRemoveViewEntities(entities);

  // Step 2a
  // add first diagonal line to newFolder using amiAddEntitiesToFolder
  pDiagonal1->setStartPoint(AcGePoint3d(10,50,0));
  pDiagonal1->setEndPoint(AcGePoint3d(50,10,0));
  postToDb(pDiagonal1, diagonal1ObjId);
  entities.insertAt(0,diagonal1ObjId);

  amiAddEntitiesToFolder(entities,pNewFolder1);

  // Step 2b
  // add second diagonal line to newFolder using gMgr.EditTarget
  pDiagonal2->setStartPoint(AcGePoint3d(50,50,0));
  pDiagonal2->setEndPoint(AcGePoint3d(10,10,0));
  postToDb(pDiagonal2, diagonal2ObjId);
  entities.insertAt(0,diagonal2ObjId);

  // use edit target
  ami2DSSetEditTarget(pNewFolder1, pWorkingDb);
  ami2DSGetEditTarget((AmiObjectKey*&)pActiveTarget, pWorkingDb);
  if (pActiveTarget==pNewFolder1) acutPrintf(_T("same!\n"));
  amiAddEntitiesToFolder(entities,pActiveTarget);
  ami2DSSetEditTarget(NULL, pWorkingDb);

  return true;
}

// --------------- nesting folders ---------------
Adesk::Boolean nestFolders(
  AmiFolderKey *&pNewFolder1,
  AmiFolderKey *&pNewFolder2,
  AmiFolderDefKey *&pNewFolder3Def,
  AmiFolderKey *&pNewFolder3) {

  AmiFolderKey *pNewFolder4;
  AcDbObjectIdArray entities;
  AcDbObjectId line1ObjId;
  AcDbObjectId circle1ObjId;
  AcDbLine *pDiagonal1 = new AcDbLine();
  AcDbCircle *pCircle1 = new AcDbCircle();

  AcGePoint3d center = AcGePoint3d(30,17.5,0);
  double radius = 5;

  AcDbLine *pLine1 = new AcDbLine();
  AcGeMatrix3d newFolder3GeMatrix;
  AcGeVector3d newFolder3Translation;
  AcGeMatrix3d newFolder3GeMatrix2;
  AcGeVector3d newFolder3Translation2;

  // Step 1
  // create circle
  pCircle1->setCenter(center);
  pCircle1->setRadius(radius);
  postToDb(pCircle1, circle1ObjId);
  entities.append(circle1ObjId);

  // create line
  pLine1->setStartPoint(AcGePoint3d(30,17.5,0));
  pLine1->setEndPoint(AcGePoint3d(35,17.5,0));
  postToDb(pLine1, line1ObjId);
  entities.append(line1ObjId);

  // Step 2
  // set translation
  newFolder3Translation.set(30,17.5,0);
  newFolder3GeMatrix.setTranslation(newFolder3Translation);

  // create Folder2 and one instance
  ami2DSCreateFolderDef(
    pNewFolder3Def,
    pNewFolder3,
    entities,
    NULL,
    newFolder3GeMatrix,
    pNewFolder1,
    _T("Folder2"));

  // set translation and rotate comp1_2side by 90 degree
  newFolder3Translation2.set(0,0,1);
  newFolder3GeMatrix2.setToRotation((atan(1.0)*2), newFolder3Translation2, AcGePoint3d(0,0,0));
  newFolder3Translation2.set(92.5,30,0);
  newFolder3GeMatrix2.setTranslation(newFolder3Translation2);

  // Step 3
  // add a second instance
  ami2DSInstanceFolder(
    pNewFolder3Def,
    pNewFolder2,
    newFolder3GeMatrix2,
    pNewFolder4);

  return true;
}

// --------------- selection modes ---------------
Adesk::Boolean selectionMode(
  AmiFolderKey *&pNewFolder1,
  AmiFolderDefKey *&pNewFolder3Def,
  AmiFolderKey *&pNewFolder3) {

  TCHAR msg[256];
  TCHAR *viewName;
  TCHAR *pathName;
  AmiPickObj *pPick = new AmiPickObj();
    AmiFolderKey *pPickFolder = NULL;

  Adesk::UInt16 red=0;

  //ZoomAll();

  // Step 1
  struct resbuf* entmask = NULL;
  AmiKeyType pickKeyType=Ami::folderKey;
  amiPick(_T("Select folder"), pickKeyType, entmask, *pPick);
  amiGetKeyFromPick(pPick, pickKeyType, (AmiObjectKey *&) pPickFolder);

  ami2DSGetViewName(pPickFolder,viewName);
  ami2DSGetViewGeomPathName(pPickFolder,pathName);

  _stprintf(msg,_T("The selected folder's name is '%s'\nIt's full occurrence path is '%s'"), viewName,pathName);
  acutPrintf(msg);

  // Step 2
  // --------------- property override ---------------

    // set color override to red
  amiApplyColorOverride(pNewFolder1, red) ;
  amiApplyColorOverride(pNewFolder3, red) ;

  // Step 3
  // --------------- alter visibility ---------------
//    Dim newFolder3Occurences As McadFolders

  int i=0;
  AcDbDatabase &workingDb = *acdbHostApplicationServices()->workingDatabase();

  // set Folder1:1 to invisible
  amiSetObjectVisibility(pNewFolder1, Adesk::kFalse);

  AmiFolderKey** pNewFolder3Occurences;
  long counter=0;
  ami2DSGetViewDefOccurrences(pNewFolder3Def, counter, pNewFolder3Occurences, &workingDb);

  // set Folder1:1 to visible
  amiSetObjectVisibility(pNewFolder1, Adesk::kTrue);

  return true;
}

Acad::ErrorStatus postToDb(AcDbEntity* ent, AcDbObjectId& objId)
{
  Acad::ErrorStatus      es;
  AcDbBlockTable*        pBlockTable;
  AcDbBlockTableRecord*  pSpaceRecord;

  if ((es = acdbHostApplicationServices()->workingDatabase()->getBlockTable(pBlockTable, AcDb::kForRead)) != Acad::eOk) return es;

  //  Determine appropriate space from AutoCAD core function isPspace()
  if ((es = pBlockTable->getAt(ACDB_MODEL_SPACE,pSpaceRecord, AcDb::kForWrite)) != Acad::eOk)
    return es;
  if ((es = pBlockTable->close()) != Acad::eOk)
    return es;
  if ((es = pSpaceRecord->appendAcDbEntity(objId, ent)) != Acad::eOk)
    return es;
  // be carefully, entity remains opened.
  ent->close();
  pSpaceRecord->close();

  return Acad::eOk;
}


Additional Information
Additional Information

Additional code samples and tools are available in the AutoCAD Mechanical SDK.

For details of the AutoCAD Mechanical API library of C++ classes, see the C++ API reference help file, acadmcpp_22_0.chm.

For documentation, tools and samples relating to ObjectARX, refer to the AutoCAD ObjectARX SDK, or visit the Autodesk Developer Network website.


Comparing the COM and C++ APIs
Comparing the COM and C++ APIs

This table compares the functionality of the AutoCAD Mechanical APIs, to assist in the transition to the C/C++ API from the COM API, or to the COM API from the C/C++ API.

MCAD API Function | Equivalent VBA Object/Method/Property
amiDefineAttClass | AcadmApplication.AddAttributeClass
amiGetAttClasses | AcadmApplication.get_AttributeClasses
amiUndefineAttClass | AcadmApplication.RemoveAttributeClass
amiGetAttClassFields | AcadmApplication.GetAttributeClassFields
amiReadAttClassesFromFile | AcadmApplication.ReadAttributeClass
amiWriteAttClassToFile | AcadmApplication.WriteAttributeClass
amiWriteAttClassesToFile | AcadmApplication.WriteAttributeClass
amiGetExecVersion | AcadmApplication.GetVersionNumber
amiGetAssociatedDoc | ApiBegin.ApiBegin
amiGetFileVersion | McadDocument.GetVersionNumber
amiGetLayerGroups | McadLayerGroupMgr.GetLayerGroupNames
amiGetLayerGroupEntities | McadLayerGroupMgr.GetLayerGroupEntities
amiMoveLayerGroupEntities | McadLayerGroupMgr.MoveLayerGroupEntities
amiGetLayersFromGroup | McadLayerGroupMgr.GetLayersFromGroup
amiGetPickPoint | McadPick.get_PickPoint
amiSetPickPoint | McadPick.put_PickPoint
amiGetPickKeyType | McadPick.get_ObjectType
amiSetPickKeyType | McadPick.put_ObjectType
amiPick | McadUtility.Pick
amiGetKeyFromPick | McadUtility.GetObjectFromPick
amiMakeInstAtt | McadUtility.CreateAttribute
amiGetAllAttributes | McadUtility.GetAllAttributes
amiCreateSystemAttribute | McadUtility.CreateSystemAttribute
amiGetDbIdsFromKey | McadUtility.GetIdsFromObject
 | McadUtility.CreateAttributeField
 | McadUtility.GetAttributeFromID
 | McadUtility.CreatePickObject
 | McadUtility.GetObjectFromKey
amiGetKeyFromId | McadUtility.GetObjectFromID
amiGetGeomKey | McadUtility.GetGeometryFromPick
amiRefocusKey | McadUtility.RefocusObject
actrTransactionManager->getObject | McadAttribute.GetAttribute
amiGetAttributeHolders | McadAttribute.get_Holders
AmiAttribute::getName | McadAttribute.get_ClassName
AmiAttribute::getNumFields | McadAttribute.get_FieldCount
AmiAttribute::getFieldDesc | McadAttribute.get_FieldDescription
AmiAttribute::getFieldName | McadAttribute.get_FieldName
AmiAttribute::getFieldType | McadAttribute.get_FieldType
AmiAttribute::getFieldCont | McadAttribute.get_FieldValue
AmiAttribute::setFieldCont | McadAttribute.put_FieldValue
AmiAttribute::getFieldName | McadAttribute.GetFieldIndex
ami2DSGetViewDescName | McadFolderDescriptor.get_ViewName
ami2DSSetViewDescName | McadFolderDescriptor.put_ViewName
ami2DSGetViewDescPosition | McadFolderDescriptor.get_Position
ami2DSSetViewDescPosition | McadFolderDescriptor.put_Position
ami2DSSetViewDescEntities | McadFolderDescriptor.put_Entities
ami2DSGetViewDescEntities | McadFolderDescriptor.get_Entities
ami2DSSetViewDescViews | McadFolderDescriptor.put_Views
ami2DSGetViewDescViews | McadFolderDescriptor.get_Views
ami2DSGetViewDescTargetView | McadFolderDescriptor.get_TargetView
ami2DSSetViewDescTargetView | McadFolderDescriptor.put_TargetView
ami2DSGetViewDescDefinition | McadFolderDescriptor.get_Definition
ami2DSSetViewDescDefinition | McadFolderDescriptor.put_Definition
ami2DSGetViewDescViewKey | McadFolderDescriptor.get_ViewKey
ami2DSGetViewDescPowObjType | McadFolderDescriptor.get_PowerObjectType
ami2DSCreateFolderFromDesc | McadFolderDescriptor.CreateFolder
ami2DSGetCompViewDescComp | McadComponentViewDescriptor.get_Component
ami2DSSetCompViewDescComp | McadComponentViewDescriptor.put_Component
ami2DSCreateCompViewFromDesc | McadComponentViewDescriptor.CreateComponentView
ami2DSGetFullCompViewDescName | McadComponentViewDescriptor.get_FullViewName
ami2DSGetCompDescComponent | Mcad2DComponentDescriptor.get_Component
ami2DSGetCompDescCompDef | Mcad2DComponentDescriptor.get_ComponentDefinition
ami2DSSetCompDescCompDef | Mcad2DComponentDescriptor.put_ComponentDefinition
ami2DSGetCompDescOwningCompDef | Mcad2DComponentDescriptor.get_OwningComponentDefinition
ami2DSSetCompDescOwningCompDef | Mcad2DComponentDescriptor.put_OwningComponentDefinition
ami2DSAddCompDescCompView | Mcad2DComponentDescriptor.AddComponentView
ami2DSRemoveCompDescCompView | Mcad2DComponentDescriptor.RemoveComponentView
ami2DSGetCompDescCompViews | Mcad2DComponentDescriptor.get_ComponentViews
ami2DSHasCompDescEqualTypeWithCompView | Mcad2DComponentDescriptor.get_HasEqualTypeWithView
ami2DSCreate2dCompFromDesc | Mcad2DComponentDescriptor.CreateComponent
ami2DSGetDescName | Mcad2DStructureDescriptor.get_Name
ami2DSSetDescName | Mcad2DStructureDescriptor.put_Name
amiGetAssociatedDoc | Mcad2DStructureDescriptor.get_Document
ami2DSAddComplexStdPartGroupDescView | Mcad2dComplexStdPartCompGroupDescriptor.AddView
ami2DSRemoveComplexStdPartGroupDescView | Mcad2dComplexStdPartCompGroupDescriptor.RemoveView
ami2DSGetComplexStdPartGroupDescViews | Mcad2dComplexStdPartCompGroupDescriptor.get_Views
ami2DSHasComplexStdPartDescEqualTypeWithViewGroup | Mcad2dComplexStdPartCompGroupDescriptor.get_HasEqualTypeWithViewGroup
ami2DSMigrate2dComplexStdPart | Mcad2dComplexStdPartCompGroupDescriptor.MigrateTo2DStructure
ami2DSGetShaftGroupDescViews | Mcad2dShaftCompGroupDescriptor.get_Views
ami2DSMigrate2dShaft | Mcad2dShaftCompGroupDescriptor.MigrateTo2DStructure
ami2DSCreateFolderDescrip | Mcad2DStructureMgr.CreateFolderDescriptor
ami2DSCreateCompViewDescrip | Mcad2DStructureMgr.CreateComponentViewDescriptor
ami2DSCreate2dCompDescrip | Mcad2DStructureMgr.Create2dComponentDescriptor
ami2DSCreate2dStdCompDescrip | Mcad2DStructureMgr.Create2dStdPartComponentDescriptor
ami2DSCreate2dComplexStdPartGroupDescrip | Mcad2DStructureMgr.Create2dComplexStdPartCompGroupDescriptor
ami2DSGetComplexStdPartViewsForMigr | Mcad2DStructureMgr.GetComplexStdPartViewsForMigr
ami2DSGetComplexStdPartsForMigr | Mcad2DStructureMgr.GetComplexStdPartsForMigr
ami2DSGetShaftsForMigr | Mcad2DStructureMgr.GetShaftsForMigr
ami2DSGetFolderPowObjectsForMigr | Mcad2DStructureMgr.GetFolderPowerObjectsForMigr
ami2DSGetSglStdPartCompsForMigr | Mcad2DStructureMgr.GetSingleStdPartComponentsForMigr
ami2DSGetSglStdPartViewsForMigr | Mcad2DStructureMgr.GetSingleStdPartViewsForMigr
amiGetMasterCompDef | Mcad2DStructureMgr.get_RootComponentDefinition
amiGetMasterViewDef | Mcad2DStructureMgr.get_RootViewDefinition
ami2DSCreateStructureFromBlocks | Mcad2DStructureMgr.CreateStructureFromBlocks
ami2DSGetEditTarget | Mcad2DStructureMgr.get_EditTarget
ami2DSSetEditTarget | Mcad2DStructureMgr.put_EditTarget
ami2DSGetFolderDefs | Mcad2DStructureMgr.GetFolderDefinitions
ami2DSGetComponentDefs | Mcad2DStructureMgr.GetComponentDefinitions
ami2DSCopyFolderFromDatabase | Mcad2DStructureMgr.CopyFolderFromDatabase
ami2DSCopyComponentFromDatabase | Mcad2DStructureMgr.CopyComponentFromDatabase
ami2DSExternalStructureDatabases | Mcad2DStructureMgr.get_ExternalStructureDatabases
ami2DSGetStructureFromEntity | Mcad2DStructureMgr.GetStructureFromEntity
ami2DSGetSelection | Mcad2DStructureMgr.GetSelection
ami2DSHighlight | Mcad2DStructureMgr.Highlight
ami2DSUpdate | Mcad2DStructureMgr.Update
ami2DSRestructure | Mcad2DStructureMgr.RestructureViews
ami2DSIsStructureBlock | Mcad2DStructureMgr.IsStructureBlock
amiCreate2dCompDef | Mcad2DStructureMgr.AddNewComponentDefinition
ami2DSCreateCompViewDef | Mcad2DStructureMgr.AddNewComponentViewDefinition
ami2DSCreateFolderDef | Mcad2DStructureMgr.AddNewFolderDefinition
ami2DSInstanceCompView | Mcad2DStructureMgr.AddNewComponentView
ami2DSInstanceFolder | Mcad2DStructureMgr.AddNewFolder
ami2DSInstanceAnnotationView | Mcad2DStructureMgr.AddNewAnnotationViewDefinition
ami2DSIsStructureEnabled | Mcad2DStructureMgr.Is2DStructureEnabled
ami2DSIsEntityAllowed | Mcad2DStructureMgr.IsEntityAllowed
ami2DSIsFreeEntity | Mcad2DStructureMgr.IsFreeEntity
ami2DSIsInActiveTarget | Mcad2DStructureMgr.IsInActiveTarget
ami2DSHasFolderDefinition | Mcad2DStructureMgr.HasFolderDefinition
ami2DSHasComponentDefinition | Mcad2DStructureMgr.HasComponentDefinition
ami2DSGetNextComponentDefinitionName | Mcad2DStructureMgr.GetNextComponentDefinitionName
ami2DSGetNextFolderDefinitionName | Mcad2DStructureMgr.GetNextFolderDefinitionName
ami2DSGetNextAnnotationViewDefinitionName | Mcad2DStructureMgr.GetNextAnnotationViewDefinitionName
ami2DSGetCompViewDefs | Mcad2DStructureMgr.GetComponentViewDefinitions
ami2DSCreateBlocksFromStructure | Mcad2DStructureMgr.CreateBlocksFromStructure
ami2DSPurgeComponentDefinitions | Mcad2DStructureMgr.PurgeComponentDefinitions
ami2DSPurgeAnnotationViewDefinitions | Mcad2DStructureMgr.PurgeAnnotationViewDefinitions
ami2DSPurgeFolderDefinitions | Mcad2DStructureMgr.PurgeFolderDefinitions
ami2DSPurgeComponentViewDefinitions | Mcad2DStructureMgr.PurgeComponentViewDefinitions
ami2DSPurgeAll | Mcad2DStructureMgr.PurgeAll2DS
amiHighlight | IMcadObject.Highlight
amiIsDirectlyEditable | IMcadObject.get_Editable
amiObjectWasErased | IMcadObject.get_WasErased
amiEraseObject | IMcadObject.Delete
amiAreKeysEquivalent | IMcadObject.IsEqualTo
amiGetContainingComp | IMcadObject.ContainingComponent
amiGetAttributes | IMcadObject.GetAttributes
amiAddAttribute | IMcadObject.AddAttribute
amiRemoveAttribute | IMcadObject.RemoveAttribute
amiGetAssociatedDoc | IMcadObject.get_Document
amiGetObjectName | IMcadObject.get_Name
amiSetObjectName | IMcadObject.put_Name
amiRegen | IMcadObject.Update
amiAddPersistentKey | IMcadObject.MakePersistent
amiGetObjectVisibility | IMcadObject.get_Visible
amiSetObjectVisibility | IMcadObject.put_Visible
amiGetObjectState | IMcadObject.GetIsState
amiGetGeomData | IMcadGeometry.get_Geometry
amiSetGeometry | IMcadGeometry.put_Geometry
amiObjectHasChanged | IMcadGeometry.HasChanged
amiGetCompChildren | McadComponent.get_Children
amiGetCompDef | McadComponent.get_Definition
amiGetCompName | McadComponent.get_Name
amiSetCompName | McadComponent.put_Name
amiGetCompOwner | McadComponent.get_Owner
amiGetCompPosition | McadComponent.get_Position
amiSetCompPosition | McadComponent.put_Position
amiGetCompInDef | McadComponent.GetComponentInDefinition
amiIsComp2D | McadComponent.get_is2D
amiIsCompHasExternalDef | McadComponent.get_hasExternalDef
amiCompSortChildren | McadComponent.SortChildren
amiGetViewsInComp | McadComponent.get_ComponentViews
ami2DSCompHasGhostViews | McadComponent.get_HasGhostViews
ami2DSCompGetReference | McadComponent.get_Reference
ami2DSCompSetReference | McadComponent.put_Reference
ami2DSReplaceCompDef | McadComponent.ReplaceDefinition
ami2DSCopyCompDefinition | McadComponent.CopyDefinition
ami2DSHasCompOverrideProperties | McadComponent.get_HasOverrideProperties
ami2DSSetCompColorOverride | McadComponent.ColorOverride
ami2DSSetCompVisibilityOverride | McadComponent.VisibilityOverride
ami2DSSetCompPredefinedRefOverride | McadComponent.PredefinedReferenceOverride
ami2DSClearCompOverrideProperties | McadComponent.ClearOverrideProperties
amiGetCompDefChildren | McadComponentDefinition.get_Children
amiIsCompDefExternal | McadComponentDefinition.get_IsExternal
amiIsCompDefLeafNode | McadComponentDefinition.get_IsLeafNode
amiIsCompDefMaster | McadComponentDefinition.get_IsRoot
ami2DSGetCompDefName | McadComponentDefinition.get_Name
amiSetCompDefName | McadComponentDefinition.put_Name
amiAddCompToCompDef | McadComponentDefinition.AddComponent
amiRemoveCompFromCompDef | McadComponentDefinition.RemoveComponent
amiCopyCompDef | McadComponentDefinition.CopyDefinition
amiExternalize | McadComponentDefinition.Externalize
amiGetAllInstances | McadComponentDefinition.GetInstances
amiIsCompDef2D | McadComponentDefinition.get_is2D
amiIsCompDef2DAssembly | McadComponentDefinition.get_is2DAssembly
amiIsCompDefFeature | McadComponentDefinition.get_isFeature
amiCompDefSortChildren | McadComponentDefinition.SortChildren
amiGetPhantomState | McadComponentDefinition.get_PhantomState
amiSetPhantomState | McadComponentDefinition.put_PhantomState
amiGetViewDefsInCompDef | McadComponentDefinition.get_ComponentViewDefinitions
amiIsCompDefStdPart | McadComponentDefinition.get_isStandardPart
amiIsCompDefShaft | McadComponentDefinition.get_isShaft
ami2DSLocalize | McadComponentDefinition.Localize2DS
ami2DSGetCompDefName | McadComponentDefinition.get_ExternalPath
ami2DSGetCompDefName | McadComponentDefinition.get_Name
ami2DSCompDefHasComponentViewDefinition | McadComponentDefinition.HasComponentViewDefinition
ami2DSCompDefGetNextComponentViewDefinitionName | McadComponentDefinition.GetNextComponentViewDefinitionName
amiRemoveFolder | McadFolderDefinition.RemoveFolder
ami2DSInstanceFolder2 | McadFolderDefinition.AddFolder
ami2DSGetViewDefName | McadFolderDefinition.get_Name
ami2DSGetViewDefFullName | McadFolderDefinition.get_FullName
ami2DSSetViewDefName | McadFolderDefinition.put_Name
ami2DSGetNextViewName | McadFolderDefinition.get_NextViewName
ami2DSLookupViewName | McadFolderDefinition.LookupViewName
ami2DSGetViewDefGeomExtents | McadFolderDefinition.Extents
ami2DSSortViewDefChildren | McadFolderDefinition.SortChildren
ami2DSIsViewDefExternal | McadFolderDefinition.get_IsExternal
ami2DSIsViewDefAnnotation | McadFolderDefinition.get_IsAnnotation
ami2DSIsViewDefDetail | McadFolderDefinition.get_IsDetail
ami2DSViewDefInstancesViewDef | McadFolderDefinition.get_InstancesDefinition
ami2DSGetViewDefChildren | McadFolderDefinition.get_Children
ami2DSGetViewDefInstances | McadFolderDefinition.get_Instances
ami2DSGetViewDefOccurrences | McadFolderDefinition.get_Occurrences
ami2DSGetViewDefInstanceCount | McadFolderDefinition.get_InstanceCount
ami2DSGetViewDefChildrenCount | McadFolderDefinition.get_ChildrenCount
ami2DSGetViewDefType | McadFolderDefinition.get_ViewType
ami2DSSetViewDefType | McadFolderDefinition.put_ViewType
ami2DSAddFromExistingEntsToViewDef | McadFolderDefinition.AddFromExistingEntities
ami2DSLocalizeFolderDef | McadFolderDefinition.Localize
ami2DSExternalizeFolderDef | McadFolderDefinition.Externalize
ami2DSIsViewDefLocked | McadFolderDefinition.get_IsLocked
ami2DSSetViewDefLocked | McadFolderDefinition.put_IsLocked
ami2DSGetViewDefLockType | McadFolderDefinition.get_LockType
ami2DSIsMasterViewDef | McadFolderDefinition.get_IsRoot
ami2DSGetDefHideSituations | McadFolderDefinition.get_HideSituations
ami2DSGetDefComplexHideSituations | McadFolderDefinition.get_ComplexHideSituations
ami2DSFindHideSituations | McadFolderDefinition.FindHideSituations
ami2DSAddHideSiatuation | McadFolderDefinition.AddHideSituation
ami2DSAddComplexHideSiatuation | McadFolderDefinition.AddComplexHideSituation
ami2DSSetHidesSuppressState | McadFolderDefinition.SetHidesSuppressState
ami2DSGetHidesSuppressState | McadFolderDefinition.GetHidesSuppressState
amiRemoveView | McadComponentViewDefinition.RemoveComponentView
ami2DSInstanceCompView2 | McadComponentViewDefinition.AddComponentView
ami2DSGetCompViewDefOwner | McadComponentViewDefinition.get_Owner
ami2DSIsCompViewDefFeature | McadComponentViewDefinition.get_IsFeature
ami2DSRemoveChildView | McadAnnotationViewDefinition.RemoveComponentView
ami2DSAddViewToAnnotationView | McadAnnotationViewDefinition.AddComponentView
ami2DSGetAnnotationViewDefCompDef | McadAnnotationViewDefinition.get_ComponentDefinition
ami2DSAddEntitiesToView | McadFolder.AddEntities
ami2DSRemoveViewEntities | McadFolder.RemoveEntities
ami2DSGetViewName | McadFolder.get_ViewName
ami2DSGetViewGeomPathName | McadFolder.get_GeomPathName
ami2DSGetViewEntities | McadFolder.get_Entities
ami2DSGetViewPosition | McadFolder.get_Position
ami2DSSetViewPosition | McadFolder.put_Position
ami2DSGetViewDefinition | McadFolder.get_Definition
ami2DSGetViewOwnerDef | McadFolder.get_Owner
ami2DSGetViewChildren | McadFolder.get_Children
ami2DSGetViewGeomExtents | McadFolder.get_ExtentsMaximum
ami2DSGetViewGeomExtents | McadFolder.get_ExtentsMinimum
ami2DSHasViewExternalDef | McadFolder.get_HasExternalDef
ami2DSIsViewLocked | McadFolder.get_IsLocked
ami2DSIsLeafOccurrence | McadFolder.get_IsLeaf
ami2DSIsInstanceOccurrence | McadFolder.get_IsInstance
ami2DSIsSubentityOf | McadFolder.IsSubentityOf
ami2DSClearLeaf | McadFolder.ClearLeaf
ami2DSGetViewContextDef | McadFolder.get_ContextDefinition
ami2DSCopyEntitiesToView | McadFolder.CopyEntities
ami2DSExplodeView | McadFolder.Explode
ami2DSReplaceViewDef | McadFolder.ReplaceDefinition
ami2DSCopyViewDefinition | McadFolder.CopyViewDefinition
ami2DSCopyViewToView | McadFolder.CopyView
ami2DSSetViewScale | McadFolder.put_ViewScale
ami2DSGetViewScale | McadFolder.get_ViewScale
ami2DSHasViewOverrideProperties | McadFolder.get_HasOverrideProperties
ami2DSSetViewColorOverride | McadFolder.ColorOverride
ami2DSSetViewVisibilityOverride | McadFolder.VisibilityOverride
ami2DSSetViewPredefinedRefOverride | McadFolder.PredefinedReferenceOverride
ami2DSClearViewOverrideProperties | McadFolder.ClearOverrideProperties
ami2DSGetViewBasePoint | McadFolder.get_BasePoint
ami2DSSetViewBasePoint | McadFolder.put_BasePoint
ami2DSGetCompInView | McadComponentView.get_Component
ami2DSIsCompViewFeature | McadComponentView.get_isFeature
ami2DSViewIsGhost | McadComponentView.IsGhostView
ami2DSSetHideName/ami2DSSetCpxHideName ami2DSGetHideName/ami2DSGetCpxHideName | McadHideSituation.Name McadComplexHideSituation.Name
ami2DSSetHideSysName ami2DSSetCpxHideSysName ami2DSGetHideSysName ami2DSGetCpxHideSysName | McadHideSituation.SysName McadComplexHideSituation.SysName
ami2DSSetHideDefinition ami2DSSetCpxHideDefinition ami2DSGetHideDefinition ami2DSGetCpxHideDefinition | McadHideSituation.Definition McadComplexHideSituation.Definition
ami2DSSetHideSuppressed ami2DSSetCpxHideSuppressed ami2DSIsHideSuppressed ami2DSIsCpxHideSuppressed | McadHideSituation.Suppressed McadComplexHideSituation.Suppressed
ami2DSSetHideConcealed ami2DSSetCpxHideSuppressed ami2DSIsHideConcealed ami2DSIsCpxHideConcealed | McadHideSituation.Concealed McadComplexHideSituation.Concealed
ami2DSIsStdPartHide ami2DSIsStdPartCpxHide | McadHideSituation.IsStandardPartHide McadComplexHideSituation.IsStandardPartHide
ami2DSIsModifiedStdPartHide ami2DSIsModifiedStdPartCpxHide | McadHideSituation.IsModifiedStandardPartHide McadComplexHideSituation.IsModifiedStandardPartHide
ami2DSIsHideMigrated | McadHideSituation.IsMigrated
ami2DSIsHideComplexHideLevel | McadHideSituation.IsComplexHideLevel
ami2DSGetHideSubents | McadHideSituation.Subents
ami2DSAddHideSubent | McadHideSituation.AddSubent
ami2DSAddHideSubents | McadHideSituation.AddSubents
ami2DSRemoveHideSubent | McadHideSituation.RemoveSubent
ami2DSRemoveHideSubentByIdx | McadHideSituation.RemoveSubentByIdx
ami2DSClearHideSubents | McadHideSituation.ClearSubents
ami2DSAddHideMSSubent | McadHideSituation.AddMSSubent
ami2DSAddHideMSSubents | McadHideSituation.AddMSSubents
ami2DSSetHideIgnoreFgExclude ami2DSGetHideIgnoreFgExclude | McadHideSituation.IgnoreFgExclude
ami2DSSetHideIgnoreBgExclude ami2DSGetHideIgnoreBgExclude | McadHideSituation.IgnoreBgExclude
ami2DSSetHideIgnoreUpperBgExclude ami2DSGetHideIgnoreUpperBgExclude | McadHideSituation.IgnoreUpperBgExclude
ami2DSSetHideFgSelectionName ami2DSGetHideFgSelectionName | McadHideSituation.FgSelectionName
ami2DSSetHideBgSelectionName ami2DSGetHideBgSelectionName | McadHideSituation.BgSelectionName
ami2DSSetHideHiddenLinesInvisible ami2DSSetCpxHideHiddenLinesInvisible ami2DSGetHideHiddenLinesInvisible ami2DSGetCpxHideHiddenLinesInvisible | McadHideSituation.HiddenLinesInvisible McadComplexHideSituation.HiddenLinesInvisible
ami2DSSetHideAppropriateObjectsOnly ami2DSSetCpxHideAppropriateObjectsOnly ami2DSGetHideAppropriateObjectsOnly ami2DSGetCpxHideAppropriateObjectsOnly | McadHideSituation.HideAppropriateObjectsOnly McadComplexHideSituation.HideAppropriateObjectsOnly
ami2DSSetHideOuterContourOnly ami2DSGetHideOuterContourOnly | McadHideSituation.OuterContourOnly
ami2DSSetHideSaveSimplifiedOuterContour ami2DSGetHideSaveSimplifiedOuterContour | McadHideSituation.SaveSimplifiedOuterContour
ami2DSSetHideInverseForeground ami2DSGetHideInverseForeground | McadHideSituation.InverseForeground
ami2DSSetHideContoursOnlyInForeground ami2DSGetHideContoursOnlyInForeground | McadHideSituation.ContoursOnlyInForeground
ami2DSHideAutoSelectBackground | McadHideSituation.AutoSelectBackground
ami2DSHideSwapFgAndBg | McadHideSituation.SwapFgAndBg
ami2DSGetHideParentHide | McadHideSituation.ParentHide
ami2DSGetHideLevelIndex | McadHideSituation.LevelIndex
ami2DSIsHideLastLevel | McadHideSituation.IsLastLevel
ami2DSGetCpxHideLevelIndex | McadComplexHideSituation.LevelCount
ami2DSGetLevelCpxHideSituations | McadComplexHideSituation.HideSituations
ami2DSInitCpxHide | McadComplexHideSituation.InitFromHide
ami2DSCpxHideAddLevel | McadComplexHideSituation.AddLevel
ami2DSCpxHideRemoveLevel | McadComplexHideSituation.RemoveLevel
ami2DSCpxHideRemoveLevelByIdx | McadComplexHideSituation.RemoveLevelByIdx
ami2DSCpxHideMoveLevel | McadComplexHideSituation.MoveLevel
ami2DSCpxHideReverseLevels | McadComplexHideSituation.Reverse
ami2DSCpxHideLookupLevelName | McadComplexHideSituation.LookupLevelName
ami2DSCpxHideNextLevelName | McadComplexHideSituation.NextLevelName
ami2DSCpxHideUpdateBgSelection | McadComplexHideSituation.UpdateBgSelection
ami2DSExplodeCpxHide | McadComplexHideSituation.Explode
amiFEGetFormulaEvaluator | AcadmApplication.GetFormulaEvaluator
amiFESetAttributeDataProvider | McadFormulaEvaluator.SetDataProvider
amiFEExistAttribute | McadFormulaEvaluator.Exist
amiFEIsAttributeEditable | McadFormulaEvaluator.IsEditable
amiFESetAttributeData | McadFormulaEvaluator.SetData
amiFEGetAttributeData | McadFormulaEvaluator.GetData
amiFEGetAllAttributeData | McadFormulaEvaluator.GetAllAttribsData
amiFEGetAllValuesOfAttribute | McadFormulaEvaluator.GetAllAttribValues
amiFEAttributeArray | McadFormulaEvaluator.GetAllAttribs
amiFEvaluate | McadFormulaEvaluator.Evaluate


Using the API - Best Practices
Using the API - Best Practices

Setting the active target

Avoid using the API ami2DSSetEditTarget to set the active target, and then edit or modify the contents of the active target. There may be some issues with setting the active target in your application. If you use this API, ensure that you use ami2DSUpdateEntities to update the active component view or folder with the entity changes.

Instead of this API, you should use the APIs ami2DSAddEntitiesToView, ami2DSRemoveViewEntities and ami2DSGetViewEntities for editing or modifying the contents of a component view or folder.

AmiObjectKey, McadObject, and closing documents

When you use the API to create a new AmiObjectKey (e.g. ami2DSCreateCompViewDef) and then close document in the same function, you need to delete the AmiObjectKey (i.e. AmiObjectKey::release()) at the end of your function, before closing the document.

Similarly, in an application which uses COM Automation, when you create a new McadObject (e.g. McadComponentViewDefintion) and then close the document in the same function, you need to set McadComponentViewDefintion to Nothing before calling the AcadDocument.Close method.

Ensuring Mechanical Structure Integrity

If your application is using the AutoCAD API to modify the entities which belong to component views and folders in the Mechanical Structure, such as calling the AcGeEntity2d::mirror function, then add SET_STRUCTURE_MODE_EDIT_ENTITY macro to the beginning of the outer-most function. This macro is used to set the editor state to the structure entity edit mode. When the structure entity edit mode is turned on, any modification to entities which belong to a component view or folder will be tracked for the updating of Mechanical Structure. This macro will turn off the structure entity edit mode at the end of the outer-most user function.

Similarly in applications which use COM Automation, if your application is modifying the entities which belong to component views and folders in Mechanical Structure, such as calling the AcadLine.Mirror method, then you have to set AcadmApplication.StructureModeEditEntity property to True at the beginning of the outer-most function. This will set the editor state to the structure entity edit mode. At the end of this outer-most function, you have to set AcadmApplication.StructureModeEditEntity to False to turn off the structure entity edit mode.

Transactions

A new Transaction object has been added, available through Mcad2DStructureMgr.StartTransaction. This object has no methods or properties (except to obtain the parent application object). Its purpose is to allow the developer to control when changes will be reflected in the 2D mechanical structure. Some operations benefit from improved performance, while others also benefit from less unnecessary activity on the screen. A good example is use of the Hide Situations API. It is good practice to create a transaction object prior to possibly lengthy hidden line calculations. Once the work is done, set the transaction object to Null, or let it go out of scope, to force an update of 2D mechanical structure.


Topics
2D Mechanical Structure
Topics
Name | Description
2D Mechanical Structure Sample Code | 2D Mechanical Structure Sample Code This simple example uses the API to perform a similar task to that shown in Figure 1. We'll create an object in AutoCAD Mechanical, and then add it as a component to the mechanical structure, complete with a component view.
2D Mechanical Structure Sample Code Detailed Explanation |


Topics
API Overviews and VBA Sample Code
Topics
Name | Description
2D Mechanical Structure |
XREFs and 2D Mechanical Structure |
Attaching Data to Mechanical Structure |
Structure Migration |
Bill of Materials (BOM) |
Data Provider |
Hide Situation |
Parts Lists and Balloons |
Revision Line |
Section Line |
Symbols |
Titles and Borders |
Sample Code Disclaimer | The sample code provided in this Help system and in the AutoCAD Mechanical Software Developers Kit is intended as an aid for learning application development techniques for AutoCAD Mechanical and as such is provided "as-is". The sample code is covered by the relevant sections of the Autodesk AutoCAD Mechanical license agreement, repeated below.


Topics
Attaching Data to Mechanical Structure
Topics
Name | Description
Attaching Data to Mechanical Structure, Code Sample 1 |
Attaching Data to Mechanical Structure, Code Sample 2 |
Attaching Data to Mechanical Structure Sample Code Detailed Explanation |


Topics
Bill of Materials (BOM)
Topics
Name | Description
BOM Sample Code 1 |
BOM Sample Code 1 Detailed Explanation |
BOM Sample Code 2 |
BOM Sample Code 2 Detailed Explanation |


Topics
Data Provider
Topics
Name | Description
Data Provider Sample Code |
Data Provider Sample Code Detailed Explanation |


Topics
Getting Started with the C++ API
Topics
Name | Description
Your First AutoCAD Mechanical C++ Application |
Adding a New Command to AutoCAD Mechanical |
Adding AutoCAD Mechanical C++ API Code |
Compiling and Running |
What Does it Do? |
Sample Code |
Additional Information |


Topics
Hide Situation
Topics
Name | Description
Hide Situation Sample Code 1 |
Hide Situation Sample Code 1 Detailed Explanation |
Hide Situation Sample Code 2 |
Hide Situation Sample Code 2 Detailed Explanation |


Topics
Parts Lists and Balloons
Topics
Name | Description
Parts Lists and Balloons Sample Code |
Parts Lists and Balloons Sample Code Detailed Explanation |


Topics
Revision Line
Topics
Name | Description
Revision Line Sample Code | Revision Line Sample Code
Revision Line Sample Code Detailed Explanation |


Topics
Section Line
Topics
Name | Description
Section Line Sample Code |
Section Line Sample Code Detailed Explanation | Section Line Sample Code - Detailed Explanation This code sample manipulates several aspects of a section line. First, it creates the variable sectionLine and makes it a pointer to a custom McadSectionLine object.


Topics
Structure Migration
Topics
Name | Description
Structure Migration Sample Code |
Structure Migration Sample Code Detailed Explanation |


Topics
Symbols
Topics
Name | Description
Symbols Sample Code - Adding a Feature Control Frame Symbol |
Symbols Sample Code - Adding a Datum Target Symbol |
Symbols Sample Code - Adding a Surface Texture Symbol |
Symbols Sample Code - Adding a Welding Symbol |
Symbols Sample Code - Adding an Edge Symbol |
Symbols Sample Code - Adding a Taper and Slope Symbol |
Symbols Sample Code - Adding a Note Symbol |
Symbols Sample Code - Adding a Detail Symbol and Label |


Topics
Titles and Borders
Topics
Name | Description
Titles and Borders Sample Code 1 |
Titles and Borders Sample Code 1 - Detailed Explanation |
Titles and Borders Sample Code 2 |
Titles and Borders Sample Code 2 Detailed Explanation |


Topics
XREFs and 2D Mechanical Structure
Topics
Name | Description
XREFs and 2D Mechanical Structure Sample Code |
XREFs and 2D Mechanical Structure Sample Code Detailed Explanation |


Contents
Introduction
Who Should Read this Guide
Opening the VBA IDE
Configuring the VBA IDE
API Overviews and VBA Sample Code
2D Mechanical Structure
2D Mechanical Structure Sample Code
2D Mechanical Structure Sample Code Detailed Explanation
XREFs and 2D Mechanical Structure
XREFs and 2D Mechanical Structure Sample Code
XREFs and 2D Mechanical Structure Sample Code Detailed Explanation
Attaching Data to Mechanical Structure
Attaching Data to Mechanical Structure, Code Sample 1
Attaching Data to Mechanical Structure, Code Sample 2
Attaching Data to Mechanical Structure Sample Code Detailed Explanation
Structure Migration
Structure Migration Sample Code
Structure Migration Sample Code Detailed Explanation
Bill of Materials (BOM)
BOM Sample Code 1
BOM Sample Code 1 Detailed Explanation
BOM Sample Code 2
BOM Sample Code 2 Detailed Explanation
Data Provider
Data Provider Sample Code
Data Provider Sample Code Detailed Explanation
Hide Situation
Hide Situation Sample Code 1
Hide Situation Sample Code 1 Detailed Explanation
Hide Situation Sample Code 2
Hide Situation Sample Code 2 Detailed Explanation
Parts Lists and Balloons
Parts Lists and Balloons Sample Code
Parts Lists and Balloons Sample Code Detailed Explanation
Revision Line
Revision Line Sample Code
Revision Line Sample Code Detailed Explanation
Section Line
Section Line Sample Code
Section Line Sample Code Detailed Explanation
Symbols
Symbols Sample Code - Adding a Feature Control Frame Symbol
Symbols Sample Code - Adding a Datum Target Symbol
Symbols Sample Code - Adding a Surface Texture Symbol
Symbols Sample Code - Adding a Welding Symbol
Symbols Sample Code - Adding an Edge Symbol
Symbols Sample Code - Adding a Taper and Slope Symbol
Symbols Sample Code - Adding a Note Symbol
Symbols Sample Code - Adding a Detail Symbol and Label
Titles and Borders
Titles and Borders Sample Code 1
Titles and Borders Sample Code 1 - Detailed Explanation
Titles and Borders Sample Code 2
Titles and Borders Sample Code 2 Detailed Explanation
Sample Code Disclaimer
Comparing the VBA IDE Operation in 32-bit and 64-bit Environments
Getting Started with the C++ API
Your First AutoCAD Mechanical C++ Application
Adding a New Command to AutoCAD Mechanical
Adding AutoCAD Mechanical C++ API Code
Compiling and Running
What Does it Do?
Sample Code
Additional Information
Comparing the COM and C++ APIs
Using the API - Best Practices


Index
2 | A | B | C | D | G | H | I | O | P | R | S | T | U | W | X | Y
2
2D Mechanical Structure
2D Mechanical Structure Sample Code
2D Mechanical Structure Sample Code Detailed Explanation
A
Adding a New Command to AutoCAD Mechanical
Adding AutoCAD Mechanical C++ API Code
Additional Information
API Overviews and VBA Sample Code
Attaching Data to Mechanical Structure
Attaching Data to Mechanical Structure Sample Code Detailed Explanation
Attaching Data to Mechanical Structure, Code Sample 1
Attaching Data to Mechanical Structure, Code Sample 2
Autodesk AutoCAD Mechanical Developer's Guide
B
Bill of Materials (BOM)
BOM Sample Code 1
BOM Sample Code 1 Detailed Explanation
BOM Sample Code 2
BOM Sample Code 2 Detailed Explanation
C
Comparing the COM and C++ APIs
Comparing the VBA IDE Operation in 32-bit and 64-bit Environments
Compiling and Running
Configuring the VBA IDE
D
Data Provider
Data Provider Sample Code
Data Provider Sample Code Detailed Explanation
G
Getting Started with the C++ API
H
Hide Situation
Hide Situation Sample Code 1
Hide Situation Sample Code 1 Detailed Explanation
Hide Situation Sample Code 2
Hide Situation Sample Code 2 Detailed Explanation
I
Introduction
O
Opening the VBA IDE
P
Parts Lists and Balloons
Parts Lists and Balloons Sample Code
Parts Lists and Balloons Sample Code Detailed Explanation
R
Revision Line
Revision Line Sample Code
Revision Line Sample Code Detailed Explanation
S
Sample Code
Sample Code Disclaimer
Section Line
Section Line Sample Code
Section Line Sample Code Detailed Explanation
Structure Migration
Structure Migration Sample Code
Structure Migration Sample Code Detailed Explanation
Symbols
Symbols Sample Code - Adding a Datum Target Symbol
Symbols Sample Code - Adding a Detail Symbol and Label
Symbols Sample Code - Adding a Feature Control Frame Symbol
Symbols Sample Code - Adding a Note Symbol
Symbols Sample Code - Adding a Surface Texture Symbol
Symbols Sample Code - Adding a Taper and Slope Symbol
Symbols Sample Code - Adding a Welding Symbol
Symbols Sample Code - Adding an Edge Symbol
T
Titles and Borders
Titles and Borders Sample Code 1
Titles and Borders Sample Code 1 - Detailed Explanation
Titles and Borders Sample Code 2
Titles and Borders Sample Code 2 Detailed Explanation
U
Using the API - Best Practices
W
Web Resources
What Does it Do?
Who Should Read this Guide
X
XREFs and 2D Mechanical Structure
XREFs and 2D Mechanical Structure Sample Code
XREFs and 2D Mechanical Structure Sample Code Detailed Explanation
Y
Your First AutoCAD Mechanical C++ Application


Autodesk AutoCAD Mechanical Developer's Guide
Topics for new users
  • Introduction
  • Who Should Read this Guide
  • Opening the VBA IDE
  • Configuring the VBA IDE
  • Using the API - Best Practices

Topics for users with experience in AutoCAD and VBA
  • API Overviews and VBA Sample Code
  • Comparing the VBA IDE Operation in 32-bit and 64-bit Environments
  • Comparing the COM and C++ APIs
  • Getting Started with the C++ API

Online resources
  • Autodesk Customer Service
  • AutoCAD Mechanical Discussion Groups
  • Autodesk Community
  • Autodesk Blogs
  • AUGI


Web Resources
  • Autodesk Customer Service
  • AutoCAD Mechanical Discussion Groups
  • Autodesk Community
  • Autodesk Blogs
  • AUGI