Sie sind auf Seite 1von 16

ArcGIS Application

Provides objects to rectify spatial Geo-


data into a known coordinate system. ReferenceUI

Provides user interfaces to


support objects contained
Contains the ArcMap application. ArcMap in the GeoDatabase-
Distributed library.

GeoDatabase-
DistributedUI

Provides user interfaces to support


objects contained in the Location LocationUI
library. EditorExt

Implements ArcMap's object editor,


supporting both a user interface and Contains extension
a programming API. Editor to the ArcMap Editor.

Provides user interfaces


components for ArcMap.
Provides user interfaces to support ArcMapUI
objects contained in the
DataSourcesRaster library.

ArcCatalog
DataSource- Contains the ArcCatalog
Provides user interfaces to support
objects contained in the Carto library.
RasterUI application.

Provides user interfaces to ArcCatalogUI


support objects contained CartoUI OutputUI
in the Catalog library. Application
Assemblies
Provides user interfaces to support Provides user interfaces
Provides user interfaces objects contained in the Output
to support objects
CatalogUI components for ArcCatalog.
library.
contained in the
GeoDatabase library.

Geo- DisplayUI Provides user interfaces to support


DatabaseUI objects in the Display library.

Framework Provides core components to support


User Interface user interface components and applications.
Assemblies

26 • ArcGIS Desktop Developer Guide


Assembly Architecture
Contains the ArcGlobe
application.

Geo- GeoStatistics- Supports the ArcScan


AnalystUI raster to vector
processingUI Spatial- conversion extension
Contains the ArcScene
ArcGlobe
application.
AnalystUI to ArcMap.

ArcScene
Implements the Geoprocessing GlobeCoreUI
Geoprocessing framework in addition to the base
set of Geoprocessing tools. ArcScan

Provides user interfaces


3DAnalystUI components specific to the
ArcGlobe application.

Provides user interfaces to support


objects in the 3DAnalyst library.

Tracking-
Analyst
Survey-
Analyst

Maplex

Supports the Maplex labeling


extension to ArcMap.

Provides user interfaces including


property pages and extensions to
PublisherUI
Provides user interfaces to the ArcMap and ArcCatalog to
support objects contained in
Output- support objects contained in
the OutputExtensions library. ExtentionsUI the Publisher library.

Provides an object that Publisher


supports the creation of
Extends the core output Published Map Files, and the
functionality with more
Output-
creation of Data Packages.
advanced output capabilities. Extentions

DataSources- DataSources-
SMUUI SMEUI
Extention
Assemblies

Chapter 2 • Getting started with VBA and ArcObjects • 27


Reading the illustrated code samples
The illustrated code samples in this section show you the fundamentals of programming with COM
components in ArcObjects. Start by entering the VBA environment in ArcMap or ArcCatalog and type in
the code. Step through the code in the VBA debugger. Look at these pages and study the relationships
between coclasses and interfaces. A careful reading of the samples in this section gives you all the important
concepts you need for developing with ArcObjects, as well as an introduction to the most important
ArcObjects components.

The interface An i n t erf ace i s a sp eci f i cat i on of


QueryInterface
properties and methods. Many coclasses
IFeatureClass : IObjectClass
can i m p l em en t t h e sam e i n t erf ace.
class
AreaField: IField I n t erf aces al l ow a h i gh degree of interface1 method1
FeatureClassID: Long
FeatureDataset: IFeatureDataset
interoperability and shared behavior method2
among a set of objects. QueryInterface
FeatureType: esriFeatureType
LengthField: IField interface2 method3
ShapeFieldName: String AreaField is a return property of type
ShapeType: tagesriGeometryType IField. FeatureClassID is of type long. method4

CreateFeature: IFeature The CreateFeature method creates an


CreateFeatureBuffer: IFeatureBuffer object of type IFeature. FeatureCount QueryInterface is a method in the IUnknown
FeatureCount (in QueryFilter: takes in a query filter and returns a long. interface, which all COM objects inherit
IQueryFilter) : Long
GetFeature (in ID: Long) : IFeature
from. This method lets you query for and
GetFeatures (in fids: Variant, in navigate to methods in other interfaces
Recycling: Boolean) : IFeatureCursor implemented by an object.
Insert (in useBuffering: Boolean) :
IFeatureCursor
Search (in Filter: IQueryFilter, in
Recycling: Boolean) : IFeatureCursor
Select (in QueryFilter: IQueryFilter, in
selType: esriSelectionType, in
Type inheritance
selOption: esriSelectionOption, in
selectionContainer: IWorkspace) :
ISelectionSet
IBoundsProperties Element
Update (in Filter: IQueryFilter, in IClone
Recycling: Boolean) : IFeatureCursor IElement IElement : IUnknown
IElementProperties
IElementProperties2 Geometry: IGeometry
IPersist Locked: Boolean
IPersistStream SelectionTracker:ISelectionTracker
IPropertySupport
Activate (in Display: IDisplay)
ITransform2D
Deactivate
Draw (in Display: IDisplay, in
trackCancel: ITrackCancel)
HitTest (in X: Double, in Y: Double,
The object model diagrams reveal a in Tolerance: Double) : Boolean
structure not evident in standard object QueryBounds (in Display: IDisplay,
in Bounds: IEnvelope)
browsers. Shown here is an abstract QueryOutline (in Display: IDisplay,
Interface inheritance class, Element, with nine interfaces. The in Outline: IPolygon)
IElement interface is shown because a
code sample made a call to it.
IFrameElement:IUnknown

Background: IBackground
IMapFrame and IMapSurroundFrame Border: IBorder
inherit from IF ram eElem ent . All DraftMode: Boolean IGraphicElement
Object: Variant Graphic-
properties and methods of
IFrameElement are accessible to the
Thumbnail: Long
Element
A GraphicElement is an abstract class that specifies
developer who accesses IMapFrame the one interface shown here as well as the nine
or IMapSurroundFrame. interfaces on the Element abstract class.

IMapFrame : IFrameElement IMapSurroundFrame:IFrameElement


IElementEditCallout TextElement
Container: IGraphicsContainer MapFrame: IMapFrame
ExtentType: esriExtentTypeEnum
IElementEditVertices
MapSurround: IMapSurround
LocatorRectangleCount: Long IGroupSymbolElement
Map: IMap ITextElement ITextElement : IUnknown
MapBounds: IEnvelope ITransformEvents
MapScale: Double ScaleText: Boolean
AddLocatorRectangle (in Locator: Symbol: ITextSymbol
ILocatorRectangle) Text: String
CreateSurroundFrame (in CLSID: IUID,
in optionalStyle: IMapSurround) :
IMapSurroundFrame TextElement is a coclass that
LocatorRectangle (in Index: Long) : implements five interfaces in addition
ILocatorRectangle
RemoveAllLocatorRectangles to the one from GraphicElement and
RemoveLocatorRectangle (in Locator: nine fromElement.
ILocatorRectangle)

28 • ArcGIS Desktop Developer Guide


LOCATE AND EXECUTE COMMAND ON TOOLBAR

Locate and Execute Command on Toolbar

This sample illustrates how to


programmatically execute existing
commands on command bars
within ArcMap.

IChangeLayout
IContentsViewEdit
IDataGraphs
MxDocument ArcMapUI
IDocument IDocument : IDispatch
IDocumentDatasets
IDocumentDefaultSymbols Accelerators: IAcceleratorTable
IDocumentDirty CommandBars: ICommandBars
IDocumentDirty2 ID: IUID
IDocumentEvents
IDocumentEventsDisp Parent: IApplication The process is repeated for another
IDocumentInfo
IMxDocument
IPersist
Title: String
Type: esriDocumentType
VBProject: Object
3 command. In this way, several existing
ArcMap commands can be executed
IPropertySupport
IReportUnitFormat with only one click of a button.

To find the command to execute, you can use the CommandBars collection. The
1 command bars collection is a property on the IDocument interface
(ThisDocument). Using the Find method, search using the ArcID module to
provide the command's identifier. The ArcID module has members that can be ICommandBars : IUnknown
identified using the Name property of a command. The convention for naming LargeIcons: Boolean
commands is: <command category> "_" <caption>. ShowToolTips: Boolean

Create (in Name: String, barType:


esriCmdBarType) : ICommandBar
Find (in identifier: Variant, noRecurse:
Boolean, noCreate: Boolean) :
ICommandItem
ICommandItem : IUnknown HideAllToolbars

Action: String
BuiltIn: Boolean
Caption: String
Category: String
Command: ICommand
FaceID: Variant
Group: Boolean
HelpContextID: Long
HelpFile: String
Framework
ID: IUID
Index: Long
Message: String
Name: String
Parent: ICommandBar
Style: esriCommandStyles
Tag: String
Tooltip: String
Type: esriCommandTypes
Delete Assuming a valid command
Execute
Refresh
2 item is returned from the find,
the command is executed by
Reset
calling the Execute method.

Add this code to the Click event of a command in ArcMap.


Dim pCommandItem As ICommandItem

1 Set pCommandItem = ThisDocument.CommandBars.Find(ArcID.Query_ZoomToSelected)


If (pCommandItem Is Nothing) Then Exit Sub
2 pCommandItem.Execute

3 Set pCommandItem = ThisDocument.CommandBars.Find(ArcID.ReportObject_CreateReport)


If (pCommandItem Is Nothing) Then Exit Sub
pCommandItem.Execute

Chapter 2 • Getting started with VBA and ArcObjects • 29


DRAW DIGITIZED LINE ON SCREEN

This sample uses a rubber banding line to


obtain a digitized line geometry. With the
geometry created, a symbol is created. The
symbol is set as the current display symbol
and the line is drawn. The color thickness
and the style of the line symbol are set.
IDisplay : IUnknown
ClipEnvelope: IEnvelope
ClipEnvelopes: ISet Finally, the geometry is drawn on the
ClipGeometry: IGeometry
DisplayTransformation:
screen. Notice the call to start
IDisplayTransformation drawing followed by the setting of
The IMxDocument interface is used Filter: IDisplayFilter
the symbol, and then the actual
1 to retrieve the currently active view,
which can be a Map or a PageLayout.
hDC: Long
hPalette: Long
IlluminationProps: IIlluminationProps
drawing of the geometry.
SuppressEvents: Boolean FinishDrawing ensures the
IChangeLayout DrawMultipoint (in Multipoint: synchronization of the drawing
IContentsViewEdit MxDocument IGeometry)
DrawPoint (in Point: IGeometry)
events.
IDataGraphs
IDocument DrawPolygon (in Polygon: IGeometry)
IDocumentDatasets DrawPolyline (in Polyline: IGeometry)
IDocumentDefaultSymbols
IDocumentDirty
IDocumentDirty2
DrawRectangle (in rectangle:
IEnvelope)
DrawText (in Shape: IGeometry, in
5
Text: String)
IDocumentEvents FinishDrawing
IDocumentEventsDisp Progress (in VertexCount: Long)
IDocumentInfo IMxDocument : IUnknown IActiveView : IUnknown
SetSymbol (in sym: ISymbol)
IMxDocument
IPersist ActivatedView: IActiveView ExportFrame: tagRECT StartDrawing (in hDC: Long, in
Extent: IEnvelope cacheID: Integer)
IPropertySupport ActiveView: IActiveView
IReportUnitFormat ActiveViewCommand: ICommand ExtentStack: IExtentStack
ContentsView (in Index: Long) : FocusMap: IMap
IContentsView FullExtent: IEnvelope
ContentsViewCount: Long
ContextItem: IUnknown Pointer
CurrentContentsView: IContentsView
GraphicsContainer: IGraphicsContainer
IsMapActivated: Boolean
ScreenCacheID (in phase:
IScreenDisplay : IDisplay 2
tagesriViewDrawPhase, in data: ActiveCache: Integer
CurrentLocation: IPoint
DefaultColor (in Type: IUnknown Pointer) : Integer CacheCount: Integer Since the IScreenDisplay interface
ScreenDisplay: IScreenDisplay CacheMemDC (in Index: Integer) : Long
tagesriMxDefaultColorTypes) : IColor
Selection: ISelection CancelTracker: ITrackCancel of the active view is to be used
DefaultTextFont: Font
DefaultTextFontSize: IFontSize ShowRulers: Boolean hWnd: Long frequently within the function, a
DelayUpdateContents: Boolean ShowScrollBars: Boolean IsFirstCacheTransparent: Boolean
ShowSelection: Boolean IsFramed: Boolean local variable is used.
FocusMap: IMap
TipText (in X: Double, in Y: Double) : ScaleContents: Boolean
Maps: IMaps
String SuppressResize: Boolean
OperationStack: IOperationStack
UseScrollbars: Boolean
PageLayout: IPageLayout Activate (hWnd: Long) WindowDC: Long
RelativePaths: Boolean Clear
SearchTolerance: Double ContentsChanged AddCache: Integer
SearchTolerancePixels: Long Deactivate DoScroll (in xDelta: Long, in yDelta:
SelectedItem: IUnknown Pointer Draw (in hDC: Long, in trackCancel: Long, in updateScreen: Boolean)
SelectedLayer: ILayer ITrackCancel) DrawCache (in hDC: Long, in Index:
StyleGallery: IStyleGallery GetContextMenu (in X: Double, in Y: Integer, in deviceRect: tagRECT, in
TableProperties: ITableProperties Double, out clsidMenu: IUID) cacheRect: tagRECT)
HitTestMap (in Location: IPoint) : IMap Invalidate (in rect: IEnvelope, in erase:
AddLayer (in Layer: ILayer) Boolean, in cacheIndex: Integer)
IsActive: Boolean
CanInsertObject (pEnabled: Boolean) IsCacheDirty (in cacheIndex: Integer) :
OnMessage (in msg: Unsigned Long, in Boolean
InsertObject wParam: Unsigned Machine Int, in
UpdateContents PanMoveTo (in mouseLocation: IPoint)
lParam: Long)
PanStart (in mouseLocation: IPoint)
Output (in hDC: Long, in dpi: Long, in
PixelBounds: tagRECT, in PanStop: IEnvelope
VisibleBounds: IEnvelope, in RemoveAllCaches
trackCancel: ITrackCancel) RemoveCache (in cacheID: Integer)
RotateMoveTo (in pPoint: IPoint)
ArcMapUI PartialRefresh (in phase:
tagesriViewDrawPhase, in data:
IUnknown Pointer, in Envelope:
IEnvelope)
RotateStart (in mousePt: IPoint, in
centerPt: IPoint)
RotateStop: Double
PrinterChanged (in Printer: IPrinter) RotateTimer
Refresh SetScrollbarHandles (in
hWndHorzScrollbar: Long, in
hWndVertScrollbar: Long)
StartRecording
StopRecording
TrackPan
TrackRotate
UpdateWindow
IRubberBand RubberBand
IRubberBand : IUnknown

TrackExisting (in ScreenDisplay:


IPolyline : IPolycurve IScreenDisplay, in Symbol: ISymbol,
in Geometry: IGeometry) : Boolean
TrackNew (in ScreenDisplay:
Reshape (reshapeSource: IPath) : IScreenDisplay, in Symbol: ISymbol)
Boolean : IGeometry
SimplifyNetwork

3
A RubberLine object is used to capture a RubberLine
digitized line geometry from the user. The
TrackNew method takes the screen to draw
to and the symbol to draw with and returns
the created geometry.

30 • ArcGIS Desktop Developer Guide


ILineSymbol LineSymbol
IMapLevel
IPropertySupport ILineSymbol : IUnknown
Color: IColor
Width: Double

ISimpleLineSymbol
SimpleLineSymbol
ISimpleLineSymbol : ILineSymbol

Style: tagesriSimpleLineStyle

Color
Display
IClone
IColor IColor : IUnknown
IPersist
IPersistStream CMYK: Long To draw a geometry on the screen, an appropriate symbol is required.
NullColor: Boolean
RGB: Long 4 This symbol instructs the screen how to draw the geometry. This step
creates a SimpleLineSymbol object and sets its properties. The Color
Transparency: Unsigned Char
UseWindowsDithering: Boolean of the Line is defined by creating an RGBColor object and setting its
GetCIELAB (out l: Double, out a: Red, Green, and Blue properties.
Double, out b: Double)
SetCIELAB (in l: Double, in a:
Double, in b: Double)

RGBColor
IRGBColor IRgbColor : IColor

Blue: Long
Green: Long
Red: Long

Add this to the MouseDown event of a tool in ArcMap.


1 Dim pMxDoc As IMxDocument
Set pMxDoc = ThisDocument

2 Dim pScreen As IScreenDisplay


Set pScreen = pMxDoc.ActiveView.ScreenDisplay

3 Dim pPolyline As IPolyline


Dim pRubber As IRubberBand
Set pRubber = New RubberLine
Set pPolyline = pRubber.TrackNew(pScreen, Nothing)

4 Dim pLineSymbol As ISimpleLineSymbol


Set pLineSymbol = New SimpleLineSymbol

Dim pRGBColor As IRgbColor


Set pRGBColor = New RgbColor
With pRGBColor
.Red = 255
.Green = 128
.Blue = 128
End With

With pLineSymbol
.Width = 2
.Color = pRGBColor
.Style = esriSLSSolid
End With

5 With pScreen
.StartDrawing pScreen.hDC, esriNoScreenCache
.SetSymbol pLineSymbol
.DrawPolyline pPolyline
.FinishDrawing
End With

Chapter 2 • Getting started with VBA and ArcObjects • 31


ADD FEATURE CLASS TO ARCMAP

IDataset
This sample opens a shapefile on the user's IDatabaseCompact (optional) Workspace
IDatabaseConnectionInfo (optional)
IDatasetContainer
local disk and adds the contents to the map IFeatureWorkspace IFeatureWorkspace : IUnknown
IFeatureWorkspaceAnno (optional)
as a feature layer. The default symbology is IFeatureWorkspaceManage CreateFeatureClass (in Name: String, in
IFeatureWorkspaceManage2 Fields: IFields, in CLSID: IUID, in
used. This sample could easily be changed IFeatureWorkspaceSchemaEdit EXTCLSID: IUID, in FeatureType:
IGeodatabaseRelease (optional) esriFeatureType, in ShapeFieldName:
to support different data sources. ISpatialCacheManager String, in ConfigKeyword: String) :
ISpatialCacheManager2 IFeatureClass
ISQLSyntax CreateFeatureDataset (in Name:
ITransactions (optional) String, in SpatialReference:
ITransactionsOptions (optional) ISpatialReference) : IFeatureDataset
CreateQueryDef: IQueryDef
WorkspaceFactory IWorkspace
IWorkspace2 CreateRelationshipClass (in
relClassName: String, in OriginClass:
IWorkspaceFactory IWorkspaceFactory : IUnknown IWorkspaceConfiguration (optional) IObjectClass, in DestinationClass:
IWorkspaceFactory2 (optional) IWorkspaceDomains (optional) IObjectClass, in forwardLabel: String,
ILocalDatabaseCompact (optional) WorkspaceDescription (in plural: IWorkspaceDomains2 (optional) in backwardLabel: String, in
RemoteDeatabaseWorkspaceFactory (optional) Boolean) : String IWorkspaceEdit Cardinality: esriRelCardinality, in
ISetDefaultConnectionInfo (optional) WorkspaceType: esriWorkspaceType IWorkspaceEditEvents Notification: esriRelNotification, in
ISetDefaultConnectionInfo2 (optional) IsComposite: Boolean, in IsAttributed:
IWorkspaceExtentionManager (optional)
ContainsWorkspace (in IWorkspaceProperties (optional) Boolean, in relAttrFields: IFields, in
parentDirectory: String, in fileNames: IWorkspaceSpatialReferenceInfo OriginPrimaryKey: String, in
IFileNames) : Boolean destPrimaryKey: String, in
Copy (in WorkspaceName: OriginForeignKey: String, in
IWorkspaceName, in destinationFolder:
String, out workspaceNameCopy:
IWorkspaceName) : Boolean
2 The OpenFromFile method returns
a reference to a workspace.
destForeignKey: String) :
IRelationshipClass
CreateTable (in Name: String, in Fields:
Create (in parentDirectory: String, in IFields, in CLSID: IUID, in EXTCLSID:
A Workspace object contains an IUID, in ConfigKeyword: String) : ITable
Name: String, in ConnectionProperties:
IPropertySet, in hWnd: Long) :
IWorkspaceName
IFeatureWorkspace interface. This
has an OpenFeatureClass method
3 OpenFeatureClass (in Name: String) :
IFeatureClass
GetClassID: IUID OpenFeatureDataset (in Name: String)
that returns a FeatureClass. : IFeatureDataset
GetWorkspaceName (in
parentDirectory: String, in fileNames: OpenFeatureQuery (in queryName:
IFileNames) : IWorkspaceName IDataset String, in pQueryDef: IQueryDef) :
IsWorkspace (in FileName: String) : IDatasetAnalyze IFeatureDataset
(optional)
Boolean IDatasetEdit Dataset OpenRelationshipClass (in Name:
Move (in WorkspaceName: IDatasetEditInfo String) : IRelationshipClass
IWorkspaceName, in ISchemaLock OpenRelationshipQuery (in pRelClass:
destinationFolder: String) : Boolean (optional) IRelationshipClass, in joinForward:
Open (in ConnectionProperties: Boolean, in pSrcQueryFilter:
IPropertySet, in hWnd: Long) : IQueryFilter, in pSrcSelectionSet:
IWorkspace ISelectionSet, in TargetColumns:
IClass String, in DoNotPushJoinToDB:
OpenFromFile (in FileName: String, in
hWnd: Long) : IWorkspace
ITable
ITableCapabilities
Table Boolean) : ITable
ReadConnectionPropertiesFromFile (in OpenTable (in Name: String) : ITable
FileName: String) : IPropertySet

IClassSchemaEdit (optional)
IClassSchemaEdit2 (optional) ObjectClass
IModelInfo (optional)
IObjectClass IObjectClass : IClass
Shapefile- IObjectClassEvents
IObjectClassInfo (optional)
Workspace- AliasName: String
IObjectClassInfo2 (optional)
ObjectClassID: Long
Factory IObjectClassSchemaEvents
ISubtypes (optional) RelationshipClasses (in
IValidation (optional) role: esriRelRole) :
1 IValidation2 (optional) IEnumRelationshipClass

The ShapefileWorkspaceFactory
coclass creates a shapefile
workspace factory object.
Geodatabase FeatureClass
IFeatureClass IFeatureClass : IObjectClass
IFeatureClassLoad (optional) AreaField: IField
IFeatureClassWrite FeatureClassID: Long
IGeoDataset FeatureDataset: IFeatureDataset
INetworkClass FeatureType: esriFeatureType
LengthField: IField
ShapeFieldName: String
ShapeType: tagesriGeometryType
CreateFeature: IFeature
CreateFeatureBuffer: IFeatureBuffer
FeatureCount (in QueryFilter:
IQueryFilter) : Long
GetFeature (in ID: Long) : IFeature
GetFeatures (in fids: Variant, in
Recycling: Boolean) : IFeatureCursor
Insert (in useBuffering: Boolean) :
IFeatureCursor
Search (in Filter: IQueryFilter, in
Recycling: Boolean) : IFeatureCursor
Select (in QueryFilter: IQueryFilter, in
selType: esriSelectionType, in
selOption: esriSelectionOption, in
selectionContainer: IWorkspace) :
ISelectionSet
Update (in Filter: IQueryFilter, in
Recycling: Boolean) : IFeatureCursor

32 • ArcGIS Desktop Developer Guide


6 IChangeLayout
IContentsViewEdit
IDataGraphs
IDocument
MxDocument
IDocumentDatasets
The IMxDocument interface is obtained IDocumentDefaultSymbols
from the ThisDocument global variable. IDocumentDirty
IDocumentDirty2
IDocumentEvents
IDocumentEventsDisp
IDocumentInfo IMxDocument : IUnknown IActiveView : IUnknown
IMxDocument
IPersist ActivatedView: IActiveView ExportFrame: tagRECT
IPropertySupport
IReportUnitFormat ActiveView: IActiveView Extent: IEnvelope
ActiveViewCommand: ICommand ExtentStack: IExtentStack
FocusMap: IMap
ArcMapUI ContentsView (in Index: Long) :
IContentsView
ContentsViewCount: Long
ContextItem: IUnknown Pointer
FullExtent: IEnvelope
GraphicsContainer: IGraphicsContainer
IsMapActivated: Boolean
CurrentContentsView: IContentsView ScreenCacheID (in phase:
IGeoDataset
CurrentLocation: IPoint tagesriViewDrawPhase, in data:
5 ILayer
IPersist
IPersistStream
ILayer : IUnknown
AreaOfInterest: IEnvelope
DefaultColor (in Type:
tagesriMxDefaultColorTypes) : IColor
IUnknown Pointer) : Integer
ScreenDisplay: IScreenDisplay
Cached: Boolean DefaultTextFont: Font Selection: ISelection
The Name property is set MaximumScale: Double DefaultTextFontSize: IFontSize ShowRulers: Boolean
DelayUpdateContents: Boolean ShowScrollBars: Boolean
to display the layer name in MinimumScale: Double
FocusMap: IMap ShowSelection: Boolean
the ArcMap table of Name: String TipText (in X: Double, in Y: Double) :
Maps: IMaps
ShowTips: Boolean String
contents. Notice that SpatialReference: ISpatialReference
OperationStack: IOperationStack
although the Name Layer
SupportedDrawPhases: Long
PageLayout: IPageLayout Activate (hWnd: Long)
RelativePaths: Boolean Clear
property is on the ILayer TipText (in X: Double, in Y: Double, SearchTolerance: Double
interface, it is accessed in Tolerance: Double) : String ContentsChanged
Valid: Boolean SearchTolerancePixels: Long Deactivate
directly via the Visible: Boolean SelectedItem: IUnknown Pointer
Draw (in hDC: Long, in trackCancel:
IFeatureLayer interface SelectedLayer: ILayer ITrackCancel)
Draw (in drawPhase: StyleGallery: IStyleGallery GetContextMenu (in X: Double, in Y:
due to interface inheritance. tagesriDrawPhase, in Display: TableProperties: ITableProperties Double, out clsidMenu: IUID)
IDisplay, in trackCancel: HitTestMap (in Location: IPoint) : IMap
ITrackCancel) AddLayer (in Layer: ILayer)
CanInsertObject (pEnabled: Boolean) IsActive: Boolean
InsertObject OnMessage (in msg: Unsigned Long,
UpdateContents in wParam: Unsigned Machine Int, in
lParam: Long)
IAttributeTable Output (in hDC: Long, in dpi: Long, in
IClass FeatureLayer PixelBounds: tagRECT, in
IDataLayer VisibleBounds: IEnvelope, in
IDataLayer2 trackCancel: ITrackCancel)
IDataset The AddLayer method on the
IDisplayAdmin
IDisplayFilterManager
IDisplayRelationshipClass
7 IMxDocument interface adds the
FeatureLayer object to ArcMap.
PartialRefresh (in phase:
tagesriViewDrawPhase, in data:
IUnknown Pointer, in Envelope:
IDisplayTable IEnvelope)
IFeatureLayer IFeatureLayer : ILayer PrinterChanged (in Printer: IPrinter)
IFeatureLayer2
IFeatureLayerDefinition
Refresh
DataSourceType: String
IFeatureLayerSelectionEvents
IFeatureSelection
DisplayField: String
IFind FeatureClass: IFeatureClass
IGeoFeatureLayer ScaleSymbols: Boolean Finally, the newly added layer is drawn on the
IHotlinkContainer
IHotlinkMacro
IHyperlinkContainer
Selectable: Boolean 8 screen. Notice the use of the PartialRefresh
method instead of the Refresh method; this
IIdentify Search (in QueryFilter:
IIdentify2 IQueryFilter, in Recycling: ensures optimal drawing of all the map layers.
ILayer2 Boolean) : IFeatureCursor
ILayerDrawingProperties
ILayerEffects
ILayerEvents
ILayerExtensions
ILayerFields
ILayerInfo
ILayerPosition
ILegendInfo
IMapLevel Add this code to the Click event of a UIButtonControl in ArcMap.
IObjectClassSchemaEvents
IPropertySupport
IRelationshipClassCollection 1 Dim pWorkspaceFactory As IWorkspaceFactory
IRelationshipClassCollectionEdit
ITable Set pWorkspaceFactory = New ShapefileWorkspaceFactory
ITableFields
ITableSelection
2 Dim pWorkSpace As IFeatureWorkspace
Set pWorkSpace = pWorkspaceFactory.OpenFromFile("C:\Source\", 0)
In order to add data to the map,
4 create a FeatureLayer and
associate the FeatureClass with it.
3 Dim pClass As IFeatureClass
Set pClass = pWorkSpace.OpenFeatureClass("USStates")

4 Dim pLayer As IFeatureLayer


Set pLayer = New FeatureLayer
Set pLayer.FeatureClass = pClass
5 pLayer.Name = pClass.AliasName

6 Dim pMxDoc As IMxDocument


Set pMxDoc = ThisDocument

7 pMxDoc.AddLayer pLayer
8 pMxDoc.ActiveView.PartialRefresh esriViewGeography, pLayer, _
Nothing

Chapter 2 • Getting started with VBA and ArcObjects • 33


ADD LAYER TO ARCMAP USING GXDIALOG

IMap : IUnknown

This example allows the user to select a ActiveGraphicsLayer: ILayer


AnnotationEngine: IAnnotateMap
feature dataset or feature class to be added AreaOfInterest: IEnvelope
Barriers (pExtent: IEnvelope) :
IBarrierCollection
to ArcMap using the GxDialog. BasicGraphicsLayer: IGraphicsLayer
ClipBorder: IBorder
ClipGeometry: IGeometry
Description: String
DistanceUnits: esriUnits
Expanded: Boolean
FeatureSelection: ISelection
IsFramed: Boolean
Layer (in Index: Long) : ILayer
LayerCount: Long
To obtain the active map, use the FocusMap Layers (UID: IUID, recursive: Boolean)

1 property of the IMxDocument interface.


: IEnumLayer
MapScale: Double
MapSurround (in Index: Long) :

ArcMapUI IMapSurround
MapSurroundCount: Long
MapUnits: esriUnits
Name: String
IChangeLayout ReferenceScale: Double
IContentsViewEdit
IDataGraphs
MxDocument SelectionCount: Long
SpatialReference: ISpatialReference
IDocument SpatialReferenceLocked: Boolean
IDocumentDatasets UseSymbolLevels: Boolean
IDocumentDefaultSymbols
IDocumentDirty AddLayer (in Layer: ILayer)
IDocumentDirty2 AddLayers (in Layers: IEnumLayer, in
IDocumentEvents autoArrange: Boolean)
IDocumentEventsDisp AddMapSurround (in MapSurround:
IDocumentInfo IMapSurround)
IMxDocument : IUnknown ClearLayers
IMxDocument
IPersist ClearMapSurrounds
ActivatedView: IActiveView
IPropertySupport ClearSelection
ActiveView: IActiveView
IReportUnitFormat ComputeDistance (in p1: IPoint, in p2:
ActiveViewCommand: ICommand IPoint) : Double
ContentsView (in Index: Long) : The GxDialog coclass provides the user CreateMapSurround (in CLSID: IUID, in
IContentsView
ContentsViewCount: Long
ContextItem: IUnknown Pointer
CurrentContentsView: IContentsView
2 interface used by all ArcGIS applications
when selecting data sources.
optionalStyle: IMapSurround) :
IMapSurround
DelayDrawing (in delay: Boolean)
DelayEvents (in delay: Boolean)
CurrentLocation: IPoint DeleteLayer (in Layer: ILayer)
DefaultColor (in Type: DeleteMapSurround (in MapSurround:
tagesriMxDefaultColorTypes) : IColor IMapSurround)
DefaultTextFont: Font GetPageSize (out widthInches: Double,
DefaultTextFontSize: IFontSize out heightInches: Double)
DelayUpdateContents: Boolean MoveLayer (in Layer: ILayer, in toIndex:
FocusMap: IMap Long)
Maps: IMaps GxDialog RecalcFullExtent
SelectByShape (in Shape: IGeometry,
OperationStack: IOperationStack
PageLayout: IPageLayout in env: ISelectionEnvironment, in
IGxDialog IGxDialog : IUnknown justOne: Boolean)
RelativePaths: Boolean IGxObjectFilterCollection SelectFeature (in Layer: ILayer, in
SearchTolerance: Double IGxSelectionEvents Feature: IFeature)
SearchTolerancePixels: Long
AllowMultiSelect: Boolean
SetPageSize (in widthInches: Double, in
SelectedItem: IUnknown Pointer ButtonCaption: String heightInches: Double)
SelectedLayer: ILayer FinalLocation: IGxObject
StyleGallery: IStyleGallery InternalCatalog: IGxCatalog
TableProperties: ITableProperties Name: String
AddLayer (in Layer: ILayer) ObjectFilter: IGxObjectFilter
CanInsertObject (pEnabled: Boolean) RememberLocation: Boolean
InsertObject
UpdateContents ReplacingObject: Boolean
StartingLocation: Variant 4
Title: String
The DoModalOpen method on
DoModalOpen (in
parentWindow: Long, out the IGxDialog interface is called
To limit the data sources available for selection Selection: IEnumGxObject)
IActiveView : IUnknown
3 within the dialog box, a GxObjectFilter is
used. For this example, the filter only allows
: Boolean
DoModalSave (in
to display the GxDialog. Once the
user has finished, the selected
parentWindow: Long) : feature classes can be accessed via
ExportFrame: tagRECT feature classes to be selected. Using filters Boolean
Extent: IEnvelope the GxObject enumerator that is
ExtentStack: IExtentStack simplifies the code after the selection is made.
FocusMap: IMap
passed out of the method call.
FullExtent: IEnvelope
GraphicsContainer: IGraphicsContainer
IsMapActivated: Boolean
ScreenCacheID (in phase:
CatalogUI
tagesriViewDrawPhase, in data:
IUnknown Pointer) : Integer GxFilterFeatureClasses
ScreenDisplay: IScreenDisplay
Selection: ISelection IGxObjectFilter IGxObjectFilter : IUnknown
ShowRulers: Boolean
ShowScrollBars: Boolean Description: String
ShowSelection: Boolean
TipText (in X: Double, in Y: Double) :
Name: String
String
Activate (hWnd: Long) CanChooseObject (in Object:
Clear IGxObject, result:
ContentsChanged tagesriDoubleClickResult) : Boolean
Deactivate CanDisplayObject (in Object:
Draw (in hDC: Long, in trackCancel: IGxObject) : Boolean
ITrackCancel)
GetContextMenu (in X: Double, in Y: CanSaveObject (in Location:
Double, out clsidMenu: IUID) IGxObject, in newObjectName:
HitTestMap (in Location: IPoint) : IMap String, objectAlreadyExists:
IsActive: Boolean Boolean) : Boolean
OnMessage (in msg: Unsigned Long, in
wParam: Unsigned Machine Int, in
lParam: Long)
Output (in hDC: Long, in dpi: Long, in 8 5
PixelBounds: tagRECT, in
VisibleBounds: IEnvelope, in If the enumerator is nothing, no selections
trackCancel: ITrackCancel) Finally, the newly added layer is drawn on the IEnumGxObject : IUnknown
PartialRefresh (in phase: were made and the sub is exited.
tagesriViewDrawPhase, in data: screen. Notice the use of the PartialRefresh
IUnknown Pointer, in Envelope: Otherwise, the enumerator is reset in
IEnvelope) method instead of the Refresh method; this Next: IGxObject
preparation for its iteration.
PrinterChanged (in Printer: IPrinter) ensures optimal drawing of all the map layers. Reset
Refresh

34 • ArcGIS Desktop Developer Guide


Layer
IGeoDataset
ILayer ILayer : IUnknown

7 IPersist
IPersistStream
AreaOfInterest: IEnvelope
Cached: Boolean
IPublishLayer

The enumerator is iterated over


MaximumScale: Double
MinimumScale: Double
Geodatabase
Name: String
and for each GxObject ShowTips: Boolean
IObjectClass : IClass
accessed, a FeatureLayer object SpatialReference: ISpatialReference
SupportedDrawPhases: Long
is created that is associated with TipText (in X: Double, in Y: Double, in
AliasName: String
the FeatureClass. Notice that Tolerance: Double) : String ObjectClassID: Long
Valid: Boolean
the Dataset property of the Visible: Boolean RelationshipClasses (in
role: esriRelRole) :
GxDataset is assigned to the Draw (in drawPhase: IEnumRelationshipClass
tagesriDrawPhase, in Display:
FeatureClass property of the IDisplay, in trackCancel:
ITrackCancel)
Layer.

IFeatureClass : IObjectClass

IAttributeTable AreaField: IField


IClass FeatureLayer FeatureClassID: Long
FeatureDataset: IFeatureDataset
IDataLayer
IDataLayer2 FeatureType: esriFeatureType
IDataset LengthField: IField
IDisplayAdmin ShapeFieldName: String
IDisplayFilterManager ShapeType: tagesriGeometryType
IDisplayRelationshipClass
CreateFeature: IFeature
IDisplayTable
IFeatureLayer IFeatureLayer : ILayer CreateFeatureBuffer: IFeatureBuffer
IFeatureLayer2 FeatureCount (in QueryFilter:
IQueryFilter) : Long
IFeatureLayerDefinition DataSourceType: String GetFeature (in ID: Long) : IFeature
IFeatureLayerSelectionEvents
IFeatureSelection
DisplayField: String GetFeatures (in fids: Variant, in
FeatureClass: IFeatureClass Recycling: Boolean) : IFeatureCursor
IFind Insert (in useBuffering: Boolean) :
IGeoFeatureLayer ScaleSymbols: Boolean IFeatureCursor
IHotlinkContainer Selectable: Boolean Search (in Filter: IQueryFilter, in
IHotlinkMacro Recycling: Boolean) : IFeatureCursor
IHyperlinkContainer Select (in QueryFilter: IQueryFilter, in
IIdentify Search (in QueryFilter: selType: esriSelectionType, in
IIdentify2 IQueryFilter, in Recycling: selOption: esriSelectionOption, in
ILayer2 Boolean) : IFeatureCursor selectionContainer: IWorkspace) :
ILayerDrawingProperties ISelectionSet
ILayerEffects Update (in Filter: IQueryFilter, in
ILayerEvents Recycling: Boolean) : IFeatureCursor
ILayerExtensions
ILayerFields
ILayerInfo
ILayerPosition
ILegendInfo
IMapLevel
IObjectClassSchemaEvents
IPropertySupport
IRelationshipClassCollection
IRelationshipClassCollectionEdit
ITable
ITableFields
ITableSelection Add this to the Click event of a UIButtonControl in ArcMap.
1 Dim pMxDoc As IMxDocument
Set pMxDoc = ThisDocument
Carto 2 Dim pGxDialog As IGxDialog
Set pGxDialog = New GxDialog
pGxDialog.AllowMultiSelect = True
pGxDialog.Title = "Select Feature Classes to Add to Map"

3 Dim pGxFilter As IGxObjectFilter


Set pGxFilter = New GxFilterFeatureClasses
Set pGxDialog.ObjectFilter = pGxFilter

4 Dim pGxObjects As IEnumGxObject


pGxDialog.DoModalOpen ThisDocument.Parent.hWnd, pGxObjects
IGxDataset : IUnknown

Dataset: IDataset 5 If (pGxObjects Is Nothing) Then Exit Sub


DatasetName: IDatasetName pGxObjects.Reset
Type: esriDatasetType
Dim pLayer As IFeatureLayer
Dim pGxDataset As IGxDataset
6 Set pGxDataset = pGxObjects.Next
Since an appropriate GxObjectFilter Do Until (pGxDataset Is Nothing)
6 object was used, the GxObjects returned
from the enumerator will support the
7 Set pLayer = New FeatureLayer
Set pLayer.FeatureClass = pGxDataset.Dataset
IGxDataset interface. pLayer.Name = pLayer.FeatureClass.AliasName
pMxDoc.FocusMap.AddLayer pLayer
Set pGxDataset = pGxObjects.Next
Loop
8 pMxDoc.ActiveView.PartialRefresh esriViewGeography, _
Nothing, Nothing

Chapter 2 • Getting started with VBA and ArcObjects • 35


STYLE GALLERY AUTO SYMBOL SELECTION

This sample goes through all polygon layers in the An enumerator is obtained from the style gallery for the style
map and attempts to match the symbology from 2 gallery's FillSymbol entries that, when accessed, will loop over
all the FillSymbols.
the standard style set to the layer name. ArcMap
does this by default. Therefore, to see a real
difference before testing the tool, layer names IStyleGallery : IUnknown
should be changed to reflect suitable styles. For Categories (in ClassName: String) :
IEnumBSTR
example, try changing a layer name to "Glacier" and Class (in Index: Long) :
IStyleGalleryClass
executing this command. ClassCount: Long
Items (in ClassName: String, in
styleSet: String, in Category: String) :
IEnumStyleGalleryItem
AddItem (in Item: IStyleGalleryItem)
Clear
ImportStyle (in FileName: String)
LoadStyle (in FileName: String, in
To begin, you must gain access to ClassName: String)
1 the current document. RemoveItem (in Item:
IStyleGalleryItem)
SaveStyle (in FileName: String, in
styleSet: String, in ClassName: String)
UpdateItem (in Item: IStyleGalleryItem)

IChangeLayout
IContentsViewEdit MxDocument
IDataGraphs
IDocument
IDocumentDatasets
IDocumentDefaultSymbols
IDocumentDirty
IDocumentDirty2
ArcMapUI
IDocumentEvents
IDocumentEventsDisp
IDocumentInfo IMap : IUnknown
IMxDocument : IUnknown
IMxDocument ActiveGraphicsLayer: ILayer
IPersist ActivatedView: IActiveView
IPropertySupport AnnotationEngine: IAnnotateMap
ActiveView: IActiveView AreaOfInterest: IEnvelope
IReportUnitFormat ActiveViewCommand: ICommand Barriers (pExtent: IEnvelope) :
ContentsView (in Index: Long) : IBarrierCollection
IContentsView BasicGraphicsLayer: IGraphicsLayer
ContentsViewCount: Long ClipBorder: IBorder
ContextItem: IUnknown Pointer ClipGeometry: IGeometry
CurrentContentsView: IContentsView Description: String
CurrentLocation: IPoint DistanceUnits: esriUnits
DefaultColor (in Type: Expanded: Boolean
tagesriMxDefaultColorTypes) : IColor FeatureSelection: ISelection
DefaultTextFont: Font IsFramed: Boolean
DefaultTextFontSize: IFontSize
Layer (in Index: Long) : ILayer
DelayUpdateContents: Boolean
LayerCount: Long
FocusMap: IMap
Maps: IMaps
OperationStack: IOperationStack
PageLayout: IPageLayout
3 Layers (UID: IUID, recursive: Boolean)
: IEnumLayer
MapScale: Double
MapSurround (in Index: Long) :
RelativePaths: Boolean
SearchTolerance: Double Using the IMap layer properties, IMapSurround
MapSurroundCount: Long
SearchTolerancePixels: Long loop over all the layers in the MapUnits: esriUnits
SelectedItem: IUnknown Pointer Name: String
SelectedLayer: ILayer map. ReferenceScale: Double
IActiveView : IUnknown StyleGallery: IStyleGallery SelectionCount: Long
TableProperties: ITableProperties SpatialReference: ISpatialReference
ExportFrame: tagRECT
Extent: IEnvelope AddLayer (in Layer: ILayer) SpatialReferenceLocked: Boolean
ExtentStack: IExtentStack CanInsertObject (pEnabled: Boolean) UseSymbolLevels: Boolean
FocusMap: IMap InsertObject AddLayer (in Layer: ILayer)
FullExtent: IEnvelope UpdateContents AddLayers (in Layers: IEnumLayer, in
GraphicsContainer: IGraphicsContainer autoArrange: Boolean)
IsMapActivated: Boolean AddMapSurround (in MapSurround:
ScreenCacheID (in phase: IMapSurround)
tagesriViewDrawPhase, in data: ClearLayers
IUnknown Pointer) : Integer ClearMapSurrounds
ScreenDisplay: IScreenDisplay ClearSelection
Selection: ISelection ComputeDistance (in p1: IPoint, in p2:
ShowRulers: Boolean IPoint) : Double
ShowScrollBars: Boolean CreateMapSurround (in CLSID: IUID, in
ShowSelection: Boolean optionalStyle: IMapSurround) :
IMapSurround
TipText (in X: Double, in Y: Double) :
String DelayDrawing (in delay: Boolean)
DelayEvents (in delay: Boolean)
Activate (hWnd: Long)
DeleteLayer (in Layer: ILayer)
Clear
DeleteMapSurround (in MapSurround:
ContentsChanged IMapSurround)
Deactivate GetPageSize (out widthInches: Double,
Draw (in hDC: Long, in trackCancel: out heightInches: Double)
ITrackCancel) MoveLayer (in Layer: ILayer, in toIndex:
GetContextMenu (in X: Double, in Y: Long)
Double, out clsidMenu: IUID) RecalcFullExtent
HitTestMap (in Location: IPoint) : IMap SelectByShape (in Shape: IGeometry,
IsActive: Boolean in env: ISelectionEnvironment, in
OnMessage (in msg: Unsigned Long, in justOne: Boolean)
wParam: Unsigned Machine Int, in Finally, all the geographic layers are SelectFeature (in Layer: ILayer, in
lParam: Long)
Output (in hDC: Long, in dpi: Long, in
PixelBounds: tagRECT, in
8 refreshed to update the map display.
Feature: IFeature)
SetPageSize (in widthInches: Double, in
heightInches: Double)
VisibleBounds: IEnvelope, in
trackCancel: ITrackCancel)
PartialRefresh (in phase:
tagesriViewDrawPhase, in data:
IUnknown Pointer, in Envelope:
IEnvelope)
PrinterChanged (in Printer: IPrinter)
Refresh

36 • ArcGIS Desktop Developer Guide


Display
IStyleGalleryItem : IUnknown

Category: String
Geodatabase
ID: Long IFeatureClass : IObjectClass
Item: IUnknown Pointer
Name: String AreaField: IField
FeatureClassID: Long
FeatureDataset: IFeatureDataset
FeatureType: esriFeatureType
LengthField: IField
ShapeFieldName: String
ShapeType: tagesriGeometryType
IEnumStyleGalleryItem:IUnknown CreateFeature: IFeature
CreateFeatureBuffer: IFeatureBuffer
Next: IStyleGalleryItem FeatureCount (in QueryFilter:
Reset IQueryFilter) : Long
GetFeature (in ID: Long) : IFeature
GetFeatures (in fids: Variant, in
Recycling: Boolean) : IFeatureCursor
6 Insert (in useBuffering: Boolean) :
IFeatureCursor
Search (in Filter: IQueryFilter, in
Recycling: Boolean) : IFeatureCursor
The style gallery enumerator is reset and
then iterated over to look for a match 5 Select (in QueryFilter: IQueryFilter, in
selType: esriSelectionType, in
selOption: esriSelectionOption, in
between the style item name and the layer selectionContainer: IWorkspace) :
Using the FeatureClass property,
name. ISelectionSet
check the shape type of the layer. Update (in Filter: IQueryFilter, in
Carto If it is not Polygon, skip to the next
layer.
Recycling: Boolean) : IFeatureCursor

ILayer : IUnknown
AreaOfInterest: IEnvelope
Cached: Boolean
Carto
MaximumScale: Double
If a match in name is found, the
MinimumScale: Double
Name: String
ShowTips: Boolean
ISimpleRenderer:IUnknown

Description: String
7 symbol obtained from the style
gallery is set into the renderer.
SpatialReference: ISpatialReference Label: String
SupportedDrawPhases: Long Symbol: ISymbol
TipText (in X: Double, in Y: Double,
in Tolerance: Double) : String
Valid: Boolean
Visible: Boolean
Draw (in drawPhase:
tagesriDrawPhase, in Display:
IDisplay, in trackCancel: Add this to the Click event of a UIButtonControl in ArcMap.
ITrackCancel)
1 Dim pMxDoc As IMxDocument
Set pMxDoc = ThisDocument
IFeatureLayer : ILayer
2 Dim pStyleItems As IEnumStyleGalleryItem
DataSourceType: String Set pStyleItems = pMxDoc.StyleGallery.Items("Fill Symbols", _
DisplayField: String
FeatureClass: IFeatureClass
"ESRI.style", "Default")
ScaleSymbols: Boolean Dim pGalleryItem As IStyleGalleryItem
Selectable: Boolean
Dim pRenderer As ISimpleRenderer
Search (in QueryFilter:
IQueryFilter, in Recycling: Dim pGeoFeatureLayer As IGeoFeatureLayer
Boolean) : IFeatureCursor Dim i As Long
3 For i = 0 To pMxDoc.FocusMap.LayerCount - 1
If (TypeOf pMxDoc.FocusMap.Layer(i) Is IGeoFeatureLayer) Then
IGeoFeatureLayer : IFeatureLayer 4 Set pGeoFeatureLayer = pMxDoc.FocusMap.Layer(i)
5 If (pGeoFeatureLayer.FeatureClass.ShapeType = _
AnnotationProperties:
IAnnotateLayerPropertiesCollection esriGeometryPolygon) Then
AnnotationPropertiesID: IUID pStyleItems.Reset
CurrentMapLevel: Long Set pGalleryItem = pStyleItems.Next
DisplayAnnotation: Boolean 6
DisplayFeatureClass: IFeatureClass Do While (Not pGalleryItem Is Nothing)
ExclusionSet: IFeatureIDSet If (pGeoFeatureLayer.Name = pGalleryItem.Name) Then
Renderer: IFeatureRenderer Set pRenderer = pGeoFeatureLayer.Renderer
RendererPropertyPageClassID: IUID 7 Set pRenderer.Symbol = pGalleryItem.Item
SearchDisplayFeatures (in QueryFilter: Exit Do
IQueryFilter, in Recycling: Boolean) : End If
IFeatureCursor
Set pGalleryItem = pStyleItems.Next
Loop
If the type of layer is not an End If
4 IGeoFeatureLayer, continue to
the next layer.
End If
Next i
8 pMxDoc.ActivatedView.PartialRefresh esriViewGeography, _
Nothing, Nothing

Chapter 2 • Getting started with VBA and ArcObjects • 37


LOOP THROUGH SELECTED AREA FEATURES

This sample loops through the selected Carto


features of the focus map. It loops using the IFeatureSelection : IUnknown
IEnumFeature interface, which is reached BufferDistance: Double
through a QueryInterface from the CombinationMethod:
esriSelectionResultEnum
SelectionColor: IColor
FeatureSelection property of the map. For SelectionSet: ISelectionSet
each feature it checks the geometry type SelectionSymbol: ISymbol
SetSelectionSymbol: Boolean
and if Polygon, it performs a QueryInterface Add (in Feature: IFeature)
Clear
for the IArea interface. Using the Area SelectFeatures (in Filter: IQueryFilter,
in Method: esriSelectionResultEnum,
property of the interface, it adds the area in justOne: Boolean)
SelectionChanged
to a running total. At the end, it reports the
total area via a message box. Obtain the IFeatureSelection interface by performing
6 a QueryInterface to the IFeatureLayer interface.

To obtain the layers of the map, you must first get IFeatureClass : IObjectClass
1 access to the currently active map. Do this through the
FocusMap property of the IMxDocument interface.
AreaField: IField
FeatureClassID: Long
FeatureDataset: IFeatureDataset
FeatureType: esriFeatureType

ArcMapUI 5 LengthField: IField


ShapeFieldName: String
ShapeType: tagesriGeometryType
If the shape type of
IChangeLayout CreateFeature: IFeature
IContentsViewEdit MxDocument the feature class is
CreateFeatureBuffer: IFeatureBuffer
IDataGraphs not a Polygon, the
IDocument FeatureCount (in QueryFilter:
IDocumentDatasets layer is skipped. IQueryFilter) : Long
IDocumentDefaultSymbols GetFeature (in ID: Long) : IFeature
IDocumentDirty
IDocumentDirty2 GetFeatures (in fids: Variant, in
IDocumentEvents Recycling: Boolean) : IFeatureCursor
IDocumentEventsDisp Insert (in useBuffering: Boolean) :
IDocumentInfo
IMxDocument
IPersist
IMxDocument : IUnknown Carto IFeatureCursor
Search (in Filter: IQueryFilter, in
IPropertySupport ActivatedView: IActiveView Recycling: Boolean) : IFeatureCursor
IReportUnitFormat ActiveView: IActiveView IMap : IUnknown Select (in QueryFilter: IQueryFilter, in
ActiveViewCommand: ICommand selType: esriSelectionType, in
ContentsView (in Index: Long) : ActiveGraphicsLayer: ILayer
selOption: esriSelectionOption, in
IContentsView AnnotationEngine: IAnnotateMap
ContentsViewCount: Long AreaOfInterest: IEnvelope
selectionContainer: IWorkspace) :
ContextItem: IUnknown Pointer Barriers (pExtent: IEnvelope) :
ISelectionSet
CurrentContentsView: IContentsView IBarrierCollection Update (in Filter: IQueryFilter, in
CurrentLocation: IPoint BasicGraphicsLayer: IGraphicsLayer Recycling: Boolean) : IFeatureCursor
DefaultColor (in Type: ClipBorder: IBorder
tagesriMxDefaultColorTypes) : IColor ClipGeometry: IGeometry
DefaultTextFont: Font Description: String
DefaultTextFontSize: IFontSize DistanceUnits: esriUnits
DelayUpdateContents: Boolean Expanded: Boolean
FocusMap: IMap FeatureSelection: ISelection
Maps: IMaps IsFramed: Boolean IFeatureLayer : ILayer
OperationStack: IOperationStack Layer (in Index: Long) : ILayer
PageLayout: IPageLayout LayerCount: Long
RelativePaths: Boolean
DataSourceType: String
Layers (UID: IUID, recursive: Boolean)
SearchTolerance: Double : IEnumLayer DisplayField: String
SearchTolerancePixels: Long MapScale: Double FeatureClass: IFeatureClass
SelectedItem: IUnknown Pointer MapSurround (in Index: Long) : ScaleSymbols: Boolean
SelectedLayer: ILayer IMapSurround
StyleGallery: IStyleGallery MapSurroundCount: Long
Selectable: Boolean
TableProperties: ITableProperties MapUnits: esriUnits
Name: String Search (in QueryFilter: IQueryFilter, in
AddLayer (in Layer: ILayer) ReferenceScale: Double Recycling: Boolean) : IFeatureCursor
CanInsertObject (pEnabled: Boolean) SelectionCount: Long
InsertObject SpatialReference: ISpatialReference
UpdateContents SpatialReferenceLocked: Boolean
UseSymbolLevels: Boolean
AddLayer (in Layer: ILayer) The layers enumerator is iterated
AddLayers (in Layers: IEnumLayer, in
autoArrange: Boolean)
AddMapSurround (in MapSurround:
4 over using the standard enumerator
method, Next.
IMapSurround)
ClearLayers
ClearMapSurrounds IEnumLayer : IUnknown
ClearSelection
ComputeDistance (in p1: IPoint, in p2:
UID IPoint) : Double
Next: ILayer
CreateMapSurround (in CLSID: IUID, in
IUID IUID : IDispatch optionalStyle: IMapSurround) : Reset
IMapSurround
IPersistStream DelayDrawing (in delay: Boolean)
2 IXMLSerialize
SubType: Long
Value: Variant
DelayEvents (in delay: Boolean)
DeleteLayer (in Layer: ILayer)
The UID object created previously is used
The UID helper object is used
to represent the GUID for the
Compare (in otherID:
IUID) : Boolean
Generate
DeleteMapSurround (in MapSurround:
IMapSurround)
GetPageSize (out widthInches: Double,
out heightInches: Double)
3 to obtain an enumerator for all layers that
support the IGeoFeatureLayer interface.
IGeoFeatureLayer interface. MoveLayer (in Layer: ILayer, in toIndex: Notice the resetting of the enumerator
Long)
RecalcFullExtent before its use.
SelectByShape (in Shape: IGeometry,
in env: ISelectionEnvironment, in

System justOne: Boolean)


SelectFeature (in Layer: ILayer, in
Feature: IFeature)
SetPageSize (in widthInches: Double, in
heightInches: Double)

38 • ArcGIS Desktop Developer Guide


Before attempting to loop through selected
7 features, a check is performed to ensure
that there are selected features for the IFeatureCursor : IUnknown
current layer. If there are no selected Fields: IFields
features, the layer is skipped. IFeature : IObject
DeleteFeature
FindField (in Name: String) : Long
Extent: IEnvelope
ISelectionSet : IUnknown Flush
FeatureType: esriFeatureType
InsertFeature (in Buffer: Shape: IGeometry
Count: Long IFeatureBuffer) : Variant
FullName: IName NextFeature: IFeature ShapeCopy: IGeometry
IDs: IEnumIDs UpdateFeature (in Object: IFeature)
Target: ITable
Add (in OID: Long) If there are selected features, a
AddList (in Count: Long, in OIDList:
Long) 8 cursor onto these features is
obtained from the layers
Combine (in otherSet: ISelectionSet, in
setOp: esriSetOperation, out selection set.
resultSet: ISelectionSet)
MakePermanent
Refresh
RemoveList (in Count: Long, in
OIDList: Long) Geodatabase
Search (in pQueryFilter: IQueryFilter, in For each feature returned by the cursor,
Recycling: Boolean, out ppCursor:
ICursor) 9 the Area of the feature's shape is
obtained and totalled. The area is obtained
Select (in QueryFilter: IQueryFilter, in
selType: esriSelectionType, in by performing a QueryInterface on the
selOption: esriSelectionOption, in feature's shape for the IArea interace and
selectionContainer: IWorkspace) :
ISelectionSet IArea : IUnknown getting the Area property from it.

Area: Double
Centroid: IPoint
LabelPoint: IPoint
Finally, the totalled area is displayed
Geometry QueryCentroid (Center: IPoint)
QueryLabelPoint (LabelPoint: IPoint)
10 to the user in a standard Visual Basic
Message Box.

Add this code to the Click event of a UIButtonControl in ArcMap.


1 Dim pMxDoc As IMxDocument
Set pMxDoc = ThisDocument

2 Dim pUID As New UID


pUID = "{E156D7E5-22AF-11D3-9F99-00C04F6BC78E}" 'IGeoFeatureLayer IID

3 Dim pEnumLayer As IEnumLayer


Set pEnumLayer = pMxDoc.FocusMap.Layers(pUID, True)
pEnumLayer.Reset

Dim pFeatureLayer As IFeatureLayer


Dim pFeatureSelection As IFeatureSelection
Dim pFeatureCursor As IFeatureCursor
Dim pFeature As IFeature
Dim pArea As IArea
Dim dTotalArea As Double

4 Set pFeatureLayer = pEnumLayer.Next


Do Until (pFeatureLayer Is Nothing)
5 If (pFeatureLayer.FeatureClass.ShapeType = esriGeometryPolygon) Then
6 Set pFeatureSelection = pFeatureLayer

7 If (pFeatureSelection.SelectionSet.Count <> 0) Then


pFeatureSelection.SelectionSet.Search Nothing, True, pFeatureCursor
8 Set pFeature = pFeatureCursor.NextFeature

Do Until (pFeature Is Nothing)


9 Set pArea = pFeature.Shape
dTotalArea = dTotalArea + pArea.Area
Set pFeature = pFeatureCursor.NextFeature
Loop
End If
End If
Set pFeatureLayer = pEnumLayer.Next
Loop

10 MsgBox "Total Area for selected polygon features = " & CStr(dTotalArea)

Chapter 2 • Getting started with VBA and ArcObjects • 39


SPATIAL QUERY

This sample builds a spatial query filter,


gets a feature cursor based on the filter
Each layer in the map is looped over; if the
and then loops over all the features, 6 layer is not of type IGeoFeatureLayer,
totalling the number of points, lines, and the layer is skipped.

areas, and reports these to the user. Carto


IMap : IUnknown
ActiveGraphicsLayer: ILayer IFeatureLayer : ILayer
AnnotationEngine: IAnnotateMap
AreaOfInterest: IEnvelope DataSourceType: String
Barriers (pExtent: IEnvelope) : DisplayField: String
IBarrierCollection FeatureClass: IFeatureClass
BasicGraphicsLayer: IGraphicsLayer
IChangeLayout ClipBorder: IBorder ScaleSymbols: Boolean
IContentsViewEdit
IDataGraphs
MxDocument ClipGeometry: IGeometry
Description: String
Selectable: Boolean
IDocument DistanceUnits: esriUnits Search (in QueryFilter:
IDocumentDatasets Expanded: Boolean
FeatureSelection: ISelection
IQueryFilter, in Recycling:
IDocumentDefaultSymbols Boolean) : IFeatureCursor
IDocumentDirty IsFramed: Boolean
IDocumentDirty2 Layer (in Index: Long) : ILayer
IDocumentEvents LayerCount: Long
IDocumentEventsDisp Layers (UID: IUID, recursive: Boolean)
IDocumentInfo : IEnumLayer IFeatureClass : IObjectClass
IMxDocument IMxDocument : IUnknown MapScale: Double
IPersist ActivatedView: IActiveView MapSurround (in Index: Long) : AreaField: IField
IPropertySupport IMapSurround FeatureClassID: Long
ActiveView: IActiveView MapSurroundCount: Long
IReportUnitFormat FeatureDataset: IFeatureDataset
ActiveViewCommand: ICommand MapUnits: esriUnits FeatureType: esriFeatureType
ContentsView (in Index: Long) : Name: String
IContentsView LengthField: IField

1 ContentsViewCount: Long
ContextItem: IUnknown Pointer
CurrentContentsView: IContentsView
ReferenceScale: Double
SelectionCount: Long
SpatialReference: ISpatialReference
ShapeFieldName: String
ShapeType: tagesriGeometryType

SpatialReferenceLocked: Boolean CreateFeature: IFeature


CurrentLocation: IPoint
The IMxDocument DefaultColor (in Type:
UseSymbolLevels: Boolean CreateFeatureBuffer: IFeatureBuffer
interface is obtained from tagesriMxDefaultColorTypes) : IColor FeatureCount (in QueryFilter:
AddLayer (in Layer: ILayer) IQueryFilter) : Long
DefaultTextFont: Font AddLayers (in Layers: IEnumLayer, in GetFeature (in ID: Long) : IFeature
the ThisDocument DefaultTextFontSize: IFontSize autoArrange: Boolean)
DelayUpdateContents: Boolean GetFeatures (in fids: Variant, in
global variable. AddMapSurround (in MapSurround: Recycling: Boolean) : IFeatureCursor
FocusMap: IMap IMapSurround) Insert (in useBuffering: Boolean) :
Maps: IMaps ClearLayers IFeatureCursor
OperationStack: IOperationStack ClearMapSurrounds Search (in Filter: IQueryFilter, in
PageLayout: IPageLayout ClearSelection Recycling: Boolean) : IFeatureCursor
RelativePaths: Boolean ComputeDistance (in p1: IPoint, in p2: Select (in QueryFilter: IQueryFilter, in
SearchTolerance: Double IPoint) : Double selType: esriSelectionType, in
SearchTolerancePixels: Long CreateMapSurround (in CLSID: IUID, in selOption: esriSelectionOption, in
SelectedItem: IUnknown Pointer optionalStyle: IMapSurround) : selectionContainer: IWorkspace) :
IMapSurround ISelectionSet
SelectedLayer: ILayer
DelayDrawing (in delay: Boolean) Update (in Filter: IQueryFilter, in
StyleGallery: IStyleGallery
DelayEvents (in delay: Boolean) Recycling: Boolean) : IFeatureCursor
TableProperties: ITableProperties
DeleteLayer (in Layer: ILayer)
AddLayer (in Layer: ILayer) DeleteMapSurround (in MapSurround:
CanInsertObject (pEnabled: Boolean) IMapSurround)
InsertObject GetPageSize (out widthInches: Double,
UpdateContents out heightInches: Double)
MoveLayer (in Layer: ILayer, in toIndex:
Long)
RecalcFullExtent
SelectByShape (in Shape: IGeometry,
in env: ISelectionEnvironment, in
The active view associated with the focus justOne: Boolean)

3 map is acquired in order for the rubber


banding geometry to have the correct
SelectFeature (in Layer: ILayer, in
Feature: IFeature)
SetPageSize (in widthInches: Double, in
heightInches: Double)
spatial reference.
IActiveView : IUnknown

ExportFrame: tagRECT The TrackNew method is called.


Extent: IEnvelope
ExtentStack: IExtentStack
FocusMap: IMap
4 This allows the user to drag the
mouse to define the envelope.
IEnvelope : IGeometry

Depth: Double
FullExtent: IEnvelope Height: Double
GraphicsContainer: IGraphicsContainer LowerLeft: IPoint
IsMapActivated: Boolean
ScreenCacheID (in phase:
IRubberBand RubberBand LowerRight: IPoint
MMax: Double
tagesriViewDrawPhase, in data: MMin: Double
IUnknown Pointer) : Integer IRubberBand : IUnknown UpperLeft: IPoint
ScreenDisplay: IScreenDisplay UpperRight: IPoint
Selection: ISelection Width: Double
ShowRulers: Boolean TrackExisting (in ScreenDisplay: XMax: Double
ShowScrollBars: Boolean IScreenDisplay, in Symbol: ISymbol, XMin: Double
ShowSelection: Boolean in Geometry: IGeometry) : Boolean YMax: Double
TipText (in X: Double, in Y: Double) : YMin: Double
String TrackNew (in ScreenDisplay: ZMax: Double
IScreenDisplay, in Symbol: ISymbol) ZMin: Double
Activate (hWnd: Long) : IGeometry
Clear CenterAt (p: IPoint)
ContentsChanged DefineFromPoints (Count: Long, in
Deactivate Points: IPoint)
Draw (in hDC: Long, in trackCancel: Expand (dx: Double, dy: Double,
ITrackCancel) asRatio: Boolean)
GetContextMenu (in X: Double, in Y:
Double, out clsidMenu: IUID)
HitTestMap (in Location: IPoint) : IMap
2 Rubber-
ExpandM (dm: Double, asRatio:Boolean)
ExpandZ (dz: Double, asRatio: Boolean)
Intersect (inEnvelope: IEnvelope)
IsActive: Boolean Offset (X: Double, Y: Double)
OnMessage (in msg: Unsigned Long, in A user-defined envelope defining the Envelope OffsetM (M: Double)
OffsetZ (Z: Double)
wParam: Unsigned Machine Int, in
lParam: Long) extent of the spatial query is required. PutCoords (XMin: Double, YMin: Double,
Output (in hDC: Long, in dpi: Long, in XMax: Double, YMax: Double)
PixelBounds: tagRECT, in
The rubber envelope object is used. QueryCoords (out XMin: Double, out
VisibleBounds: IEnvelope, in YMin: Double, out XMax: Double, out
trackCancel: ITrackCancel) YMax: Double)
PartialRefresh (in phase:
tagesriViewDrawPhase, in data:
IUnknown Pointer, in Envelope:
IEnvelope)
Display Union (inEnvelope: IEnvelope)

PrinterChanged (in Printer: IPrinter)


Refresh

40 • ArcGIS Desktop Developer Guide


IGeometry : IUnknown
IFeatureCursor : IUnknown Enumeration esriGeometryTypeConstants
Dimension: tagesriGeometryDimension 0 - esriGeometryNull
Fields: IFields Envelope: IEnvelope
8 DeleteFeature
FindField (in Name: String) : Long
GeometryType: tagesriGeometryType
IsEmpty: Boolean
1 - esriGeometryPoint
2 - esriGeometryMultipoint
3 - esriGeometryPolyline
Flush SpatialReference: ISpatialReference 4 - esriGeometryPolygon
A feature cursor is obtained
InsertFeature (in Buffer: GeoNormalize 5 - esriGeometryEnvelope
from the layer by calling the IFeatureBuffer) : Variant
GeoNormalizeFromLongitude 6 - esriGeometryPath
Search method passing in NextFeature: IFeature (Longitude: Double) 7 - esriGeometryAny
the SpatialFilter. UpdateFeature (in Object: IFeature) Project (newReferenceSystem: 9 - esriGeometryMultiPatch
ISpatialReference) 11 - esriGeometryRing
QueryEnvelope (outEnvelope: IEnvelope)
Geodatabase SetEmpty
SnapToSpatialReference
13 - esriGeometryLine
14 - esriGeometryCircularArc
15 - esriGeometryBezier3Curve
16 - esriGeometryEllipticArc
5 IFeature : IObject Geometry 17 - esriGeometryBag
18 - esriGeometryTriangleStrip
Extent: IEnvelope 19 - esriGeometryTriangleFan
A new spatial filter object is created. FeatureType: esriFeatureType 20 - esriGeometryRay
The shape and spatial reference is set. Shape: IGeometry 21 - esriGeometrySphere
ShapeCopy: IGeometry

This cursor is looped over and the features returned by


IClone
IPersistStream
9 the cursor are inspected. Based on their geometry type,
the totals are updated accordingly.
IQueryFilter QueryFilter
IQueryFilter2
IXMLSerialize

Add this to the MouseDown event of a UIToolControl in ArcMap.


ISpatialFilter
SpatialFilter Dim pMxDoc As IMxDocument
1 Set pMxDoc = ThisDocument
ISpatialFilter : IQueryFilter
FilterOwnsGeometry: Boolean Dim pEnv As IEnvelope
Geometry: IGeometry
Dim pRubber As IRubberBand
GeometryEx (in Geometry:
IGeometry) : Boolean 2 Set pRubber = New RubberEnvelope
GeometryField: String
SearchOrder: tagesriSearchOrder Dim pActiveView As IActiveView
SpatialRel: esriSpatialRelEnum 3 Set pActiveView = pMxDoc.FocusMap
SpatialRelDescription: String
4 Set pEnv = pRubber.TrackNew(pActiveView.ScreenDisplay, Nothing)

Dim pSpatialFilter As ISpatialFilter


5 Set pSpatialFilter = New SpatialFilter
Set pSpatialFilter.Geometry = pEnv
pSpatialFilter.SpatialRel = esriSpatialRelIntersects
The spatial filter must be told what
7 column in the database table holds the
feature shape. This information is
Dim lPoints As Long, lPolygons As Long, lPolylines As Long
Dim pLayer As IFeatureLayer
retrieved from the feature class.
Dim pFeatureCursor As IFeatureCursor
Dim pFeature As IFeature
Dim i As Long
For i = 0 To pMxDoc.FocusMap.LayerCount - 1
6 If (TypeOf pMxDoc.FocusMap.Layer(i) Is IGeoFeatureLayer) Then
Set pLayer = pMxDoc.FocusMap.Layer(i)
Enumeration esriSpatialRelEnum pSpatialFilter.GeometryField = pLayer.FeatureClass.ShapeFieldName
7
0 - esriSpatialRelUndefined
1 - esriSpatialRelIntersects 8 Set pFeatureCursor = pLayer.Search(pSpatialFilter, True)
2 - esriSpatialRelEnvelopeIntersects
3 - esriSpatialRelIndexIntersects 9 Set pFeature = pFeatureCursor.NextFeature
4 - esriSpatialRelTouches Do Until (pFeature Is Nothing)
5 - esriSpatialRelOverlaps Select Case pFeature.Shape.GeometryType
6 - esriSpatialRelCrosses Case esriGeometryPoint
7 - esriSpatialRelWithin
8 - esriSpatialRelContains lPoints = lPoints + 1
9 - esriSpatialRelRelation Case esriGeometryPolyline
lPolylines = lPolylines + 1
Case esriGeometryPolygon
Finally, the results of the selection are lPolygons = lPolygons + 1
10 displayed in a Visual Basic message box. End Select
Set pFeature = pFeatureCursor.NextFeature
Loop
End If
Next i

10 MsgBox "Features Found:" & vbCrLf & lPoints & " Points " & vbCrLf & _
lPolylines & " Polylines " & vbCrLf & lPolygons & " Polygons "

Chapter 2 • Getting started with VBA and ArcObjects • 41

Das könnte Ihnen auch gefallen