Вы находитесь на странице: 1из 9

Geodetic Science 634 - Digital Mapping Systems Winter 2007 Laboratory Exercise No. 4.

ArcObjects and VBA Programming


Date assigned: Jan 30, 2007 Date due: February 13, 2007 Objectives: 1. 2. To customize the graphical user interface (GUI) of ArcGIS, To learn program VBA with ArcObjects.

Introduction: This lab will help you become familiar with ESRI application developer experience. First, you will see how to control and modify the graphical user interface (GUI) of ArcMap and ArcCatalog. Next, you will use the development environment thats embedded in ESRI applications, Visual Basic for Applications (VBA), to create your own commands. At the end of the lab, you will go through a tutorial with MapObjects using Visual Basic. This lab assumes some familiarity with programming with Visual Basic and terms used to describe it. Part 1. Customizing the user interface Although ArcGIS are designed to be flexible and easy to use, you may want the ArcMap and ArcCatalog interfaces to reflect your own preferences and the way you work. You can customize ArcMap and ArcCatalog in many ways. Here are some examples: Position toolbars in a specific area of the application. Group commands in a way that works best for you. Add new macros or load custom commands from another source. Always work with the same geographic data.

In this part, you will go through a tutorial and learn how to customize the user interface. a. Tutorial Start ArcMap and add street feature class to the map. 1. Manipulating toolbars using the Customize dialog In the Tools menu click Customize. The Customize dialog appears. You can also double-click any unoccupied area of any toolbar to display the Customize dialog. Click the Toolbars tab. The presence or absence of a check mark next to the toolbar name indicates its visible state, just as the in the Toolbars submenu of the View menu. You can click the check mark next to any toolbar to turn it off and on. Creating a new toolbar In the Toolbars tab of the Customize dialog, click the New button. In the dialog that appears, specify My Tools as the name of the new toolbar or use the default setting.

2.

3. 4.

5.

Store the toolbar in the document by changing the name of the Save in the dropdown list from Normal.mxt to Untitled or the name of the current project. Click OK. The newly created toolbar appears near the top of the application window. Adding buttons to a toolbar Make sure the toolbar you just created, My Tools, is visible. Display the Customize dialog. Click the Commands tab of the Customize dialog. Select the Pan/Zoom category from the Categories list at the left of the dialog. Scroll to the bottom of the Commands list at the right of the dialog. Select the Zoom in command and drag it to the My Toolbar.

6.

7. 8. 9. 10. 11.

12. Continue adding some commands from the Pan/Zoom, Selection, and Page Layout categories, until you have your own version of the built-in Tools toolbar. You can resize the toolbar so that it width allows the display of two commands per column. You can also dock the toolbar or drag it to wherever you want. Renaming a toolbar

13. In the Toolbars tab, select the name of the toolbar whose name you want to change. In this case, select My Tools. Click the Rename button. 14. In the dialog that appears, specify My Own Tools as the new name. Note that you can only rename toolbars youve created. 15. Click OK. If you choose not to rename the toolbar, click Cancel. Removing buttons from a toolbar.

16. Make sure the toolbar you just renamed, My Own Tools, is visible. Display the Customize dialog. 17. Drag the Fixed Zoom In, Fixed Zoom Out, Full Extent buttons off the dialog.

Even though youve removed the buttons from the toolbar, they are still available in the Customize dialog. Adding a menu to a toolbar

18. Make sure the toolbar named My Own Tools is visible. Display the Customize dialog. 19. Click the Commands tab and choose the Menus category from the Categories list at the left-hand side of the dialog. 20. In the Commands list at the right-hand side of the dialog, choose Selection. 21. Drag and drop it to the right of the Zoom Out button on the My Own Tools toolbar.

22. In the Customize dialog, click Close.

Saving changes to a template

You can save your work to a document or template. Changes save to a document are specific to the document, whereas changes saved to a template will be reflected in all document based on the template. 23. In the File menu, click Save As. 24. In the Save As dialog, navigate to N:\gs634 or any other folder you like. 25. Type the template name, choose ArcMap Templates (*.mxt), and then click Save. Next time when you create a new map, you may open this template and use the toolbar you created here. b. Task Create another toolbar containing menu and command buttons. Name it as GS634 Tools. Part 2. Learning VBA fundamentals and programming with ArcObjects. Both ArcMap and ArcCatalog come with Visual Basic for Applications (VBA). VBA is not a standalone program; it's embedded in the applications. It provides an integrated programming environment, the Visual Basic Editor (VBE), that lets you write a Visual Basic (VB) macro and then debug and test it right away in ArcMap or ArcCatalog. A macro can integrate some or all of VB's functionality, such as using message boxes for input, with the extensive object library that ArcMap and ArcCatalog expose. The ESRI Object Library is always available to you in the VBA environment. In ArcMap, each document and template that is currently loaded has an associated VBA project in the VBE. The VBA project for the document is called Project (NameOfDoc.mxd), the VBA project for the Normal template is called Normal (Normal.mxt), and if another template is loaded, its VBA project is called TemplateProject (NameOfTemplate.mxt). In ArcCatalog, there is only a VBA project for the Normal template, called Normal (Normal.gxt). Macros can be stored in any of the VBA projects depending on where you want the new functionality to be available. When you create a macro, you're creating a VB Sub Procedure. The procedure's name is the name you assign to the macro. You add code to the procedure in a Code window just as you would in VB. When you create a new macro in the Macros dialog box, precede the macro's name with the name of the module to store it in. You can organize your macros in different modules; each module has its own Code window. To add your macro to a specific module, type the module name before the macro's name, for example, "Department.WorkMacro". If the module doesn't exist, a new module with that name is created for you and added to the VBA project. Similarly, if you provide a name for a new macro but don't specify which module to store it in, a new module called "NewMacros" is created. Using modules makes it easier to share your VB code with others; you can export a module to a .bas file from, and import a .bas file to, your VBA project. a. Tutorial 1. 2. 3. Creating a macro In the Tools menu, select Macros and then Macros. In the Macros dialog, type MyZoomIn in the Macro name text box and then click Create. The application creates a new module named Module1 and stubs in the Sub procedure. Enter the following code to MyZoomIn: Sub MyZoonIn( ) macro: MyZoomIn Dim pDoc as IMxDocument Dim pEnv as IEnvelope Set pDoc = ThisDocument

Set pEnv = pDoc.ActiveView.Extent pEnv.Expand 0.5, 0.5, True pDoc.ActiveView.Extent = pEnv pDoc.ActiveView.Refresh End Sub The first line of the macro declares a variable that represents the ArcMap document. The second line declares a variable that represents a rectangle with sides parallel to a coordinate system defining the extent of the data. The predefined variable, ThisDocument, is the IDocument interfaces to the MxDocument object that represent the ArcMap document. The ActiveView property provides an IActiveView interface that links the document data to the current screen display of that data. By reducing the size of the envelope that represents the extent of the map, the macro zooms in on the maps features once the screen display is refreshed. 4. 5. 6. Switch back to ArcMap. In the Tools menu, select Macros and then Macros. Select the NewMacros.MyZoomIn macro and click Run. Then display zooms in.

7. 8. 9. 10. 11. 12. 13. 14. 15.

Adding a macro to a tool bar In the Tools menu, select Customize. In the Toolbars tab, create a new toolbar. Switch to the Commands tab and select the Macros category. In the Save in combo box, select the name of your project. The commands list at the right of the dialog lists NewMacros.MyZoomIn. Drag the macro name to the toolbar you created. The macro appears with a default icon. To change its properties, right-click the icon. In the context menu that appears, select Change Button Image and choose a button from the palette of icons. Close the Customize dialog. Click the button to run the macro. Invoking the Visual Basic Editor directly and getting help in the Code Window

As an alternative to the Create button in the Macro dialog, you can navigate directly to the Visual Basic Editor and create procedures on your own. 16. 17. 18. 19. 20. 21. 22. Press Alt+F11, the Visual Basic Editors keyboard accelerator. In the VBEs View menu, select Project Explorer. In the Project Explorer, click the Project entry, then Modules, and then Module1. In the Code Window, copy the MyZoomIn code from the beginning of the Sub to the End Sub. Paste the MyZoomIn Sub code below the existing code. Change the name of the copied Sub to MyZoomOut. Change the line pEnv.Expand 0.5, 0.5, True to pEnv.Expand 1.5, 1.5, True 23. Follow steps 7-15 to add and run your second macro.

You can use ArcObjects Developer Help in the ArcInfo program group to learn more about the methods and functions you used above. You may get information about object model diagrams, samples, tips, and tricks. 24. Go to Start->All programs->original programs->ArcGIS, click ArcObjects Developer Help. The ArcObjects Developer Help window displays the help topic for Expand. Such as the command pEnv.Expand 0.5, 0.5, True in the Code Window of VBE.

In addition to ArcObjects Help, you can consult ArcObjects Developer Help in the ArcInfo program group for object model diagrams, samples, tips, and tricks.
Creating a tool in VBA

To this point in the tutorial, youve only created commands. Commands, once invoked, usually perform some direct action without user intervention. As youve seen in the build-in toolbars and menus, users interact with other controls in addition to commands. As part of the customization environment, you can add sophisticated controls to toolbars and menus. These controls are called UIControls. 1. 2. 3. 4. 5. In the Tools menu, select Customize. In the Customize dialog, select commands tab and then change the Save in the combo box to the name of your project or Untitled. In the Categories list, select UIControls. Click New UIControl. In the dialog that appears, choose UIToolControl as the UIControl Type and then click Create and Edit. Adding code for the UIToolControl

The application adds an entry in the Object Box for a UIToolControl and stubs in an event procedure for the UIToolControls Select event. You wont add any code to the Select event procedure at this time; instead, select the MouseDown event in the Events/Procedures box at the right-hand side of the Code Window. Youll add code to this event to enable you to drag a rectangle on the screen display; the application will zoom to the rectangles extent. 1. Add the following code to the MouseDown event procedure. If button = 1 Then Dim pDoc As IMxDocument Dim pScreenDisp As IScreenDisplay Dim pRubberEnv As IRubberBand Dim pEnv As IEnvelope Set pDoc = ThisDocument Set pScreenDisp = pDoc.ActiveView.ScreenDisplay Set pRubberEnv = New RubberEnvelope Set pEnv = pRubberEnv.TrackNew(pScreenDisp, Nothing) pDoc.ActiveView.Extent = pEnv pDoc.ActiveView.Refresh End If The key line of this procedure is the one containing the TrackNew method, which rubber-bands a new shape on the specified screen. The code use Envelope object that the method returns to set the new extent for the map. 2. Add the following code to the UIToolControls Enabled event procedure. Dim pDoc as IMxDocument Set pDoc = ThisDocument

If pDoc.Focusmap.LayerCount > 0 Then UIToolControl1_Enabled = True ElseIf pDoc.FocusMap.LayerCount = 0 Then UIToolControl1_Enabled = False End If 3. Add the following code to the CursorID event procedure to control the cursor that appears when you use the tool. UIToolControl1_CursorID = 3 4. Crosshair

To provide a ToolTip when the mouse hovers over the tools button, add the following code to the ToolTip event procedure. UIToolControl1_ToolTip = Zoom to rectangle

5.

Add the following code to the Message event procedure to supply additional text describing the tools functionality in the Status bar area. UIToolControl1_Message = Zoom to a designated rectangle

6. 7. 8.

Close VBE and return to ArcMap. Add this UIControl to the toolbar you created above. You can change the icon of the button. Test the tool. Import ArcView Project into ArcMap

Many items from an ArcView GIS 3 project (.apr) can be imported to an ArcMap 8.3 project (.mxd). 1. 2. 3. Start ArcMap and open a blank map document. Click the File menu and click Import from ArcView project. Navigate to and select the ArcView project you would like to import to ArcMap. If you are importing a layout, choose the layout you would like to import from the Layouts dropdown list. The views that are in the layout will be automatically selected. Views that are not in the selected layout may be selected interactively. Click OK to import the project. The selected import layout is now the layout view in ArcMap. Some graphic and text adjusting may be required to get the desired look for the map layout. The imported views are now separate data frames located in the table of contents.

4.

Note: ArcMap does not support multiple layouts in a document. Importing ArcView projects with multiple layouts requires that you choose only one layout to import. Move from layout view to data view to see a single data frame in the window. Having multiple data frames in ArcMap is the equivalent of having multiple views in ArcView GIS 3. The active data frame will be visible in the view and will be the only data frame with the title in bold letters. To activate a different data frame, right-click the data frame's title in the table of contents and select Activate from the list of options. To import multiple layouts from an ArcView GIS 3.x project, import each of the layouts in your ArcView 3.x project into separate ArcMap map documents (.mxd).

b. Tasks In this part, you will be given some VB codes about programmatically adding a line event layer to ArcMap. Your task is to turn these codes into one command button of your own and add it into the toolbar you created. Add comments for each line in the codes.

How to use the code: 1. 2. 3. 4. Add a route layer to ArcMap called 'Bus' (or change the code accordingly). Add a table called 'fare' to ArcMap (or change the code accordingly). If necessary, change the field names in the code to fit your data. Paste the code into VBA. Run the code.

Public Sub AddLineEventLayer() '+++ VBA code that shows how to add a line RouteEventSource as a layer in the Map On Error GoTo eh '+++ Get the event table. It is called fare. Dim pMxDoc As IMxDocument Dim pTblColl As ITableCollection Dim pEventTable As ITable Dim i As Long Dim pMap As IMap Dim pDS As IDataset Set pMxDoc = ThisDocument Set pMap = pMxDoc.FocusMap Set pTblColl = pMap For i = 0 To pTblColl.TableCount - 1 Set pDS = pTblColl.Table(i) If LCase(pDS.BrowseName) = "fare" Then Set pEventTable = pDS Exit For End If Next i If pEventTable Is Nothing Then MsgBox "Could not find event table", vbExclamation, "AddLineEventLayer" Exit Sub End If '+++ Get the route feature class. It is called 'Bus'. Dim pLayer As ILayer Dim pFLayer As IFeatureLayer Dim pRouteFc As IFeatureClass For i = 0 To pMap.LayerCount - 1 Set pLayer = pMap.Layer(i) If LCase(pLayer.Name) = "Bus" Then If TypeOf pLayer Is IFeatureLayer Then Set pFLayer = pLayer Set pRouteFc = pFLayer.FeatureClass Exit For End If End If Next i If pRouteFc Is Nothing Then MsgBox "Could not find the route feature class", vbExclamation, "AddLineEventLayer" Exit Sub End If

'+++ Create the route event source ... '+++ The route locator Dim pName As IName Dim pRMLName As IRouteLocatorName Set pDS = pRouteFc Set pName = pDS.FullName Set pRMLName = New RouteMeasureLocatorName With pRMLName Set .RouteFeatureClassName = pName .RouteIDFieldName = "BUS_ID" .RouteIDIsUnique = True .RouteMeasureUnit = esriUnknownUnits '.RouteWhereClause = "" End With '+++ Create the route event properties Dim pRtProp As IRouteEventProperties Dim pRMLnProp As IRouteMeasureLineProperties Set pRtProp = New RouteMeasureLineProperties With pRtProp .EventMeasureUnit = esriUnknownUnits .EventRouteIDFieldName = "BUS_ID" End With Set pRMLnProp = pRtProp pRMLnProp.FromMeasureFieldName = "FR_M" pRMLnProp.ToMeasureFieldName = "TO_M" Set pDS = pEventTable Set pName = pDS.FullName Dim pRESN As IRouteEventSourceName Set pRESN = New RouteEventSourceName With pRESN Set .EventTableName = pName Set .EventProperties = pRMLnProp Set .RouteLocatorName = pRMLName End With '+++ By opening a route event source name object, you have a 'dynamic' '+++ feature class ... Dim pEventFC As IFeatureClass Set pName = pRESN Set pEventFC = pName.Open '+++ Create the layer and add it to the current map Dim pActive As IActiveView Set pFLayer = New FeatureLayer Set pFLayer.FeatureClass = pEventFC pFLayer.Name = pDS.BrowseName + "_Events"

'+++ Add the layer extension (this is done so that when you edit '+++ the layer's Source properties and click the Set Data Source '+++ button, the Add Route Events Dialog appears Dim pLayerExt As ILayerExtensions Dim pRESPageExt As New RouteEventsSourcePageExtension Set pLayerExt = pFLayer

pLayerExt.AddExtension pRESPageExt pMap.AddLayer pFLayer Set pActive = pMxDoc.ActiveView pActive.Refresh Exit Sub eh: Dim lNum As Long, sDesc As String, sSrc As String lNum = Err.Number sDesc = Err.Description sSrc = Err.Source Err.Raise lNum, sSrc, sDesc End Sub

Вам также может понравиться