AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX...

59
The ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications. This guide describes the concept of exposing objects through an ActiveX interface and programming those objects using various languages including the Visual Basic for Applications programming environment. The section “Getting Started” covers the example code found in the help reference and the sample applications that are installed with the ActiveX Object Model. Refer to the section “Understanding the ActiveX Object Model” for specific information on features of AutoCAD Land Desktop that can be accessed through the ActiveX Object Model. In the section “Programming Guidelines” there are tips and recommendations for developing applications using various programming languages and development environments. If you are new to the Visual Basic for Applications programming environment or AutoCAD ActiveX technology, please refer to the AutoCAD ActiveX and VBA Developer's Guide before using this guide. Topics in this Section: Referencing the Automation Type Libraries Running the Example Code in this Guide Reviewing the Sample Applications Getting Started Introduction

Transcript of AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX...

Page 1: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

TheActiveXObjectModelforAutoCADLandDesktopisanActiveXandVBAinterfacethatenablesdeveloperstocreatedynamicandpowerfulapplications.ThisguidedescribestheconceptofexposingobjectsthroughanActiveXinterfaceandprogrammingthoseobjectsusingvariouslanguagesincludingtheVisualBasicforApplicationsprogrammingenvironment.

Thesection“GettingStarted”coverstheexamplecodefoundinthehelpreferenceandthesampleapplicationsthatareinstalledwiththeActiveXObjectModel.Refertothesection“UnderstandingtheActiveXObjectModel”forspecificinformationonfeaturesofAutoCADLandDesktopthatcanbeaccessedthroughtheActiveXObjectModel.Inthesection“ProgrammingGuidelines”therearetipsandrecommendationsfordevelopingapplicationsusingvariousprogramminglanguagesanddevelopmentenvironments.

IfyouarenewtotheVisualBasicforApplicationsprogrammingenvironmentorAutoCADActiveXtechnology,pleaserefertotheAutoCADActiveXandVBADeveloper'sGuidebeforeusingthisguide.

TopicsinthisSection:

ReferencingtheAutomationTypeLibraries

RunningtheExampleCodeinthisGuideReviewingtheSampleApplications

GettingStartedIntroduction

Page 2: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

WheneveranewAutoCADLandDesktopprojectiscreated,thesupportingtypelibrariesmustbereferenced.AutoCADLandDesktoprequiresreferencetothreetypelibrariesbeforeanycodingbegins.Thethreetypelibrariesare:

AECBase4.0ApplicationLibrary(AecXUiBase40.tlb)AECBase4.0ObjectLibrary(AecXBase40.tlb)AutodeskLand4.0TypeLibrary

TheselibrariesprovideaccesstoalltheAutoCADLandDesktopObjects,Properties,Methods,andEvents.TheVBAIDEReferencesdialogallowsyoutosetthetypelibrariesforuse.

ToopentheReferencesdialogbox1. FromtheToolsmenu,chooseReferences.2. ScrollthroughthelistandchecktherequiredAutoCADLand

Desktoptypelibraries.3. ClickOK.

ReferencingtheAutomationTypeLibraries

Page 3: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

AlloftheexamplecodeintheReferencecanbecopiedfromthehelpfiles,pasteddirectlyintotheAutoCADVBAenvironment,andthenexecutedwiththefollowingrequirements:

ThecurrentactivedrawinginAutoCADmustbeadrawingcreatedwithAutoCADLandDesktopopentomodelspace.

Theactiveprojectmustcontainobjectsordatathattheexampleistryingtoaccessforuse.Inordertoprovideclearandsimpleexamples,alltheexamplesprovidedinthereferenceassumethattheBasePointandNorthRotationisthesameastheAutoCADWorldcoordinatesystemusingthedefaultXandYsettings.IfyouuseanyoftheexamplesinyourowncodemakesureyoutestforBasePointandNorthRotationandprovideappropriateconversionwhennecessary.SomeexamplescontainuserinputmethodssuchasUtility.GetPoint,whichcanbecalledfromamacro,butcannotbecalledfromamodaldialog.

Toruntheexamples

1. CopytheexamplefromthehelpfileintoanemptyVBAcodemodule.

2. AddareferencetotheAECBaseApplication,AECBaseObject,andAutoCADLandTypeLibraries.

3. VerifythatAutoCADhasanAutoCADLandDesktopdrawingopentomodelspace.

4. Verifythattheactiveprojecthasdatafortheexampletoworkwith.5. OpentheMacrosdialogboxbyenteringthecommandVBARUN.6. ChoosethemacroandpressRun.

NOTE:TheexamplesareprovidedtosimplyshowhowaspecificObject,Property,Method,orEventcanbeused.Noprovisionsforerrortrappingareprovided.Codeoptimization,formatorlogichavebeenkeptsimple,andtoaminimum,forthesakeofclarity.

RunningtheExampleCode

Page 4: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

TheAutoCADLandDesktopActiveXandVBAActiveXObjectModelcomeswithseveralsamplesthatdemonstratehowtocreateyourownutilitiesandextensionstoAutoCADLandDesktop.Wehaveprovidedsamplesforeachofthemostcommondevelopmentenvironments:

VisualBasicforApplications

ProjectFindPointGroupFncsPointGroupReportDraw3dSurfaceAlignmentUtilitiesDrapeLinePointGroupTableParcelAreaDrawCrossSection

VisualBasic

LockWatcher

VisualLisp

CogoPoints

ObjectARX

AeccNewPointGroupPointExport

VisualC++

EventLogger,

Thislistingprovidesthename,description,andlocationofthemainsourcecodefileforeachsampleapplication.Manysampleapplicationshavesupportfilesthatcanbefoundinthesamedirectoryasthemain

ReviewingtheSampleApplications

Page 5: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

sourcecodefile.

SampleApplications:

Sample\Land\Vba\ProjectFind.dvb

Description:VBAdialogforfindingAutoCADLandDesktopprojects.

Macros:

ProjectFind

Thismacrolaunchesamodaldialogthatyoucanusesearchforaprojectbasedonapathandfiltersusingwildcards,andoptionallyloadadrawingfromthatprojectintoAutoCADLandDesktop.

Sample\Land\Vba\PointGroupFncs.dvb

Description:VBAfunctionstomodifyPointGroups.

Macros:

AddPointsToGroupThismacroaddsapointlisttotheselectedPointGroup.ThepointlistcanberetrievedfromanAutoCADdrawingortypedin.

CreateGroupByDesc

Thismacrodisplaysalistofalluniquepointdescriptions.YoucanthencreateanewPointGroupbasedonthatuniquedescription.ThenthemacroaddsallpointswiththatdescriptiontothatnewPointGroup.

DisplayGroupsByPoint

GivenaPointnumber,themacrodisplaysallpointgroupsthatcontainthatPointnumber.ThePointnumbercanbetypedorselectedfroman

Page 6: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

AutoCADdrawing.

Sample\Land\Vba\PointGroupReport.dot

Description:VBAmacrothatcreatesacustomPointGroupreport.

Macros:

PointGroupReportThismacrowillacceptcustomerdataandprintout:customerdata,projectstatistics,andmultiplePointGroups.

NOTE:Tousethewordtemplate,youmusthavetheAutoCADLandDesktoprunningandadrawingopenwithapointdatabasecreatedinitsproject.LocatethePointGroupReport.dotwithExploreranddoubleclickonthefilename.ThiswillopenWordandbeginanewdocumentusingPointGroupReport.dotasthetemplate.FromtheToolsmenuopentheMacrosdialogandselectthemacronamedPointGroupReport.SelecttheRunbuttontodisplaythePointGroupDisplayDialog.Thisdialogcreatesaclientdatasectionandapointtablelistingforeachselectedpointgroup.

ToeditthismacrousetheVisualBasicEditorfromtheMacroselectionoftheToolsmenuinMicrosoftWord.

Sample\Land\Vba\Draw3dSurface.dvb

Description:VBAdialogfordrawingaSurfaceas3dFaces.

Macros:

DrawSurface

ThismacrolaunchesamodaldialogthatyoucanusetoselectaSurfaceandthendrawallvisibleSurfaceFacesasAutoCAD3dFaces.Alldrawingisdoneonthecurrent

Page 7: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

drawingsurface.

Sample\Land\Vba\AlignmentUtilities.dvb

Description:VBAdialogformakingacopyofanalignmentinthealignmentdatabase.

Macros:

CopyAlignment

Thismacrolaunchesamodaldialogthatyoucanusetoselectanalignmentandthenmakeacopyofthatalignment.ThealignmentisnotdrawninthecurrentAutoCADdrawing.

Sample\Land\Vba\DrapeLine.dvb

Description:VBAdialogforprojectinganalignmenttoasurface,anddrawingtheresultasasetoflines.

Macros:

DrapeLineThismacrolaunchesamodaldialogthatletstheuserselectanalignmentandasurface,anddrapeaprojectedseriesoflineentitiesontothesurfaceonthecurrentlayer.

Sample\Land\Vba\PointGroupTable.dvb

Description:VBAdialogforaddingapointtabletothedrawing.

Macros:

Page 8: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

PointGroupTable

Thismacrolaunchesamodaldialogthatallowstheusertoselectapointgroup,andinsertsatableonthecurrentlayerthatidentifiespointnumber,eastings,northingsandelevations.

Sample\Land\Vba\ParcelArea.dvb

Description:VBAdialogfordisplayingthetotalareaofasetofparcels.

Macros:

ParcelAreaThismacrolaunchesamodaldialogthatallowstheusertoselectoneormoreparcels,anddisplaysthetotalareaintheproperunits.

Sample\Land\Vba\DrawCrossSection.dvb

Description:VBAutilityfordrawingacrosssectionofthefirststationofthecurrentalignment.

Macros:

DrawCrossSection

ThismacrowilldrawingacrosssectioninModelSpaceusingaverticalscalefactorof10.ItimportstheCrossSectionblock,andthendraftseachcrosssectionsurfacesasalightweightpolyline.Thecodedemonstrateshowtoprocesstherightandleftsidesofthesurfacesproperly.

Sample\Land\ActiveX\LockWatcher

Page 9: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

Description:AVBapplicationformonitoringmulti-userlocksforaproject.

NOTE:TheVBsampleLockWatcherwasdevelopedusingVisualBasicversion5.0.ItisalsocompatiblewithVB4-32andVB6.

Sample\Land\VLisp\CogoPoints.lsp

Description:VariousVisualLispfunctionstoaccesstheProjectandCogointerfaces.ThislispfileisusefulforlearningthesyntaxofActiveXandVLisp.

Functions:

loadAecProjLoadstheAutoCAD,Aecc.Application,andtheActiveProjectinterfaces.Thisroutinemustberunbeforeallotherfunctions.

cleanup Releasesallglobalinterfaces.

ProjectStats Displaystheactiveproject'sproperties.

PointGroups ListsthepointgroupnamesusingtheItem()method.

PointGroups2 ListsthepointgroupnamesusingEnumeration.

addCgPoint AddsanewCogoPoint.

Sample\Land\Arx\AeccNew

Description:ThisARXprovidesthecommandlineequivalentsofthe

Page 10: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

NewandOpendialogs.ItdemonstratestheuseoftheACRX_CMD_SESSIONandACRX_CMD_NOINTERNALLOCKflagsforregisteredcommandsthatusetheDocument.NewProjectBasedandDocument.OpenProjectBasedActiveXmethods.

NOTE:Youmustmodifyprojectsettingsfortheincludeddirectoriesandthelibrarytomatchyoursystem.Thelocationsofthefollowingtypelibrariesmustalsobemodifiedinstdafx.h:acad.tlb,aecxbase.tlb,aecxuibase.tlbandlandauto.tlb.

Functions:

aeccnew Thispromptsyouforargumentsandcreatesanewproject/drawing.

aeccopen Thispromptsyouforargumentsandopensanexistingproject/drawing.

Sample\LandArx\PointGroup

Description:Thisapplicationdisplaysthecurrentlydefinedpointgroupsanddisplaysthepointsforanexistingpointgroup.

NOTE:Youmustmodifyprojectsettingsfortheincludeddirectoriesandthelibrarypathstomatchyoursystem.Thelocationsofthefollowingtypelibrariesmustalsobemodifiedinstdafx.h:acad.tlb,aecxbase.tlb,aecxuibase.tlbandlandauto.tlb.

Functions:

c:pointgroup ListsroutinesforPointGroup.arx.

c:listpointgroups Listsallpointgroupsforthecurrentproject.

Page 11: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

listgrouppoints Givesapointgroupname,willlistallofthepoints.

Sample\Land\Arx\PointExport

Description:ApplicationwillexportallCogopointsintoanASCIIfile.

NOTE:Youmustmodifyprojectsettingsfortheincludeddirectoriesandthelibrarypathstomatchyoursystem.Thelocationsofthefollowingtypelibrariesmustalsobemodifiedinstdafx.h:acad.tlb,aecxbase.tlb,aecxuibase.tlbandlandauto.tlb.

Functions:

pointexport ExportsallCogopointstoanASCIIfile.

Sample\Land\ActiveX\EventLogger

Description:AC++applicationformonitoringalignmentevents.

Thissampleapplicationdisplaysadialogwithalistboxthatrecordsallalignmentevents(whenanalignmentorstationequationiswrittentothedatabase).ThesampledemonstrateshowtoimplementaneventsinkinaCOMobjectusingMFCandATL.

Page 12: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

TheActiveXObjectModelforAutoCADLandDesktopexposesfeaturesandprovidesaccesstoprojectdatathroughanobjecthierarchy.Thishierarchyprovidesaconvenientandconsistentprogramminginterfacetoyourprojects.

Theobjecthierarchycanbegroupedintothefollowingcategories:

AlignmentsPlanalignmentscanbedefinedfromtangent,curve,andspiralobjects.YoucanalsomanageStationEquations.

ProjectManagementThisincludesextensionstotheAutoCADobjectmodelsothatyoucanmanageLandDesktopProjects.ItalsoprovidesaccesstoPreferencesandProjectPrototypes.

COMWrappersforARXObjectsTheseareprovidedforthePoint,Contour,andCurveTextARXobjectsthatresideinyourdrawings.Youcanmodifyexistingobjects,oraddanddeleteobjectsfromthedrawing.Inaddition,programmaticaccesstotheContourStyledictionaryobjectisprovidedsothatyoucanmanagetheappearanceofContourobjects.

CoordinateGeometryTheseobjectsallowyoutomanageyourCogoPointdatabase,PointGroups,andDescriptionKeys.

SurfacesTerrainmanagementisexposedthroughacollectionofsurfacesthathaveinputsandgeneratedoutputs.YoucandefineasurfacefromPointFiles,PointGroups,Boundaries,Breaklines,Contourdata,orDEMFiles.Youcanbuildasurfaceandawatershedmodel.ThegeneratedTinPoints,Edges,FacesandElevationContoursareprovidedasoutputs.

UnderstandingTheActiveXObjectModelIntroduction

Page 13: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

ParcelsParcelobjectscanbedefinedfromlineandcurveobjects.Propertiessuchasarea,perimeter,centroid,andnamecanalsobeaccessed.

Profiles,CrossSections,andSuperelevationsTheActiveXObjectmodelprovidesaccesstoprofiles,crosssections,andsuperelevations.Youcanalsoaccesstheprofilesandcrosssectionblocksinthedrawingforcustomdrafting.

TopicsinthisSection:

TheBigPictureProjectManagementAlignmentsSurfacesCogoPointsProfilesCrossSectionsandSuperelevationsParcelsCOMWrappers

Page 14: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

ActiveXObjectModelTheActiveXObjectModelisaninterfaceintotheAutoCADLandDesktopproduct.ItisnotareplacementforAutoCAD'sActiveXinterfacebutisanextensionofthatinterface.

ThroughtheActiveXObjectModelyoucancreateandedityourprojectdata.ThroughAutoCADActiveX,youcancreateandmodifydrawingentities.Thereisverylittleoverlapbetweenthetwo.TheActiveXObjectModelprovidesverylittledrawinginteraction.TheActiveXObjectModelhasnouserinterface.AutoCADActiveXprovidesthese(andothers)features.UsingAutoCADActiveXyoucandrawandeditAutoCADentities,aswellasprompttheuserforentityselectionorcreation.

ByusingboththeActiveXObjectModelandtheAutoCADActiveXinterface,youcaneasilycustomizeAutoCADLandDesktopforyourbusiness.

ActiveXObjectModelVersionsWhendesigningyourapplications,youcandetectwhatversionoftheActiveXObjectModelisinstalled,andbehaveappropriatelyaccordingtotheavailablefeatures.IfyouareusingActiveXAutomation(usingIDispatchmethodssuchasInvokeandGetIdsOfNames),youcantrytoaccessanewfeaturewiththeappropriateerrorhandling(onerrorhandler,try-catchblock,etc.).However,ifyouarecreatingcompiledapplications(vtablebinding),youmustchecktheprogramIDsthatareregisteredfortheapplicationobject:

Subversion()DimappAsAeccApplicationDimversion2AsBooleanDimversion4AsBooleanversion2=Falseversion4=False

TheBigPicture

Page 15: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

Check1:OnErrorGoToCheck2Setapp=ThisDrawing.Application.GetInterfaceObject("Aecc.Application.2")version2=TrueCheck2:OnErrorGoToDoneSetapp=ThisDrawing.Application.GetInterfaceObject("Aecc.Application.4")version4=TrueDone:Ifversion4ThenDebug.PrintvbCrLf&"LandDesktop2007functionalityisavailable."ElseIfversion2ThenDebug.PrintvbCrLf&"LandDesktop2ifunctionalityisavailable."&_"Donottrytoinvoke2007featuresonthisdesktop."ElseDebug.PrintvbCrLf&"NoActiveXfunctionalityforLandDesktopisavailable."EndIfEndSub

LoadingCivilEngineeringFeaturesToaccesscivlengineeringfeatures,suchasAlignmentProfiles,CrossSectionsandSuperelevations,youmusthaveAutoCADCivil3DLandDesktopCompanion2009running.The"AutoCADCivil3DLandDesktopCompanion2009"versionofLandDesktophasthecivilengineeringandsurveyfeaturesincluded.TheversionofLandDesktopnamed"AutoCADLandDesktop2009",sometimesreferredtoasthestand-aloneversionofLandDesktop,doesnothavethecivilengineeringandsurveyfeaturesinstalled.YoumaygetanerrorcodeAECC_E_CIVIL_NOT_LOADED(ormessage"CivilDesktop\civilengineeringfeatureshas\havenotbeenloaded.")whenyoutrytoaccessprofileobjectsontheversionofLandDesktopthatdoesnotcontaincivil

Page 16: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

engineeringfeatures("AutoCADLandDesktop2009").

IfyouhaveAutoCADCivil3DLandDesktopCompanion2009installed,thecivilengineeringfeaturesareautomaticallyloaded.

DataValidationTheAutoCADLandDesktopproductgetsinputthroughmenus,dialogs,commandlineinput,andthepointerdevice.Inmostcasestheprogramvalidatesthisinputbeforesendingthedatatothefunctions.TheActiveXObjectModelexposestheprogramsfunctions,bypassingtheAutoCADLandDesktopinterface.WhenusingTheActiveXObjectModel,youareresponsiblefortheinterface.ThemethodusedforcollectingandvalidatingthedataiscriticaltothedesignofanyprogramwrittenforusewiththeActiveXObjectModel.ProvidingincorrectdatatotheMethodsorPropertiesprovidedintheActiveXObjectModelcanresultininvalidresultsandincorrectdataintheprojectsdatabases.

ProjectsandDrawingsAutoCADLandDesktopisproject-based.ThemajorityofdataforaprojectisstoredexternallyfromanAutoCADdrawing.ThisincludesCOGOpoints,surfaces,andalignments.ADrawingisconsideredpartofthatprojectdata.Adrawingisassociatedwithoneproject.However,aprojectcanhavemultipledrawingsassociatedwithit.Adrawingisaviewintotheprojectdata.Becauseyoucanhavemultipledrawingsassociatedwithaproject,youcanhavemultipleviewsoftheproject.Inonedrawing,youmighthavealloftheCOGOpoints.Inanotherdrawing,thealignmentsmightbedisplayed.Thenumberofproject-baseddrawingsandtheircontentisuptotheenduser.However,alldataendsupasprojectdata.

Thisideaofbeingproject-basediscentraltoAutoCADLandDesktop,andtheActiveXObjectModelisbasedonit.

DrawingsandDocumentsAProjectcanhavemultipleAutoCADdrawingsassociatedwithit.TheDrawingscollectionisthislistofAutoCADdrawings.Thislistisretrievedfromthe[Project]\dwgsdirectory.

Page 17: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

ADocumentisadrawingfileloadedintoAutoCADLandDesktop.Currently,theActiveXObjectModelonlysupportsoneDocumentbeingloadedatatime.ThisDocumentisderivedfromtheAutoCADActiveXDocumentandallmethodsaresupported.

RetrievingProjectInformationTheActiveXObjectModelcanonlyretrievedatafortheActiveProject.TheActiveProjectistheProjectassociatedwiththeDocumentthatiscurrentlyloaded.YoucangetalistofallProjects,thestatisticsforthoseProjects,andthedrawingsassociatedwiththoseProjects.YoucannotgetanyotherinformationfromthoseProjects.Forexample,youcannotgetalistofalignmentsorsurfacesforanon-activeProject.Inaddition,youcannothaveanactiveprojectifAutoCADLandDesktopisnotrunning.IfAutoCADLandDesktopisnotrunning,theActiveXObjectModelwillnotberunningandyoucannotgetanyinformationaboutprojectsordrawings.

Keepingthisinmind,usuallythefirstthingyoudoistogettheActiveProject.InVBA,toretrievetheActiveProject,do:

DimactiveProjAsAeccProjectSetactiveProj=AeccApplication.ActiveProject

ProjectNavigationFromtheProject,youcangetmostoftheLandprojectinformationthathasbeenexposedthroughtheActiveXObjectModel.TheObjectModeldiagramshowsthatfromtheProjectyouhavedirectaccesstoCogoPoints,PointGroups,DescriptionKeys,Surfaces,andAlignments.Inaddition,youhaveaccesstoalloftheProjectspecificsettingsandFileLocks.

CogoPoints,PointGroups,DescriptionKeys,Surfaces,andAlignmentsarecollections.Acollectionwillcontainzeroormoreobjects.Forexample,theSurfacescollectionwillcontainzeroormoreindividualsurfaces.Togetaccesstoanindividualmemberofacollection,useeithertheItemorEnumerationmethodsonthecollection.

Note:AllcollectionssupporttheItemandEnumerationmethods,andtheCountproperty.Notethatallcollectionsbeginwithanindexof0.Thisisa

Page 18: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

C++standard,andisusedconsistentlyacrossAutoCAD-basedActiveXimplementations.

Youcanqueryormodifytheobjectafteryouretrieveit.Deleteoraddoperationsalwaysexistatthecollectionlevel.Ifyouthinkaboutthis,itmakessense.Whenaddingordeleting,youarechangingthecollection.Alladditionsanddeletionstoacollectionwillreturnthenewobject.

What'sNextOk,sonowyouhavetheActiveProject,whatisthenextstep?First,youhavetofigureoutwhatyouwanttoaccomplishwithyourprogram.Let’stakeasimpleproblem:printoutthePointGroupnames.TheeasiestwaytousetheActiveXObjectModelistolookattheObjectModelandworkyourwaybackward.TheproblemistoprintoutsomeinformationonaPointGroup.IfweclickonthePointGroupintheDevelopersGuide,itwilldisplayallofthemethodsandpropertiesforthePointGroup.IntheDevelopersGuide,weseethatPointGrouphasapropertycalledGroupName.Thisiswhatwewanttoprintout.

Afterwehavefiguredoutwhatwewanttoprint,thenweworkourwayuptheObjectModeluntilwegettotheApplication.Bydoingthis,weseethatwehavetousethePointGroupscollection,theProjectobject,theProjectscollection,andfinallytheAeccApplication.ThesearetheobjectsneededtoprintoutthePointGroup.GroupName.IfwereversetheorderandstartattheAeccApplication,wecannowworkourwaybackdowntothePointGroup.ThisishowtogetPointGroupinformation.

YoucantraversetheObjectModelinthesamefashionforanyoftheobjectsorcollections.First,findwhatinformationandobjectyouneed,thenfollowtheObjectModeldowntothatobject.

OverviewofModulesProjects

FromProjects,youcangettoCogoPoints,PointGroups,DescriptionKeyFiles,Surfaces,Alignments,Parcels,CrossSectionsandSuperelevations.Inaddition,thePreferencesProject,FileLocks,andDrawingsareexposed.

Page 19: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

ThePreferencesProjectcontainstheCogo,Surface,Alignment,Parcel,Profile,andCrossSectionproperties.Thesepropertiesreturnobjectsthatexposesettingsforthoseareas.Allsettingsarefortheproject.

FileLocksisacollectionofallmulti-userlocksthatexistfortheproject.

Drawingcollectionisthelistofdrawingsfortheproject.

Cogo

CogoPoints,PointGroups,andDescriptionKeysareexposedthroughtheActiveXObjectModel.TheCogoPointisaCOGOpointthatexistsintheProjectdatabase.Itmayormaynotexistinthecurrentdrawing.WhenaCOGOpointisinsertedintoadrawing,itcanbeinsertedasanAeccPointorasablock.TheAeccPointisaCOMwrapperaroundanARXobject.

PointGroupsareusedtoworkwithanumberofpointsatatime.APointGroupdoesnotactuallyholdtheCogoPoint.ThePointGrouphasarangeofpointnumbers.ThepointnumberinapointgroupmaycontainpointsthatarenotcontainedintheProjectpointdatabase.APointGroupcanalsobeusedtooverridetheelevation,description,andnameforthepointsinthePointGroup.

ADescriptionKeyoverridestherawdescriptionfortheCOGOpoint.ByusingDescriptionKeys,youcansubstituteashortdescriptionwithalongerdescription.BydoingitwithaDescriptionKey,youonlyhavetochangethevalueinonespot.

Surfaces

TheTerrainModelisexposedthroughtheSurfacescollection.UsingtheSurfaceobject,youcandefinetheinputsfromPointFiles,PointGroupNames,BreakLines,ContourItemsandDEMFiles.YoucanalsoaddBoundariestoyourSurface.

YoucanalsogetalloutputinformationfortheSurface.TinPoints,Edges,Faces,ElevationContours,andWatershedscanberetrievedforaSurface.YoucanquerytheSurfacebypointtogettheelevationusingtheSurface.FindPointmethod.YoucanquerybetweentwopointsandretrievethecoordinateswherethatlinecrossesaSurfaceFacebyusing

Page 20: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

theSurface.SampleElevationsmethod.Foragivenelevation,youcanretrieveallofthecontoursonthatSurfacebyusingtheElevationContours.Elevationmethod.ThisgivesyoufullcontrolovercreationandqueryingofaSurface.

VolumesarealsosupportedasSurfaceobjectsthatresultfromDifferenceGridandCompositecalculationmethods.

Alignments

TheAlignmentscollectionhasalloftheAlignmentsfortheproject.ForeachAlignment,youcanretrieve,add,anddeletetheentitiesandstationequations.QueriescanalsobemadeontheAlignment:Alignment.StationOffset,Alignment.PointLocation.

Parcels

TheParcelscollectionprovidesaccesstoalloftheparcelsintheproject.EachParcelcanbequeriedtoobtainpropertyinformationsuchasarea,perimeter,centroidandname.Newparcelscanbecreatedorexisitingparcelmodifiedbyeditingthierindividualcurveandlineobjects.

Profiles,CrossSections,andSuperelevations

IfyouareusingAutoCADCivil3DLandDesktopCompanion,whichincludescivilengineeringandsurveyfeatures,extensivereadaccessisavailableforexistinggroundprofiles,finishedgroundprofiles,crosssections,andsuperelevationsproperties.Ifyouareusingthestand-aloneversionofLandDesktop(titled"AutoCADLandDesktop"),thecivilengineeringandsurveyfeaturesarenotavailable.

Youcanimportprofilesandcrosssectionstothecurrentdrawing,andthenaccesstheresultingProfileBlocksandCrossSectionBlocksforcustomannotation.

OverviewofEventsEventsareamechanismthatallowsyourapplicationtoreceivenotificationwhenachangeoccurstothestateofsomeobject.Toreceivenotification,youmust“enable”eventsbyprovidinga“handler”or“event

Page 21: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

sink”.RefertothesampleapplicationsforexamplesofhowtoimplementeventhandlersinVBandC++.

WhencodinginVBA,youmustprovideaneventhandlerforallobjectsenabledfortheModifiedevent.Ifyoudonotprovideahandler,VBAmayterminateunexpectedly.

Notethatnoeventswillbefiredwhileamodaldialogisbeingdisplayed.

AcadObject

AlloftheobjectsoutsideoftheProjectsandPrototypeshierarchyarederivedfromAcadObject.ThismeansthatobjectssuchasAeccApplicationandAeccDocumentderiveallofthepropertiesandmethodsfromtheparentActiveXobjects.However,sincenoadditionaleventswereimplemented,youwillusethebaseobjects(AcadApplicationandAcadDocument,forexample)togetnotificationsinyourapplication.

AcadEntity

TheCOMwrappersfortheAeccDbPoint,AeccDbContourandAecDbCurveTextobjectssupporttheModifiedevent.Thiseventwillbetriggeredwhenevertheobjectismodified.Modificationincludeswheneverthevalueofapropertyisset,evenifthenewvalueisequaltothecurrentvalue.

AeccObject

TheAeccObjectsupportstheModifiedevent,andallobjectsintheProjectsandPrototypeshierarchyarederviedfromAeccObject.Whileeveryobjectcansupporteventnotification,refertothefollowingtabletodeterminewhenaneventisfired.

EventnotificationisdispatchedbyaqueueingmechanismthatrespondswhenAutoCADentersaquiescentstate.Noeventswillbefiredwhileamodaldialogisbeingdisplayedorwhileacommandisinprogress.Inaddition,theeventqueuewillnotacceptmorethatoneeventforagiveninstanceofaCOMobjectatatime.Iftwoormoreeventconditionsoccuronanobjectwhileapendingeventisinthequeue,therewillbeonlyoneeventsentwhenAutoCADbecomesquiescent.

Page 22: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

Event Objects

ProjectManagement NewDrawing Project,Drawings

OpenDrawing Project

CoordinateGeometry Save/Deletepoint Points,Point

Save?Deletepointgroup PointGroups,PointGroup

Save/Deletedesckey

DescKeyFiles,DescKeyFile,DescKey

PlanAlignments Save/Delete Alignments,Alignment,AlignEntities,StationEquations

Surfaces Lock/Unlocksurface Surfaces

Create Surfaces

Setcurrentsurface Surfaces

Save/SaveAs Surfaces,Surface

Page 23: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

Delete/Rename Surfaces,Surface

Setdescription Surface

Addpointfile Surface,SurfaceInputs,Pointfiles

Addpointgroups Surface,SurfaceInputs,PointGroupNames

Addbreakline Surface,SurfaceInputs,BreakLines

Addboundary Surface,SurfaceInputs,Boundaries

Addcontour Surface,SurfaceInputs,ContourItems

Setouterboundary

Surface,SurfaceInputs,Boundaries

Flipface Surface,SurfaceOutputs,Edges,Faces,WaterSheds

InsertNDbreakline

Surface,SurfaceOutputs,TinPoints,Edges,WaterSheds

Surface,SurfaceOutputs,

Page 24: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

Insertline TinPoints,Edges,WaterSheds

DeletelineSurface,SurfaceOutputs,TinPoints,Edges,Faces,WaterSheds

Minimizeflattriangles

Surface,SurfaceOutputs,Edges,Faces,WaterSheds

Addboundary Surface,SurfaceOutputs,TinPoints,Edges,WaterSheds

Addtoallelevations

Surface,SurfaceOutputs,TinPoints,Edges,Faces,WaterSheds

SetelevationSurface,SurfaceOutputs,TinPoints,Edges,Faces,WaterSheds

PastesurfaceSurface,SurfaceOutputs,TinPoints,Edges,Faces,WaterSheds

Build Surface,SurfaceOutputs,TinPoints,Edges,Faces

Buildhydrologymodel

Surface,SurfaceOutputs,TinPoints,Edges,Faces,WaterSheds

Page 25: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

Computeextendedstats Surface

Set/Calcboundingbox Surface

Alignments Setcurrentalignment Alignments

Parcels Create Parcels

Delete,Import,Merge Parcel,Parcels

Profiles AlignmentEditorSave EGProfiles,FGProfiles

Creat,Edit,Delete EGProfiles,FGProfiles

CrossSections& SampleExistingGround CrossSections,Superelevations

Superelevations ProcessSections CrossSections,Superelevations

RunningMultipleInstancesofAutoCADAllAecBaseobjectsthatarederivedfromAcadobjectssupporttheInitmethod.ThisincludesAecApplication,AecDocuments,AecDocuments,AecDatabasePreferences,AecPreferences,AecPreferencesFiles,AecPreferencesUser,etc.

Page 26: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

ThehelpstringdescribestheInitmethodasan"InitializationmethodwhichmustbecalledbeforeaccessingtheAECapplicationobject"TheActiveXObjectModelforAutoCADLandDesktopperformsthecalltoInitautomaticallyforAeccobjects.

Itisnotrestricted(hidden)becauseitcomesinhandywhenyouarerunningmultipleinstancesofAutoCAD,ArchitecturalDesktop(AutoCADArchitecture)orAutoCADLandDesktop.ThisallowsyoutopassinaninstanceoftheAutoCADapplicationobjectthatyouareinterestedin,insteadofrelyingontheactiveinstancehandedbackfromtheRunningObjectTable.Ifyoupassthisintoaninstanceoftheapplicationobject,itwillautomaticallybepassedontoanynewinstanceofchildobjects.

Page 27: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

LandDesktopprojectsareusedtoorganizedrawingfiles,supportdatafiles,andsettingsthatareassociatedwitheachjobyouworkon.JustastheActiveDrawingiscentraltotheAutoCADapplicationobject,theLandDesktopapplicationobjectexposestheActiveProject.Throughtheprojectobject,youcanaccessCoordinateGeometry,PlanAlignment,DigitalTerrain,Parcels,Profile,CrossSectionandSuperelevationdataandpreferences.

Tocreateanewproject,usetheProjects.Addmethod,supplyingaprototypenamefromthePrototypescollectionandaprojectnameforthenewproject.Tocreatethefirstproject-baseddrawingforthenewproject,usetheDocument.NewProjectBasedmethod,specifyingthedrawingtemplatename,theprojectname,andthenewdrawingname.Thiswillswitchthedesktoptothenewlycreatedprojectanddrawing.

TheProjectscollectionisupdatedwhenevertheProjectPathpropertyischanged.Thisallowsyousearchforprojectsatvariouspaths.Toaccessfoldersonanetwork,youmustfirstmapthedrive.NotethatyouarelimitedtotheFileLocksandDrawingscollectionsforanyProjectthatisnottheActiveProject.ToaccesstheCogoPoints,PointGroups,DescriptionKeyFiles,Alignments,Surfaces,Parcels,Profiles,CrossSectionsandSuperelevationsyoumustbeintheprojectcurrentlyloadedintoAutoCADLandDesktop.

ExtensionstoAutoCADobjectsTheLandDesktopobjectmodelextendsmanyAutoCADActiveXobjectsbyaddingpropertiesandmethods.ThisincludestheApplication,Documents,Document,DatabasePreferences,PreferencesUser,PreferencesFile,andtheUtilityobjects.ThisenhancementisautomaticallyavailablewhenyounavigatefromtheAeccApplicationobjecttootherobjectsinthemodel.

TheDocumentscollectionsupportsthemanagementofmultipledrawings(MDI)intheAutoCADenvironment.SinceAutoCADLandDesktopworksonasingledrawingatatime(SDI),theDocumentsobjectisancillary.Youcangetthefirst(andonly)documentfromtheDocumentcollection,

UnderstandingProjectManagement

Page 28: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

butitisgenerallymoreconvenienttousetheAeccApplication.ActiveDrawingmethod.Also,notethattheDocuments.AddandDocuments.NewmethodsarenotavailableinSDImode.

TheDocumentobjectaddstwoimportantmethods-OpenProjectBasedandNewProjectBased.Usethesemethodstoopenandcreateproject-baseddrawings,respectively.BothmethodsacceptanoptionalProjectnametoallowyoutoswitchfromoneprojecttoanother.NotethattheDocument.OpenandDocument.Newmethodsdonotsupportprojectsandwillreturnanerrorifinvoked.

TheDatabasePreferencesobjectrepresentssettingsthataresavedonapre-drawing(ordocument)basis.ThisincludesbasesettingsforArchitectureandCivilEngineering,aswellasAutoCADLandDesktopspecificsettings.Thesesettingscanbeloadedandsavedtoanexternalsetupprofile.

ThePreferencesUserandPreferencesFilesobjectsstoreuserandapplicationlevelsettings,respectively.ThePreferencesUsersettingscontroloverridestoAutoCADbehaviorandthemostrecentlyusedprojectanddrawings.Italsoallowsadefaultdrawingsetupprofiletobeappliedtonewdrawings,sothattheuserisnotpromptedforsettings.ThePreferencesFilesobjectexposesthepathsusedbyAutoCADLandDesktop.

TheUtilityobjectaddsmethodsthatconvertanEastingandNorthingtoanAutoCADXandYandbackusingthegeodeticbasepointandnorthrotationforthedrawing.

Project-ownedobjectsInadditiontoprovidingaccesstoCoordinateGeometry,PlanAlignments,Parcels,TerrainModeling,Profiles,CrossSections,andSuperelevations,theProjectobjectexposestheDrawingsandFileLockscollection.

TheDrawingscollectionissimilartotheDocumentscollection,exceptthatitrepresentsAutoCADdrawingfilesinalocalorremotefolder(directory).Thesefilesmayormaynotbeloadedintotheapplication.YoucanusetheProjectsandDrawingscollectionstobrowseanyLandDesktopprojectonalocalormappedremotedrive.Forconvenience,you

Page 29: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

canusetheDrawings.OpenmethodtoswitchtotheparentprojectandopenthedrawingastheActiveDocument(similartotheDocument.OpenProjectBasedmethod).

TheFileLockscollectionexposesmulti-userprojectlocks.

UsingCollectionsTheobjectmodelcontainssimpleobjectsandcollectionsofobjects.Forsomecollections,ifyouchangethevalueofaproperty,thecollectionwillberebuilt.Youneedtorefreshyourobjectstoseetheeffectofthischange.Forexample:

DimprojectsAsAeccProjectsSetprojects=AeccApplication.Projects'GetthefirstprojectinthecollectionDimprojectAsAeccProjectSetproject=projects(0)'Changetheprojectpathprojects.Path="c:\projects2"'Projectisavalidobject,butnolongerrepresents'thefirstitemintheprojectscollection'refreshprojectSetproject=projects(0)

ChangingtheActiveProjectWhenadrawingisopenedfromadifferentproject,theAeccApplication.ActiveProjectobjectandAeccApplication.Projectscollectionarereleased.Forthisreason,itisagoodideatogettheseobjectsasneededinsteadofholdingontothemforthedurationofyourapplication.

NotificationsforchangestodrawingsettingsThesettingsexposedbytheDatabasePreferencesobjectarestoredintheAcDbDictionarynamed"AEC_VARS".The"AEC_VARS_DWG_SETUP"keyreturnsanAecDbVarsDwgSetupobjectthatstoresthebasesettingsforArchitectureandCivilEngineering.The

Page 30: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

"AEC_VARS_CIVILSETUP"keyreturnsanAcDbVarsCivilSetupobjectstorestheAutoCADLandDesktopspecificsettings.

Toreceiveeventswhendrawingsettingsarechanged,implementaneventhandlerinaclassmodule,declareanobjectoftypeAcadObjectwithevents,andassignthedesireddictionaryobjecttothehandlerinyourcodemoduleorform.

Page 31: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

TheActiveXObjectModelgivesaccesstoAutoCADLandDesktophorizontalalignments.AnAlignmentcancontaintangents(AlignTangent),curves(AlignCurve)andspirals(AlignSpiral).AnAlignmentcanbesettocurrent.ItsupportsthelockingmechanismfromAutoCADLandDesktop.Inaddition,stationequationsaresupportedforeachAlignment.

ThissectiondescribesthefundamentalsyouneedtoknowwhendevelopinganapplicationwithAlignments.Itprovidesinformationoncreating,using,andsavingAlignments.

CreatinganAlignmentIfanAlignmentisaddedsuccessfullytotheAlignmentscollection,therearetworesults:a)thenewAlignmentismadeCurrentandb)thenewAlignmentwillhaveawritelockonit.ThenewAlignmentisalsosavedimmediately.AutoSaveisignoredwhenanAlignmentiscreated.

"Current"AlignmentandLocksAutoCADLandDesktophasthenotionofa"current"alignment.Historically,thishasbeenusedintheapplicationtorelievetheuserfromhavingtoselectanalignmentforeverycommand.Also,whenanalignmentwassettocurrent,lockswerecreatedonthatalignment.Iftherewasapreviousalignment,thelockswerefreed.

TheActiveXObjectModelsupportsthe“Current”Alignmentconcept.AnAlignmentcanbemadeCurrentandlockswillbegeneratedatthattime.Also,thatCurrentAlignmentinActiveXObjectModelwillalsobethecurrentalignmentinAutoCADLandDesktop.ThroughtheActiveXObjectModel,youcanstayinsyncwiththemenus.

WhentheAlignmentscollectioniscreated,alloftheAlignmentnamesareloadedintomemory.Atthattime,eachAlignmentisgivenakReadLock.Nophysicallockiscreatedondisk.ThislockexistsonlyintheActiveXObjectModel.IftheAlignmentinthecollectionistheCurrentAlignment,thentheActiveXObjectModelwillretrievewhateverlockcurrentlyexistsondisk.ItcouldbeeitherakReadLockorakWriteLock.

UnderstandingAlignments

Page 32: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

WhenyoumakeanAlignmentcurrent,severalthingswillhappen.IftherewasapreviousCurrentAlignment,thatwillbeunlocked.Next,thenewCurrentAlignmentwillbesetinboththeActiveXObjectModelandAutoCADLandDesktop.Finally,alockwillbegeneratedonthatAlignmentintheActiveXObjectModelandondisk.Thislockcanbeseenbyanyuserscurrentlyinthatproject.ThelockcanbeeitherakReadLockorakWriteLock.ThetypeoflockdependsonweatherthatAlignmentwaslockedbyanotheruser.

Asarule,boththeActiveXObjectModelandAutoCADLandDesktopwillalwaystrytoretrieveakWriteLockwhenaccessinganobject.ThisappliestoAlignmentsandSurfaces.Ifsomeoneelsehasawritelockonthatobject,thenareadlockwillbeaddedtothatobject.

BeforeanyeditsaremadeonanAlignment,theAlignmentmustbemadeCurrent.Also,thatAlignmentmusthaveakWriteLockforanychangestobemade.

Youcanaddanewalignmenttothecollectionandlaterdefinetheunderlyinggeometry.Beadvisedthatifyousaveanalignmentwithoutaddinganytangents,curvesorspirals,youwillnotbeabletoeditthegeometryusingthealignmenteditor.

AutoSaveAnychangesmadetoanAlignmentareautomaticallysaved.WhentheAlignmentissavedallentitiesandthegeneralAlignmentdata(startingstation,description)arewrittenout.ThiscanimpactperformanceifmanychangesaremadetotheAlignment.RememberthateverychangemaderesultsinwritingtheentireAlignment.

Tohelpwiththeperformanceissues,AutoSavewascreated.IfAlignments.AutoSaveisTrue,theneverychangemadetoanalignmentresultsinawriteoperation.IfAlignments.AutoSaveisFalse,thennowriteoperationsareperformed.ItistheresponsibilityoftheprogrammertocallAlignment.Saveforthewriteoperation.

AutoSaveisattheAlignmentscollectionlevel.WhentheAutoSavevalueisset,allalignmentsinthecollectionareupdated.

Page 33: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

ThroughTerrainModelExplorer,athreedimensionalsurfacemodelcanbegeneratedfromdata.IntheActiveXObjectModel,youcancreateandquerythisthreedimensionalmodelthroughtheSurfacescollection.YoucanusetheSurfacecollectiontoiteratethroughalloftheexistingSurfaces,createannewSurface,ordeleteanexistingSurface.ThesearejustafewoftheSurfaceoperationsatthecollectionlevel.

ASurfaceisbrokendownintoinputs(SurfaceInputs)andoutputs(SurfaceOutputs).YoucanmodifytheSurfaceInputsbychangingtheContourItems,Breaklines,Boundaries,PointFiles,PointGroupsorDEMFiles.FromtheSurfaceOutputs,youcangettheTinPoints,Edges,Faces,ElevationContours,andWatersheds.

VolumeinformationcanbecreatedbyusingtheSurfaces.DifferenceGridortheSurfaces.CompositeGridmethods.BothmethodscreateanewSurface.ThisnewSurfacecanthenbequeriedforvolumeinformation.

SurfaceBoundaryPointsTheimplementationofIAeccBoundaries::Add()willcloseaboundary,ifthelastpointandfirstpointarenotidentical.Inaddition,ifthelastandfirstpointsarenotidenticalandcauselinesthatintersecteachother,thesurfacewillnotbehaveasexpected.Iftwopointsontheboundaryareco-located,theboundarywillberejected.Thebestwaytocreateaboundaryistoallowtheimplementationtoclosetheboundaryautomatically.

VisibleAreasUsingBreaklinesandBoundaries,areasofaSurfacecanbemadeinvisible.WatershedsandContourswillnotbereturnedfortheinvisibleareas.Faces,Edges,andTinPointswillbereturnedfortheinvisibleareas.

BuildSettingsSurface.BuildwillusethesettingsdefinedinTerrainModelExplorerBuilddialog.Thesesettingsincludethe"ApplyEditHistory"and"LogErrorsTo

UnderstandingSurfaces

Page 34: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

File"options.

EditHistoryEditHistoryisnotexposedinthisreleaseoftheActiveXObjectModel.However,ifthe"ApplyEditHistory"isturnedoninTerrainModelExplorer,thenSurface.Buildwillusethissetting.

SurfaceLockingInitially,allSurfaceshavenolocksappliedtothem.Whenamethodorpropertyiscalled,thentheSurfaceisopened.Atthattime,alockwillbecreatedonthatSurface.TheActiveXObjectModelwillalwaystrytocreateawritelock(kWriteLock).IfsomeoneelsehascontrolofthatSurface,youwillgetareadlock(kReadLock).IftheSurfaceisselectedastheCurrentSurface,thelockswillalsobegenerated.Whentheobjecthasgoneoutofscope,theSurfacewillgobacktoitsoriginalstate.IfitwasopenedandlockedbeforetheActiveXObjectModelobjectwascreated,thenitwillstayopenedandlocked.IftheSurfacewasnotopened(andtherefore,notlocked),thenwhentheActiveXObjectModelobjectgoesoutofscope,theSurfacewillbeclosedandunlocked.

ElevationContoursAfterasurfacehasbeenbuild,youcangeneratecontourdatabysettingtheElevationContours.Elevationproperty.ZeroormoreElevationContourobjectswillbeaddedtothecollection,dependingontheelevationyouset.YoucanusetheElevationContour.CoordinatespropertytosettheverticesofanAeccContourobject.

Page 35: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

ForeachLandDesktopProject,thereisaCOGOpointsdatabase.TheActiveXObjectModelgivesaccesstothisdatabasethroughtheCogoPointscollection.Throughthiscollection,youcanadd,delete,andmodifyaCogoPoint.

ACogoPointhasNorthing,Easting,andElevationfields.IftheGroupNameissetfortheCogoPoint,thenyouwillalsoseetheoverridesfromthatPointGroup.

PointGroupsandDescriptionKeyarealsoexposedthroughtheActiveXObjectModel.ThesecollectionsandobjectsallowyoutoworkwithgroupsofCOGOpoints.

CogoPointandAeccPointInaLandDevelopmentdocument,aCOGOpointcanexistinthedrawing.ThispointcanberepresentedaseitheranArxobjectoraSoftdeskblock.IfthepointisanArxobject,thenyoucanaccessitbyusingtheCOMwrapperAeccPoint.Thispointdoesnotnecessarilyexistinthepointdatabase.Ifitdoesexistinthedatabase,thenyoucouldaccessitbyusingaCogoPointobject.

Tostateitdifferently,aCogoPointobjectisapointdatabaseobjectandanAeccPointisaCOMwrapperfortheArxobject.

ACogoPointandAeccPointcanrepresentthesamegeometry.IfyouchangethecoordinatesforaCogoPoint,theArxobjectinthedrawingwillbeupdated.

PointNumberversesItemNumberWhenthecollectionclassisbuiltforCogoPoints,severalthingshappen.First,alistofthecurrentlyusedpointsisgenerated.Thesepointsarethenaddedtothecollection.Forexample,thepointdatabasehaspointswithpointnumbers1,3,5,and7.Whenthecollectionisbuilt,thenthecollectionwillhave4items.Item(0)willbepoint1,Item(1)point3,Item(2)point5,andItem(3)point7.ThereisnocorrespondencebetweentheItemnumberandthepointnumber.

UnderstandingCogoPoints

Page 36: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

Ifyouwanttoworkwithpointsbypointnumber,useCogoPoints.PointByNumber.

Page 37: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

Theverticalalignmentdataisrepresentedbytwocollections:theEGProfilesandtheFGProfiles.TheEGProfile,orexistinggroundprofiles,containsthesampledsurfacedataalongthealignment.TheFGProfile,orfinishedgroundverticalalignments,containthePVIswhichrepresentthebasisforthefinalroadwaydesign.TheEGProfilecanbeimportedintothedrawing,sothatthefinishedverticaldesigndatacanbedraftedontotheProfileBlock.

ExistingGroundProfilesWhiletheActiveXinterfacedoesnotrequireyoutodefineanyEGProfiles,theverticalalignmenteditorexpectstheExistingGroundCentertobedefined.

FinishedGroundProfilesWhenyoucreateanewFGProfileobject,adefaultPVIisaddedtothePVIscollectionasaplaceholder.ThepropertiesofthisPVIareallsetto0.0.Thisbehaviorisintentionalsinceatleastonedatumisrequiredtoaccesstheverticalalignmenteditor.

ItisuptotheusertomakesurethatthegeometryfortheFinishedGroundProfileiscorrect.Whendefiningaprofile,besuretocheckforthefollowing:

AFinishedGroundProfilecannotsupportaverticalcurveonthefirstorlastPVI.

TheFinishedGroundProfileobjectdoesnotcheckforoverlappingverticalcurves.TheFinishedGroundProfileobjectdoesnotchecktoensurethestartandendpointscoincidewiththepalnalignment.

LockingExistingGroundProfilesandFinishedGroundProfilesobjectsusethesamelockingastheAlignment.IftheAlignmenthasareadlock,thenExistingGroundProfilesandFinishedGroundProfileshaveareadlock.

UnderstandingProfiles

Page 38: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

Thesameistrueforwritelocks.Remember,theonlywaytogenerateawritelockistosettheAlignments.CurrentAlignmenttotheoneyouwanttoworkwith.

ProfileBlocksProfileBlocksdonotsupportxrefs.IfandrawingisXRefedintoanotherdrawingandithasaprofile,theProfileBlockscollectionwillnotputitintoitslist.

Inadrawing,analignmentcanhavemorethanoneProfileBlockdrawn.Ifthishappens,therewillbenouniqueidentifierfortheProfileBlock.TheProfileBlockscollectionwillhavebothProfileBlockobjectsbutitisuptheusertodeterminewhichprofilewillbeused.

ThescalefactorusedfortheverticalexaggerationoftheexistinggroundandfinishedgroundprofilesistheProfileBlock.VerticalScaledividedbytheDatabasePreferences.DatabaseScale.

TheCoordinatesoftheProfileBlockareoneinchbelowtheDatumElevationbaseline.

Page 39: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

TheCrossSectionsandSuperelevationscollectionsrepresentasliceofverticalalignmentdataatstationintervalsalongthealignment.ForagivenCrossSection,thedataispresentedasacollectionofpointcodesandsurfaces,suchasexistingground,topsurface,matchsurface,templatesandsubassemblies.Superelevationsarepresentedasacollectionofstationsatwhichthesuperelevationchanges.CrossSectionscanbeimportedintothedrawingasaCrossSectionBlockforcustomannotation.

Read-onlyCrossSectionandSuperelevationObjectsTheprocessofdesigningandapplyingroadwaytemplates,subassemblies,transitions,andsuperelevationsisacomplexprocedure.Forthisreason,theCrossSectionandSuperelevationobjectsareread-only.Youmustusetheappropriatecommandstocreateandeditthedata.TheActiveXobjectsprovideaccesstothedataforanalysisandcustomdrafting.

ManagingtheCurrentAlignmentWhenyouaccesstheCrossSectionandSuperelevationobjects,the"currentalignment"issettotheAlignmentyouareaccessing.YoucanusetheAlignments.CurrentAlignmentpropertytosaveandrestorethecurrentalignmentifrequired.

CrossSectionBlocksCrossSectionBlocksdonotsupportxrefs.IfadrawingisXRefedintoanotherdrawingandithasacrosssection,theCrossSectionBlockscollectionwillnotputitintoitslist.

Inadrawing,analignmentcanhavemorethanoneCrossSectionBlockdrawnforagivenstation.Ifthishappens,therewillbenouniqueidentifierfortheCrossSectionBlock.TheCrossSectionBlockscollectionwillhavebothCrossSectionBlockobjectsbutitisuptheusertodeterminewhichprofilewillbeused.

UnderstandingCrossSectionsandSuperelevations

Page 40: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

ThescalefactorusedfortheverticalexaggerationofthecrosssectionistheCrossSectionBlock.VerticalScaledividedbytheDatabasePreferences.DatabaseScale.

Page 41: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

TheParcelscollectionprovidesaccesstotheParceldatabaseandallowsadefinedParceltobeimportedinthedrawing.SimilartoanAlignment,aParcelismadeupofgeometricentitiesthatcanbeenumeratedusingtheParcelEntitescollection.

ClosingParcelPerimetersWhendefiningaParcel,theperimeterisnotautomaticallyclosedforyou.AParcelthathasnotbeenclosedwillreturnanareaof0.0squareunits.

LockingTheParceldatabasesupportsmulti-useraccesswithlocks.UnlikeAlignments,thelockingoccursautomaticallyonacommandbycommandbasis.AParcelcannotbelockedforthedurationofadesignsession.

UnderstandingParcels

Page 42: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

OverviewACOMwrapperprovidesaninstanceofanActiveXobjectthatrepresentsadrawingentity.Yourapplicationusestheproperties,methods,andeventsfromthisobjecttoaccessandmanagethecorrespondingentityinthedrawing.COMwrappersareimplementedforAeccDbContour,AeccDbPoint,andAecDbCurveTextentities.

AutoCADLandDesktopobjectsthatarecreatedinmodelspace,usetheAcadModelSpacecollectiontoiteratethroughobjects.Forexample:

DimpntAsAeccPointDimobjAsAcadObjectForEachobjInThisDrawing.ModelSpaceIfobj.ObjectName="AeccDbPoint"ThenSetpnt=objEndIfNext

Similarly,youcaniterateexistingentitiesinaselectionsettoaccessyourcustomARXobjectsthroughtheirCOMwrappers.WhenusingtheFilterDataparameterforanAcadSelectionSet,specifytheobjectnamethatappearsinthePropertieswindow(orwhenyoulistanobject):AECC_CONTOUR,AECC_POINT,orAEC_CURVETEXT.

ObjectCreationYoucanusetheAcadModelSpace.AddCustomObjectmethodto(1)createaninstanceofyourARXobjectand(2)returnaninstanceofyourCOMwrappersoyoucanuseitspropertiestoinitializetheobject.NotethatyoucannotcreateAutoCADLandDesktopobjectsinPaperSpaceorBlocks.Forexample:

DimpntAsAeccPointSetpnt=ThisDrawing.ModelSpace.AddCustomObject("AeccDbPoint")pnt.Easting=1000pnt.Northing=1000pnt.Elevation=100

UnderstandingComWrappers

Page 43: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

pnt.Number=1pnt.Description="testpoint"

EventsTheAutoCADLandDesktopobjectssupportnotificationthroughtheModifiedevent.

ContourStylesContourstylesaresavedonaper-drawingdrawingbasisinthedictionary.Tofacilitatethemanagementofstylesforcontourobjects,aCOMwrapperforthecontourstyleisprovided.Youcanaccessanystyleloadedinthecurrentdrawingthroughthe"AECC_CONTOUR_STYLE";dictionary:

DimcsAsAeccContourStyleDimobjAsAcadObjectForEachobjInThisDrawing.Dictionaries("AECC_CONTOUR_STYLES")Setcs=objIfcs.Name="Standard"ThenExitForEndIfNextDimContourAsAeccContourSetContour=ThisDrawing.ModelSpace.AddCustomObject("AeccDbContour")Contour.SetContourStylecs

Page 44: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

ThissectionprovidesusefulinformationonhowtousetheActiveXObjectModelwithvariousprogramminglanguagesanddevelopmentenvironments.

TopicsinthisSection

VBAVBC++J++OtherLanguages

ProgrammingGuidelinesIntroduction

Page 45: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

OptionExplicitAgoodprogrammingpracticeistoaddtheOptionExplicitdeclarationatthetopofyourmodule.ThiswillrequireyoutodeclareallvariablesusingtheDim,Private,Public,ReDim,orStaticstatements.Ifyouattempttouseanundeclaredvariablename,anerroroccursatcompiletime.ThispreventsVisualBasicfromautomaticallycreatingavariantfortheundeclaredvariableonyourbehalf,whichleadstoprogramerrors.

ForNextLoopsWhenusingaForNextlooptoiteratethroughanobjectcollectionuse"EXITFOR"ifyouneedtoexittheloopbeforconclusion.Ifa"GOTO"isusedtoexittheloopthereferencecounttotheobjectisnotcleanedandwillcreateanerrorcondition.

IntelliSenseIfanAutoCADLandDesktopobjectdoesnotdisplaythecompletelistofpropertiesandmethodsintheIntelliSensepicklist,tryassigningtheobjecttoatypedvariablefirst.Forexample:

DimprefuserAsAeccPreferencesUserSetprefuser=AeccApplication.Preferences.User'Theprefuserobjectwillnowcorrectlydisplay'allpropertiesandmethodswithIntelliSense

AutoCADLandDesktopEnumeratedValueAutoCADLandDesktopenumeratedvaluesarenamedconstantsusedintheAutoCADLandDesktopActiveXAutomationmethodsandproperties.

InVBA,youcannotcreateaninstanceofanobjectoftheenumeratedtype.Forexample:

'WorksinVB,butnotVBADimborderstyleAseAeccBorderStyle

Globals

VBAProgrammingGuidelines

Page 46: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

InVBA,globalvariablesarenotreleaseduntiltheVBAprojectisunloaded.Forexample,inyourprojectthefollowingvariablesaredeclaredasglobalvariables:

OptionExplicitPublicacadAsAcadApplicationPublicappAsAeccApplicationPublicprojsAsAeccProjects

Theobjectsacad,app,andprojwillnotbereleaseduntiltheVBAprojectisunloaded.ThisiscorrectbehaviorbutyoumustrefreshthevariableswhenyoucomebackintotheVBAcode.Ifyoudonotrefreshthevariables,youmightnotgetthelatestinformation.Forexample,additionalprojectsmightbeaddedtotheAeccProjectscollection.

Page 47: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

Ingeneral,alloftheguidelinesfromtheVBAsectionalsoapplytoVB.Thissectionincludessomeadditionalinformationthatisspecifictodevelopingstand-alone(out-of-process)applicationsusingVisualBasic.

ConnectingtoAutoCADLandDesktopVisualBasicprovidesafunctioncalledGetObjecttogetareferencetoacurrentlyactiveinstanceofanActiveXobjectofthespecifiedtype.SinceacompiledVBapplicationisinadifferentprocessthanAutoCADLandDesktop,youmust"connect"totheapplicationobject:

DimacadAsAcadApplicationSetacad=GetObject(,"AutoCAD.Application")

Next,youusetheAcadApplication.GetInterfaceObjectmethodtogetaninstanceoftheAutoCADLandDesktopapplicationobject:

DimappAsAeccApplicationSetapp=acad.GetInterfaceObject("Aecc.Application")

YoumightwanttodeclarethesevariablesasPublicatthemodulelevelsothattheyareavailabletoallproceduresinallmodules.

ForNextLoopsWhenusingaForNextlooptoiteratethroughanobjectcollectionuse"EXITFOR"ifyouneedtoexittheloopbeforconclusion.Ifa"GOTO"isusedtoexittheloopthereferencecounttotheobjectisnotcleanedandwillcreateanerrorcondition.

QuiescentStateandActiveXcallsWhenAutoCADisatthecommandlineprompt,itisinaquiescentstate.WhenAutoCADhascompletedprocessingthelastcommandandtherearenopendingcommands,itisinastatethatAutoCADcanprocessanActiveXcall.

BeawarethatifAutoCADisbusywhenyourapplicationtriestoinvokeanActiveXpropertyormethod,AutoCADmaydisplayamodaldialogindicatingthattheActiveXrequestwasnothandled.Youarethen

VBProgrammingGuidelines

Page 48: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

promptedtoretrytherequest.

Topreventthissituation,yourapplicationshouldusetheAcadApplication.GetAcadStatemethodtodetermineifAutoCADisbusy.ThismethodreturnsanAcadStateobject,whichisatransientobjectusedtocheckforAutoCADquiescencefromout-of-processapplications.

Page 49: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

ImportingTypeLibrariesCOMreplacesthenotionofheaderfileswithTypeLibraries.IntheMicrosoftVisualC++environment,youusethepreprocessordirective#importintheStdAfx.hfiletomakeallinterfaces,properties,methods,events,enumerations,etc.availableinyourcode.Usetheno_namespaceoptiontodisabletherequirementofqualifyingeachobjectwiththetypelibraryname.

Forexample:

//createC++wrapperclassesfortheCOMinterfaces

//newTLHandTLIfileswillbegeneratedeachtime

#import"acax16enu.tlb"/*no_implementation*/raw_interfaces_onlyno_namespacenamed_guidsrename("GetObject","acaxGetObject")

#import"AecXUIBase40.tlb"no_implementationraw_interfaces_onlynamed_guidsno_namespace

#import"AecXBase40.tlb"no_implementationraw_interfaces_onlynamed_guidsno_namespace

#import"LandAuto46.tlb"no_implementationraw_interfaces_onlynamed_guidsno_namespace

NotethattheAecXBasetypelibraryreferencestheAutoCADAxDb16typelibrary.WhileyoudonothavetoexplicitlyimportAxDb16enu.tlb,itmustbeinthepathorproperlyregisteredonyourworkstation,otherwiseyouwillencountererrorswhenimportingAecXBase40.tlb.

InitializingtheCOMlibrariesWhenyoucreateyourproject,youmaysafelyomittheoptions"Automation"and"ActiveXControls"toreducethecodesizeofyourproject.However,youwillneedtomake2manualchangestoensurethattheCOMlibrariesareinitialized:

C++ProgrammingGuidelines

Page 50: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

InStdAfx.h:

#include<afxdisp.h>//MFCOLEautomationclasses

Inyourapplication’sInitInstancemethod:

//InitializeOLElibrariesif(!AfxOleInit()){AfxMessageBox("OLEinitializationfailed.");returnFALSE;}

ConnectingtotheLandDesktopApplicationObjectIngeneral,thesearethestepstogettotherunninginstanceoftheLandDesktopApplicationObject:

CallGetActiveObjecttogettherunninginstanceoftheAutoCADapplicationobject.ThismethodreturnsapointertoIUnknown.

CallQueryInterfacetogettheinterfaceIAcadApplication.

CallGetInterfaceObjecttogettherunninginstanceoftheLandDesktopapplicationobject.ThismethodreturnsapointertoIDispatch.

CallQueryInterfacetogettheinterfaceIAeccApplication.

IfyouhaveseveralinstancesofAutoCADapplicationsrunningatthesametime(AutoCAD,LandDesktop,ArchitecturalDesktop,RasterDesign),andyouaredevelopinganin-processapplication(e.g.ARXDLL),youcanusethesestepstogetthecorrectinstanceofAutoCAD:

CallAfxGetApptogetapointertotheCWinAppderivedobject.

CallGetIDispatchtogettheIDispatchinterfacefortheAutoCADapplicationobject.

CallQueryInterfacetogettheinterfaceIAcadApplicationinterface.

Page 51: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

CallGetInterfaceObjecttogettherunninginstanceoftheLandDesktopapplicationobject.ThismethodreturnsapointertoIDispatch.

CallQueryInterfacetogettheinterfaceIAeccApplication.

CallInit,passingintheIAcadApplicationpointertoinitializetheobjectmodelwiththeproperinstanceofAutoCAD.

Whendevelopingastandalone(outofprocess)applicationthatneedstohandlemultiplerunninginstancesofAutoCADapplications,youmustenumeratetheRunningObjectTableforthedesiredinstanceofAutoCADinplaceofthecalltoAfxGetApp.SeeMSDNArticle190985fordetailsandsamplecode.

RestrictedPropertiesandMethodsWhenyouimportaTypeLibraryintoyourproject,youmayseemtohaveaccesstoread-onlypropertiesandbeabletoinvokemethodsthatarenotdocumentedintheAutoCADLandDesktopActiveXandVBAReference.These"restricted"membersoftheinterfacearehiddeninVBAandothermacrolanguages,butarenotfilteredoutbytheimportdirective.

Beawarethatthesememberscannotbecalledarbitrarily.MostareusedforinitializingtheCOMobject,andwillnotupdateyourprojectdatabase.RefertotheAutoCADLandDesktopActiveXandVBAReferenceforthelistofsupportedinterfacemembers,orusetheOLEViewersuppliedwiththeMicrosoftVisualStudioToolstodeterminewhichmembersarerestricted.

CachingInterfacesItisrecommendedthatyoucachetheapplicationobjectonly(i.e.IAeccApplicationPtr).Thiswillallowaccesstoanyobjectthroughoutthedurationofyourapplication.

Forallotherobjects,itisgenerallysafertoqueryforinterfacesuponeachuseinsteadofcachingandre-usingpointersasclassmembersorothernon-localvariables.Thiswillavoidanyconfusionaboutthestateoftheinterfaceobjectatthetimeofuse.

Page 52: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

ExceptionHandlingWhenyouimportaTypeLibraryintoyourMicrosoftVisualC++project,thepreprocessorgeneratesboth"raw"methodsand"wrapper"methodsinthe*.tlhfile.TherawmethodsreturnHRESULTs,whichshouldbecheckedbytheprogrammer.ThewrappermethodshidetheHRESULTs,providingerrorhandlingforyou,andwillissueaCOMexceptionwhenanerroroccurs.Whilethewrappermethodsprovideaconveniencetothedeveloper,unhandledexceptionswillappearinadialogbeforeyourusers.

Ineithercase,youshouldhandletheseerrorsinyourapplication.Thiscanbeaccomplishedinoneoftwoways:

Wrapallcallstowrappermethodsintry-catchblocks

ChecktheHRESULTfromtherawmethodsandimplementerrorcheckingyourself

SmartPointersWhenyouimportaTypeLibrary,thegeneratedwrappermethodswilluse"smartpointers"wheneverthemethodreturnsaninterface.Youmustuseasmartpointerinyourcodetoensurethatthereferencecountontheobjectdoesnotdecrementto0beforethecalltothewrappermethodreturns.Ifyouuseastandardpointer,youwillbeleftwiththeaddressofareleasedCOMobject,andanexceptionwilloccurwhenyoutrytouseit.

COMSupportclassesIfanargumentorreturnvalueofawrapperclassexpectsa_variant_t(or_bstr_t),donotuseaVARIANT(orBSTR).Thiswillcompile,butwillultimatelycauseproblems.

Forexample,therawmethodforAeccCogoPoints.PointStringToArraylookslikethis:

virtualHRESULT__stdcallraw_PointStringToArray(BSTRPointString,VARIANT*Points)=0;

Page 53: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

Thewrappermethodlookslikethis:

;_variant_tPointStringToArray(_bstr_tPointString);

TheCOMsupportclass_variant_tautomaticallyinitializesitsinternalVARIANTusingthecorrectconstructor(theonethattakesaVARIANT*,inthiscase).Notethatwhileingeneral,theclientisresponsiblefordeallocatingthememoryallocatedforthevariant,the_variant_t(or_bstr_t)classesdoitautomaticallyforyou.

MFCclassWizardSupportThroughMicrosoft'sMFCclassWizard,youcangenerateMFCclassesfromtheTypeLibrary.Thisgivesyoueasyaccesstowrappedmethodsandproperties.However,someoftheLandDesktopobjectsarederivedfromAutoCADorAecobjects.Forexample:AeccApplication,AeccDocument.WhenaMFCclassisgeneratedfortheseclassesthroughclassWizard,thenonlytheadditionalmethodsandpropertiesthatLandDesktopaddedwillbeimplementedinthatnewclass.classWizarddoesnotimplementthemethodsandpropertiesfromtheparentclass.

ARXdevelopmentWhenregisteringanewcommandthatwillinvokeActiveXmethods,usetheACRX_CMD_MODALcommandflag.Thecommandmustbemodal(andnottransparent)sothatnoothercommandsorprogramsarecurrentlyactive.

IfyouplantousetheDocument.OpenProjectBasedorDocument.NewProjectBasedmethodsinyourregisteredcommand,besuretoaddtheACRX_CMD_SESSIONandACRX_CMD_NOINTERNALLOCKflags.Theformerflagrunsthecommandhandlerinthesessionfiber,whilethelateravoidslockingtheAutoCADstateoutofquiescence(normallyusedwithActiveXcalls).TheseflagsarerequiredtoensurethatAutoCADisinthepropercontextwhenswitchingdocuments.

ReturnvaluesIngeneral,allpropertiesandmethodsreturnS_OKwhennoerrorsare

Page 54: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

encountered.ThereturnvalueE_FAILisreturnedwhenaninternalerrorconditionpreventssuccessfulcompletionoftheoperation.AnexampleisamemoryallocationorotherWin32servicefailure.Incertaincases,areturnvalueofS_FALSEisreturnedtoindicatethattheoperationdidnotcompleteduetousererror.Someexamplesincludetryingtoappendanalignmententitythathasnomatchingendpointwiththepreviousentity,ortryingtoaccessthecoordinatesofanelevationcontourusinganinvalidelevationforthesurface.

Inyourapplication,checkforareturnvalueofS_OKtoindicatethatnointernalorusererrorshaveoccured.

Using"IntelliSense"IfyoutypicallyuseIntelliSensetodeterminewhatpropertiesandfunctionsareavailableforagiveninterface,pleasebeadvisedthatrestrictedfunctionswillshowupinIntelliSense.Theserestrictedfunctionsarenotsupported,andinmostcaseswillcauseundesirableeffects.ThesafewaytodeterminethesupportedfunctionsistoconsulttheHelpforAutoCADLandDesktopActiveXObjects.

Page 55: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

ImportingTypeLibrariesAftercreatingaWindowsApplicationprojectinVisualJ++,youcanimportCOMobjectsthroughtheTypeLibraries.VisualJ++createsclasswrappersthatprovidetheinterfaceforaccessingtheCOMobjects.Theseclasswrappersareaddedaspackagesinyourprojectdirectory.

Note:ToaccessaspecificCOMobjectfromanotherproject,youcanavoidwrappingtheobjectsforeachprojectbyplacingtheCOMwrapperclassesintheCLASSPATH.

TheCOMwrapperscanbecreatedfromtheVisualJ++IDEoratthecommandlineusingthejactivex.exeutility.

TocreatetheCOMwrappersfromthecommandline:Invokethejactivex.exeutility.Forexample:jactivex/wfc/w/xi/X:rkc/d"d:\VJ++\COM_Wrappers"landauto46.tlbBuildtheclassfilesforeachCOMWrapperjavafileusingtheJavacompiler.The*.javafilescanberemovedfromtheCLASSPATHaftertheclassfileshavebeencreated.

TogeneratetheCOMWrappersfromtheVisualJ++IDE:OntheCOMWrapperdialog,selecttheLandTypeLibrary1.1checkboxandclickOK.SelecttheBuildmenuitemtobuildthesolutionandgeneratetheclassfilesfromthejavafilesTheCOMwrapperfoldersmaynowberemovedfromtheprojecttopreventtheclassfilesfrombeingregeneratedduringeachbuild.Thiswillreducethesizeofthesolutionandreducethebuildtime

GettingtheApplicationobjectThisexampleshowshowtoaccesstheAutoCADLandDesktopApplicationobjectthroughtherunningobjecttable.

//Importthelibrarypackagessoobjectscanbereferredbytheirshortnames://RequiredVisualJ++imports:importcom.ms.win32.Ole32;

J++ProgrammingGuidelines

Page 56: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

importcom.ms.wfc.ui.*;importcom.ms.com.*;//RequiredLandautoimports:importacax16enu.*;importAecXBase40.*;importAecXUIBase40.*;importAxDb16enu.*;importLandAuto46.*;publicclassLandAutoSampleextendsObject{privateIAeccApplicationm_iaecApp;privateIAeccProjectsm_iaecProjects;privateIAeccProjectm_iaecProject;//Constructor:publicLandAutoSample(){m_iaecApp=GetAeccApplication();m_iaecProjects=m_iaecApp.getProjects();m_iaecProject=m_iaecApp.getActiveProject();}//SampleclassmethodtogettheexistingIAeccApplicationobject:privateIAeccApplicationGetAeccApplication(){//***GettheexistingAutoCADsession:Ole32ole32=newOle32();StringsAcadApp="AutoCAD.Application";_Guid_guid=ole32.CLSIDFromProgID(sAcadApp);StringsGuidAcad=_guid.toString();StringsMonikerDispName="!"+sGuidAcad;IRunningObjectTableirot=ole32.GetRunningObjectTable(0);IMonikerimoniker=ole32.CreateItemMoniker(sMonikerDispName,"");IAcadApplicationiacApp=(IAcadApplication)

Page 57: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

irot.GetObject(imoniker);//***Ifyouaregoingtousecivilengineringfeatureinterfaces,CrossSections,Profiles,etc.//initializecivilengineeringfeaturesinterfaceincaseithasnotbeeninitialized.:IAcadDocumentiacDoc=(IAcadDocument)iacApp.getActiveDocument();iacDoc.SendCommand("(cd_mnl)");//***GettheAeccApplicationinterfaceobject:StringsAeccApp="Aecc.Application";IAeccApplicationiaecApp=(IAeccApplication)iacApp.GetInterfaceObject(sAeccApp);returniaecApp;}//SamplemethodthatreturnsaStringarraycontainingProjectNames//thatcouldbedisplayedinaListBoxcontrol:publicString[]GetProjectNames(){IAeccProjectproj=m_iaecApp.getActiveProject();intiCount=m_iaecProjects.getCount();String[]sProjects=newString[iCount];StringsProjName="";Variantv=newVariant();for(inti=0;i<iCount;i++){v.putInt(i);proj=m_iaecProjects.Item(v);sProjects[i]=proj.getName();}returnsProjects;}}

Page 58: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

RestrictedPropertiesandMethodsWhenyouimportaTypeLibraryintoyourproject,youmayseemtohaveaccesstoread-onlypropertiesandbeabletoinvokemethodsthatarenotdocumentedintheAutoCADLandDesktopActiveXandVBAReference.These"restricted"membersoftheinterfacearehiddeninVBAandothermacrolanguages,butarenotfilteredoutbytheimportdirective.

Beawarethatthesememberscannotbecalledarbitrarily.MostareusedforinitializingtheCOMobject,andwillnotupdateyourprojectdatabase.RefertotheAutoCADLandDesktopActiveXandVBAReferenceforthelistofsupportedinterfacemembers,orusetheOLEViewersuppliedwiththeMicrosoftVisualStudioToolstodeterminewhichmembersarerestricted.

Page 59: AutoCAD Land Desktop ActiveX and VBA … ActiveX Object Model for AutoCAD Land Desktop is an ActiveX and VBA interface that enables developers to create dynamic and powerful applications.

TheActiveXObjectModelopensupprogrammaticaccesstoAutoCADLandDesktopProjectstomanyprogrammingenvironmentsotherthanVB,VBA,C++,J++andVisualLISP.Theseinclude:

AnyMicrosoftOffice97product,includingWord,Access,Excel,ProjectandPowerPoint.AnyVBScriptenabledproduct,includingOutlookandInternetExplorer.AnyproductthatsupportsAutomation(ActiveXDispatchinterfaces),includingDelphi.

Pleaserefertothedocumentationprovidedwitheachproduct.

OtherProgrammingGuidelines