arcgis_vba

57
Customizing ArcGIS Using Customizing ArcGIS Using ArcObjects With VBA ArcObjects With VBA

Upload: rajaanwar

Post on 23-Oct-2015

25 views

Category:

Documents


4 download

TRANSCRIPT

Customizing ArcGIS Using Customizing ArcGIS Using ArcObjects With VBAArcObjects With VBA

IntroductionIntroduction

•• Add custom controls to ArcGISAdd custom controls to ArcGIS

•• Overview of ArcObjectsOverview of ArcObjects

•• Use of VBA in ArcGISUse of VBA in ArcGIS

•• DemonstrationsDemonstrations

Types of BuiltTypes of Built--in Controlsin Controls

Custom menu with added commandsCustom menu with added commandsMenu : Menu :

Pick list of valuesPick list of valuesComboboxCombobox ::

Editable text boxEditable text boxEdit Box :Edit Box :

Controls action of mouseControls action of mouseTool :Tool :

Executes when clickedExecutes when clickedCommand :Command :

Added to Toolbars menuAdded to Toolbars menuToolbar :Toolbar :

Adding Custom Control:Adding Custom Control:Toolbar: Step 1 Toolbar: Step 1 –– Right ClickRight Click

Adding Custom Control:Adding Custom Control:Toolbar: Step 2 Toolbar: Step 2 –– Toolbars TabToolbars Tab

Adding Custom Control:Adding Custom Control:Toolbar: Step 3 Toolbar: Step 3 –– Check “Save in”Check “Save in”

Adding Custom Control:Adding Custom Control:Toolbar Toolbar -- CompleteComplete

Adding Custom Control:Adding Custom Control:Commands, Tools, Commands, Tools, EditboxEditbox, , ComboboxCombobox Step 1 Step 1 –– Right ClickRight Click

Adding Custom Control:Adding Custom Control:Commands, Tools, Commands, Tools, EditboxEditbox, , ComboboxCombobox Step 2 Step 2 –– Commands TabCommands Tab

Adding Custom Control:Adding Custom Control:Commands, Tools, Commands, Tools, EditboxEditbox, , ComboboxCombobox Step 3 Step 3 –– Create New Create New UIToolControlUIToolControl

Adding Custom Control:Adding Custom Control:Commands, Tools, Commands, Tools, EditboxEditbox, , ComboboxCombobox Step 4 Step 4 –– Drag new control onto Drag new control onto

interfaceinterface

Adding Custom Control:Adding Custom Control:Commands, Tools, Commands, Tools, EditboxEditbox, , ComboboxCombobox Step 5 Step 5 –– Right click, View SourceRight click, View Source

Adding Custom Control:Adding Custom Control:Commands, Tools, Commands, Tools, EditboxEditbox, , ComboboxCombobox Step 6 Step 6 –– Add CodeAdd Code

Adding Custom Control:Adding Custom Control:Menu: Step 1 Menu: Step 1 –– Right ClickRight Click

Adding Custom Control:Adding Custom Control:Menu: Step 2 Menu: Step 2 –– Command Tab > New Menu > drag new menu on Command Tab > New Menu > drag new menu on

interfaceinterface

Adding Custom Control:Adding Custom Control:Menu: Step 3 Menu: Step 3 –– right click on Menu to renameright click on Menu to rename

Adding Custom Control:Adding Custom Control:Menu: Step 4 Menu: Step 4 –– Click menu with customize dialog openClick menu with customize dialog open

Adding Custom Control:Adding Custom Control:Menu: Step 5 Menu: Step 5 –– Drag desired commands onto menu from dialogDrag desired commands onto menu from dialog

What Are “ArcObjects” ?What Are “ArcObjects” ?

•• A set of components of the ArcGIS platform A set of components of the ArcGIS platform which can be accessed through which can be accessed through programming environment (VBA, VB, C++, programming environment (VBA, VB, C++, .NET, VB Script).NET, VB Script)

•• ArcObjects have:ArcObjects have:

–– characteristics which can be queried or setcharacteristics which can be queried or set

–– the ability to perform operationsthe ability to perform operations

–– the ability to respond to changes in application the ability to respond to changes in application framework in which they are deployedframework in which they are deployed

ArcObjects Object ModelArcObjects Object Model

•• Synoptic view of ArcObjectsSynoptic view of ArcObjects

•• Included with ArcObjects Developer KitIncluded with ArcObjects Developer Kit

•• ArcGIS installation optionArcGIS installation option

•• Diagrams (Diagrams (OMD’sOMD’s)) in PDF formatin PDF format

Reading ArcObjectsReading ArcObjects OMD’sOMD’s: : ClassClass

•• Template (blueprint) for Template (blueprint) for creating ArcGIS objectscreating ArcGIS objects

•• Defines interfaces, properties Defines interfaces, properties and methods for an objectand methods for an object

•• With VBA, code is stored in With VBA, code is stored in the documentthe document

Reading ArcObjectsReading ArcObjects OMD’sOMD’s: : InterfaceInterface

•• Method of communication with an Method of communication with an objectobject

•• Logical groups of methods and Logical groups of methods and propertiesproperties

•• Can be one or many on a single Can be one or many on a single objectobject

•• Can be used by more than one Can be used by more than one type objecttype object

•• May be inbound or outboundMay be inbound or outbound

Reading ArcObjectsReading ArcObjects OMD’sOMD’s::properties and Methodsproperties and Methods

•• Properties of interface can be set and/or readProperties of interface can be set and/or read

•• Methods are actions object performed through interfaceMethods are actions object performed through interface

•• Accessed as:Accessed as:<object interface>.<property or method> (par1, par2)<object interface>.<property or method> (par1, par2)

ReadWriteRead / WriteWrite

ArcObjects OMDArcObjects OMDRelationship NotationRelationship Notation

Egg

Bird

Wings

Nest

*

Chicken

Coop

•• Is a type ofIs a type of•• Is composed ofIs composed of•• CreatesCreates•• AssociationAssociation

Navigating OMDNavigating OMDStep 1 Step 1 –– Start with Start with MxDocument MxDocument classclass

•• Example: Return name of Example: Return name of first layer in ArcMap TOCfirst layer in ArcMap TOC

•• Start with Start with IMxDocumentIMxDocumentinterface of document object, interface of document object, MxDocumentMxDocument

•• Use Use FocusMap FocusMap property to property to reference the Map object reference the Map object through through IMapIMap interfaceinterface

Navigating OMDNavigating OMDStep 2 Step 2 –– Explore the Map classExplore the Map class

•• Example: Return name of Example: Return name of first layer in ArcMap TOCfirst layer in ArcMap TOC

•• Start with Start with IMxDocumentIMxDocumentinterface of document object, interface of document object, MxDocumentMxDocument

•• Use Use FocusMap FocusMap property to property to reference the Map object reference the Map object through through IMapIMap interfaceinterface

•• Use Layer property of the Use Layer property of the Map to reference layer objectMap to reference layer object

Navigating OMDNavigating OMDStep 3 Step 3 –– Query the Layer classQuery the Layer class

•• Example: Return name of Example: Return name of first layer in ArcMap TOCfirst layer in ArcMap TOC

•• Start with Start with IMxDocumentIMxDocumentinterface of document object, interface of document object, MxDocumentMxDocument

•• Use Use FocusMap FocusMap property to property to reference the Map object reference the Map object through through IMapIMap interfaceinterface

•• Use Layer property of the Use Layer property of the Map to reference layer objectMap to reference layer object

•• Query Layer object’s Name Query Layer object’s Name propertyproperty

Common ArcMap ObjectsCommon ArcMap Objects

SelectedLayer(Layer)

SelectedLayer(Layer)

LayerLayer

SelectionSelection

Common ArcMap ObjectsCommon ArcMap Objects

Maps (Collection)

Map (FocusMap )

Map (FocusMap )

MapMap

ApplicationApplicationMxDocument(ThisDocument)

Document EventsDocument EventsCode executes when user interacts with documentCode executes when user interacts with document

–– Open documentOpen document

–– Close documentClose document

–– New documentNew document

–– othersothers

Defining Variables•• Must define object variables before settingMust define object variables before setting

•• Use the Dim, Private, or Public statementsUse the Dim, Private, or Public statements

•• Variables pointing to ArcObjects must reference Variables pointing to ArcObjects must reference one of the object’s interfacesone of the object’s interfaces

Defining Variables

Option ExplicitDim <variable> as <VBA instrinsic type>Dim strLayerName as StringPublic strTitle as String

Dim <variable> as <interface name>Dim pMxDoc as IMxDocumentPrivate pFL as IFeatureLayer

ArcGIS Predefined VBA VariablesArcGIS Predefined VBA VariablesApplication, Application, ThisDocumentThisDocument

•• Starting points for writing codeStarting points for writing code

•• Application Application –– pointer to ArcMap or ArcCatalogpointer to ArcMap or ArcCatalog

•• ThisDocument ThisDocument –– pointer to current documentpointer to current document

Application.Caption = “Watershed Analysis”Dim pMxDoc as esriCore.IMxDocumentSet pMxDoc = ThisDocument

ObjectsObjects

•• Created from class Created from class “blueprints”“blueprints”

•• Stored in memoryStored in memoryDim pPnt As IPoint

Dim pMxDocument As IMxDocument

Set pMxDocument = ThisDocument

Set pPnt = _

pMxDocument.CurrentLocation

•• Created from Created from interface property or interface property or methodmethod

Dim pTextElement As ITextElement

Set pTextElement = _

New TextElement

•• Created using “New” Created using “New” keywordkeyword

Query Interface:Query Interface:Use one interface to get to anotherUse one interface to get to another

•• Method for getting to a Method for getting to a different interface on an different interface on an existing object using an existing object using an established interface variableestablished interface variable

Query Interface:Query Interface:Coding exampleCoding example

Use of SET Keyword•• When using query interfaceWhen using query interface

Use of SET Keyword

Set pGraphicsContainer = pMap

•• Setting a Setting a ByRefByRef property to property to another objectanother objectSet pMap.SpatialReference = pSR

Set pPoint = New esriCore.Point•• When instantiating an object When instantiating an object

with NEW keywordwith NEW keyword

Set pMap = pMxDoc.FocusMap•• When instantiating an object When instantiating an object

from a property of another from a property of another objectobject

strName = pLayer.Name •• Not necessary for intrinsic Not necessary for intrinsic data typesdata types

Working with Macros Working with Macros –– 1 1

•• A subroutine with A subroutine with public scopepublic scope

•• Create with VBA Create with VBA editoreditor

•• Run macros from Run macros from Tools menu > Tools menu > Macros > MacrosMacros > Macros

Public Sub Stamp()

End Sub

Working with Macros Working with Macros –– 2 2

•• A subroutine with A subroutine with public scopepublic scope

•• Create with VBA Create with VBA editoreditor

•• Run macros from Run macros from Tools menu > Tools menu > Macros > MacrosMacros > Macros

Public Sub Stamp()

End Sub

Methods of VBA Code DistributionMethods of VBA Code Distribution

•• Export to class Export to class file or text filefile or text file

•• Copy/Paste code Copy/Paste code text to text editortext to text editor

ArcObjects ReferencesArcObjects References

•• ArcObjects Online: ArcObjects Online: http://arconline.esri.com/arcobjectsonline/http://arconline.esri.com/arcobjectsonline/

•• Exploring ArcObjects (on Digital Books CD)Exploring ArcObjects (on Digital Books CD)

•• ArcObjects Developer HelpArcObjects Developer Help

•• ESRI Object BrowserESRI Object Browser

ArcObjects TrainingArcObjects Training

•• InstructorInstructor--Led CoursesLed Courses–– Introduction to Programming ArcObjects with VBAIntroduction to Programming ArcObjects with VBA–– Migrating from Avenue to VBAMigrating from Avenue to VBA–– Advanced ArcObjects Component Development IAdvanced ArcObjects Component Development I–– Advanced ArcObjects Component Development II C++Advanced ArcObjects Component Development II C++–– Advanced ArcObjects Component Development II .NETAdvanced ArcObjects Component Development II .NET

•• ESRI Web CoursesESRI Web Courses–– Exploring the VBA Environment (Free)Exploring the VBA Environment (Free)–– Customizing ArcMap: Easy Ways to Extend the InterfaceCustomizing ArcMap: Easy Ways to Extend the Interface–– Introduction to Visual Basic for ESRI SoftwareIntroduction to Visual Basic for ESRI Software–– Working with Variables and Functions in VBAWorking with Variables and Functions in VBA–– Working with Forms in VBAWorking with Forms in VBA–– Understanding Branching and Looping in VBAUnderstanding Branching and Looping in VBA

ArcObjects ReferencesArcObjects References

•• ArcObjects Online: ArcObjects Online: http://arconline.esri.com/arcobjectsonline/http://arconline.esri.com/arcobjectsonline/

•• Exploring ArcObjects (on Digital Books CD)Exploring ArcObjects (on Digital Books CD)

•• ArcObjects Developer HelpArcObjects Developer Help

•• ESRI Object BrowserESRI Object Browser

Demonstration toolbarDemonstration toolbar

Sample code:Sample code:Get selected TOC layer’s fieldsGet selected TOC layer’s fields

when when combobox combobox is clickedis clickedPrivate Sub UIComboBoxControl1_GotFocus()

On Error GoTo ErrorhandlerDim pMxDoc As IMxDocumentDim pFL As IFeatureLayerDim i As Long

Set pMxDoc = ThisDocumentUIComboBoxControl1.RemoveAllUIEditBoxControl1.ClearIf Not TypeOf pMxDoc.SelectedLayer Is IFeatureLayer Then GoTo ExitpntSet pFL = pMxDoc.SelectedLayerFor i = 0 To pFL.FeatureClass.Fields.FieldCount - 1

UIComboBoxControl1.AddItem pFL.FeatureClass.Fields.Field(i).NameNext i

Exitpnt:Set pMxDoc = NothingSet pFL = NothingExit Sub

Errorhandler:Resume Exitpnt

End Sub

Sample code:Sample code:Label selected TOC layer based on chosen Label selected TOC layer based on chosen

combobox combobox fieldfield

Private Sub UIButtonControl1_Click()On Error GoTo ErrorhandlerDim pMxDoc As IMxDocumentDim pGFL As IGeoFeatureLayer

Set pMxDoc = ThisDocumentIf Not TypeOf pMxDoc.SelectedLayer Is IFeatureLayer Then GoTo ExitpntSet pGFL = pMxDoc.SelectedLayerUpdateLabels pGFLpMxDoc.ActiveView.PartialRefresh esriViewGeography, Nothing, _

pMxDoc.ActiveView.ExtentExitpnt:

Set pMxDoc = NothingSet pGFL = NothingExit Sub

Errorhandler:Resume Exitpnt

End Sub

•• For the For the custom custom button click, button click, get selected get selected layer, then layer, then call a call a subroutine subroutine to draw the to draw the labelslabels

Sample code:Sample code:Label selected TOC layer based on chosen Label selected TOC layer based on chosen combobox combobox fieldfield

Private Sub UpdateLabels(pGeoFeatureLayer As IGeoFeatureLayer)On Error GoTo ErrorhandlerDim pLabelEngineLayerProperites As ILabelEngineLayerProperties

If pGeoFeatureLayer.FeatureClass.FindField(UIComboBoxControl1.EditText) = -1 Then GoTo ExitpntIf pGeoFeatureLayer.DisplayAnnotation = True Then

pGeoFeatureLayer.AnnotationProperties.QueryItem 0, pLabelEngineLayerProperitesIf pLabelEngineLayerProperites.Expression = "[" & UIComboBoxControl1.EditText & "]" Then

pGeoFeatureLayer.DisplayAnnotation = FalseElse

If Len(UIComboBoxControl1.EditText) = 0 ThenpGeoFeatureLayer.DisplayAnnotation = False

ElsepLabelEngineLayerProperites.Expression = "[" & UIComboBoxControl1.EditText & "]"

End IfEnd If

ElsepGeoFeatureLayer.AnnotationProperties.QueryItem 0, pLabelEngineLayerProperitespLabelEngineLayerProperites.Expression = "[" & UIComboBoxControl1.EditText & "]"pGeoFeatureLayer.DisplayAnnotation = True

End IfExitpnt:

Set pLabelEngineLayerProperites = NothingExit Sub

Errorhandler:Resume Exitpnt

End Sub

Sample code:Sample code:Filter selected TOC layer based on Filter selected TOC layer based on editbox editbox value for chosen fieldvalue for chosen field

Private Sub UIEditBoxControl1_KeyDown(ByVal keyCode As Long, ByVal shift As Long)On Error GoTo ErrorhandlerDim pMxDoc As IMxDocumentDim pFLD As IFeatureLayerDefinition

If keyCode <> 13 Then GoTo Exitpnt

Set pMxDoc = ThisDocumentIf Not TypeOf pMxDoc.SelectedLayer Is IFeatureLayer Then GoTo ExitpntSet pFLD = pMxDoc.SelectedLayer

If Len(UIComboBoxControl1.EditText) = 0 ThenpFLD.DefinitionExpression = ""

ElsepFLD.DefinitionExpression = UIComboBoxControl1.EditText & " = '" & _

UIEditBoxControl1.Text & "'"End IfIf pMxDoc.SelectedLayer.Visible = False Then

pMxDoc.SelectedLayer.Visible = TruepMxDoc.UpdateContents

End IfpMxDoc.ActiveView.PartialRefresh esriViewGeography, Nothing, _

pMxDoc.ActiveView.ExtentExitpnt:

Set pMxDoc = NothingSet pFLD = NothingExit Sub

Errorhandler:Resume Exitpnt

End Sub

Sample code:Sample code:Label selected TOC layer based on chosen Label selected TOC layer based on chosen combobox combobox fieldfield

Private Function UIToolControl1_Deactivate() As BooleanUIToolControl1_Deactivate = True

End Function

Private Sub UIToolControl1_MouseDown(ByVal button As Long, ByVal shift As Long, ByVal x As Long, ByVal y As Long)Dim pMxApp As IMxApplicationDim pRubberEnv As IRubberBandDim pFillSymbol As ISimpleFillSymbolDim pRubberPolygon As IRubberBandDim pPolygon As IPolygonDim pMxDoc As IMxDocumentDim pTOp As ITopologicalOperator

Continued on next slide ….

Sample code:Sample code:Label selected TOC layer based on chosen Label selected TOC layer based on chosen combobox combobox fieldfield

Set pMxDoc = ThisDocumentSet pMxApp = ApplicationSet pRubberPolygon = New RubberPolygonSet pFillSymbol = New SimpleFillSymbolpFillSymbol.Style = esriSFSHollowSet pPolygon = pRubberPolygon.TrackNew(pMxDoc.ActiveView.ScreenDisplay, pFillSymbol)If pPolygon Is Nothing Then GoTo ExitpntSet pTOp = pPolygonIf pTOp.IsSimple = False Then

MsgBox "Selection polygon cannot self-intersect."GoTo Exitpnt

End IfpMxDoc.FocusMap.SelectByShape pPolygon, pMxApp.SelectionEnvironment, FalsepMxDoc.ActiveView.PartialRefresh esriViewGeoSelection, Nothing, pMxDoc.ActiveView.Extent

Exitpnt:Set pMxApp = NothingSet pRubberEnv = NothingSet pFillSymbol = NothingSet pRubberPolygon = NothingSet pPolygon = NothingSet pMxDoc = Nothing

End Sub

Sample code:Sample code:When ArcMap document opened, collapse all TOC layer When ArcMap document opened, collapse all TOC layer symbology symbology and make all layers visible, regardless of how document was saveand make all layers visible, regardless of how document was savedd

Private Function MxDocument_OpenDocument() As BooleanDim pDoc As IMxDocumentDim pGFL As IGeoFeatureLayerDim pLInfo As ILegendInfoDim pLGrp As ILegendGroupDim i As Long

Set pDoc = ThisDocumentFor i = 0 To pDoc.FocusMap.LayerCount - 1

If TypeOf pDoc.FocusMap.Layer(i) Is IFeatureLayer ThenSet pGFL = pDoc.FocusMap.Layer(i)Set pLInfo = pGFLSet pLGrp = pLInfo.LegendGroup(0)pLGrp.Visible = FalsepGFL.Visible = True

End IfNext ipDoc.UpdateContentspDoc.ActiveView.Refresh

Set pDoc = NothingSet pGFL = NothingSet pLInfo = NothingSet pLGrp = NothingEnd Function

Sample code:Sample code:Create ArcMap extension .dll so when ArcMap document opened, Create ArcMap extension .dll so when ArcMap document opened,

collapse all TOC layer collapse all TOC layer symbology symbology and make all layers visible, and make all layers visible, regardless of how document was savedregardless of how document was saved

Step 1Create newVisual BasicActiveX dll

Sample code:Sample code:Create ArcMap extension .dll so when ArcMap document opened, Create ArcMap extension .dll so when ArcMap document opened,

collapse all TOC layer collapse all TOC layer symbology symbology and make all layers visible, and make all layers visible, regardless of how document was savedregardless of how document was saved

Step 2Establishreferenceto ESRIObjectlibrary

Sample code:Sample code:Create ArcMap extension .dll so when ArcMap document opened, Create ArcMap extension .dll so when ArcMap document opened,

collapse all TOC layer collapse all TOC layer symbology symbology and make all layers visible, and make all layers visible, regardless of how document was savedregardless of how document was saved

Step 3Implement IExtension,establish MxDocument variable WithEvents and establish other necessary module-level variables

Sample code:Sample code:Create ArcMap extension .dll so when ArcMap document opened, Create ArcMap extension .dll so when ArcMap document opened,

collapse all TOC layer collapse all TOC layer symbology symbology and make all layers visible, and make all layers visible, regardless of how document was savedregardless of how document was saved

Step 4Add code to the OpenDocument event to control TOC configuration

Sample code:Sample code:Create ArcMap extension .dll so when ArcMap document opened, Create ArcMap extension .dll so when ArcMap document opened,

collapse all TOC layer collapse all TOC layer symbology symbology and make all layers visible, and make all layers visible, regardless of how document was savedregardless of how document was saved

Step 5Compile with no compatibility then with binary compatibility

Sample code:Sample code:Create ArcMap extension .dll so when ArcMap document opened, Create ArcMap extension .dll so when ArcMap document opened,

collapse all TOC layer collapse all TOC layer symbology symbology and make all layers visible, and make all layers visible, regardless of how document was savedregardless of how document was saved

Step 6Register withESRI Mx ExtensionsCategory usingCategories.exe in the ArcGIS/arcexe83/bindirectory

Sample code:Sample code:Create ArcMap extension .dll so when ArcMap document opened, Create ArcMap extension .dll so when ArcMap document opened,

collapse all TOC layer collapse all TOC layer symbology symbology and make all layers visible, and make all layers visible, regardless of how document was savedregardless of how document was saved

Step 6OR register withESRI Mx ExtensionsCategory using .reg file called from .bat, all in same directory as the extension .dll