Presentation is loading. Please wait.

Presentation is loading. Please wait.

ArcObjects的开发.

Similar presentations


Presentation on theme: "ArcObjects的开发."— Presentation transcript:

1 ArcObjects的开发

2 AO是什么? AO(ArcObjects的缩写)是ESRI公司ArcGIS™ 家族中应用程序ArcMap™, ArcCatalog™ 和 ArcScene™的开发平台。 是基于Microsoft® COM技术所构建的一系列COM组件集。 开发人员可以在AO组件对象的基础上开发出更加强大灵活的应用系统。

3 AO开发的一般步骤 1.用AO术语对问题进行描述和定义,合理地将大任务合理划分为一些子任务;
3.决定在什么地方来编写代码,是VBA呢,还是VB或其它工具; 4.根据标识的关键字在AO Developer help和其它开发资源中搜索有没有相关示例代码。 5.  打开正确的对象模型图(OMD),寻找所需要的类、接口。 6.  在AO Component Help中浏览有关接口的详细说明及相关文档; 7.  在开发环境中使用确定的接口及其方法属性等,完成代码实现。

4 AO开发的方式比较

5 AO VBA开发培训总体过程安排 VBA skills Objects Maps & Layers Data Management
Day 1 Day 2 Day 3 Day 4 Day 5 Lesson 1: Introduction Lesson 5: Programming with Class Lesson 8: Maps & Layers Lesson 11: Subsets and Selections Lesson 14B: Data Management Break Lesson 2: The VBA Development Environment Lesson 6: COM Lesson 9A: Accessing Data Lesson 12: Layer Rendering and Symbology Lesson 15 Application Framework LUNCH Lesson 3: Visual Basic code: How, where, when? Lesson 7: Understanding Object Model Diagrams Lesson 9B: Customize raster dataset storage Lesson 13: Using Tools Lesson 16: Working with layout elements Lesson 4: Using Variables Lesson 7: Understanding Object Model Diagrams Lesson 10: Working With Geometry Lesson14A: Data Conversion Lesson 17: Creating COM classes with VB Classes Object Model Diagrams Subsets & Selections Application Framework Introduction to Programming ArcObjects with VBA

6 The VBA development environment(I)
Introduction to Programming ArcObjects with VBA

7 Lesson overview VBA开发环境 使用客户化对话框进行以下操作 存储和发布客户化结果 Visual Basic Editor
Create new toolbars and commands Add, delete, and move commands Set control properties 存储和发布客户化结果 Visual Basic Editor Code storage Modules Procedures Visual Basic statements Lecture 2 overview In this lesson, you will learn about the VBA development environment. This environment consists of the Customize dialog box, which is used to modify the ArcMap or ArcCatalog graphical user interface, and the Visual Basic Editor, which is used to write VBA procedures (macros). The first half of this lesson will discuss the Customize dialog box. You will learn how to modify the ArcMap and ArcCatalog user interface by (1) adding new toolbars, (2) adding existing ArcInfo commands, (3) removing existing commands from toolbars and menus, (4) altering command properties (e.g., icon), and (5) creating custom interface controls. You will also learn how to store and distribute your customizations. The last half of this lesson will teach you how to use the Visual Basic Editor. Introduction to Programming ArcObjects with VBA

8 The VBA development environment
Customize dialog box: Interface customization Visual Basic Editor: Writing code Customize dialog box Visual Basic Editor The VBA development environment The VBA development environment consists of two parts: the Customize dialog box for modifying the user interface and the Visual Basic Editor for writing code. An advantage of using VBA that you will soon discover is that several applications use the VBA development environment for customization. While these environments are not identical, they are very similar. All Microsoft Office products, for example, will have a Customize dialog box that allows you to add, remove, and rearrange interface controls. All of these applications will have a Visual Basic Editor for writing macros or designing forms. Once you are familiar with the ArcGIS™ VBA development environment, your skills will be portable to several other applications. Customize dialog box The Customize dialog box is a powerful tool that allows you to customize ArcMap and ArcCatalog without writing a single line of code. You can create, add, move, and remove toolbars and commands, and even add tools others have created. Visual Basic Editor The Visual Basic Editor provides an interface for creating forms and writing code. It also provides several utilities for debugging and getting help that will be discussed throughout this course. Introduction to Programming ArcObjects with VBA

9 ArcGIS commands Toolbars and menus contain commands
Commands are buttons, menus, macros, and UIControls 每个命令都连接了代码 Toolbar ArcGIS commands ArcMap and ArcCatalog have toolbars that contain commands (i.e., controls). Commands are things such as buttons and menus, macros (Visual Basic procedures), and UIControls (user interface controls). UIControls are custom controls that an ArcGIS VBA developer can add to the interface to perform specialized tasks. There are four types of UIControls: UIButtonControls, UIToolControls, UIEditBoxControls, and UIComboBoxControls. COM commands are similar to UIControls, except they are stored in DLL, EXE (executable), or similar files and are created by a developer in a full-scale programming environment such as Visual Basic or C++. Users interact with commands by clicking, typing, selecting, or applying, depending on the type of control. Behind each control, there is associated code that will execute in response to user interaction. As a developer of a UIControl, you can write code to respond to button clicks, mouse interaction (mouse button down, mouse button up, mouse move), and keyboard typing. While the Customize dialog box is open, you can reorganize commands by dragging and dropping them to a new location on a toolbar or menu. You can even drag them between toolbars and menus or remove them altogether. Commands Introduction to Programming ArcObjects with VBA

10 Using the Customize dialog box
打开客户化对话框,使界面进入设置模式 在客户化对话框打开的状态,你可以 … 从新排列或移除现有的命令条目 Add new toolbars and commands Change command properties Using the Customize dialog box In the ArcMap and ArcCatalog Customize dialog box, you will find utilities for adding new toolbars, menus, and commands to the user interface. You may want to simply modify some of the existing commands by rearranging them or changing their icon, for example. Regardless of the interface customization you want to make, however, you always need to start by opening the Customize dialog box. While the Customize dialog box is open, the user interface is in design mode, which means clicking on commands will not execute them but will instead allow you to rearrange them or change their properties. Once you are satisfied with the interface customizations you have made, close the Customize dialog box to begin working with the controls. Introduction to Programming ArcObjects with VBA

11 The Customize dialog 客户化对话框的三个页面:
Toolbars: Turn toolbars on or off, create new toolbars Commands: Drag new commands onto the interface Options:管理客户化的口令等等. The Customize dialog The Customize dialog has three panels: Toolbars, Commands, and Options. The Toolbars and Commands tabs are the ones you will use to modify the user interface, while the Options tab provides some control over basic customization options. Toolbars On the Toolbars tab of the Customize dialog, you have the ability to work with existing toolbars by turning them on or off, renaming them, or deleting them. If you make a mistake while customizing the interface, you can also reset an individual toolbar to its original state by selecting it in the Customize dialog and clicking Reset. You may also use the Customize dialog to create brand new toolbars. When creating a new toolbar, you will be prompted for a name and a location in which to save it (more about storing customizations later). A new toolbar will be nothing more than a small gray box; to add commands to a new toolbar, use the Commands tab. Commands The Commands tab on the Customize dialog box contains all existing ArcMap or ArcCatalog commands (depending on which application you are customizing). Commands can be dragged from the Customize dialog onto a toolbar as a button or onto a menu as a menu choice. A Introduction to Programming ArcObjects with VBA

12 Using the Customize dialog box
所有的命令按分类组织 All ArcMap or ArcCatalog commands are here 有一些没有被放到缺省的界面上 Drag commands onto toolbars or menus Command Categories Commands Using the Customize dialog box As mentioned earlier, the Customize dialog box contains all ArcMap or ArcCatalog commands. These commands are available on the Commands tab and are organized into categories. By highlighting a category on the left side of the dialog, you will see all commands in the category listed on the right. Some familiar categories are things like Selection, Pan/Zoom, and File. You will also find categories for Visual Basic procedures you write yourself (Macros), for creating new menus (New Menu), and for creating new custom controls (UIControls). Because many of the commands you find here are not found on the default (out-of-the-box) ArcGIS interface, you might find a few gems here: functionality that you did not know existed. Once you locate a command you want to add to the interface, you can select the command in the dialog and drag it to a toolbar as a button or onto a menu as a menu choice. You need to be careful, however, as controls that require user interaction will not work as menu choices, and some commands only work as context menu choices (e.g., layer properties). ArcCatalog commands categories In ArcCatalog, you will find commands to launch ArcToolbox™ tools and wizards. These commands are organized under their appropriate ArcToolbox tool category, prefixed with ATB. For example, ATB Conversion Tools contains tools and wizards for data conversion. Introduction to Programming ArcObjects with VBA

13 Creating a new command 在UIControls 分类中 Four types
选择User-created commands Four types Button Tool EditBox ComboBox Creating new commands (user interface controls) The Customize dialog box contains controls you develop yourself in a category called UIControls. You can add these commands to the user interface by dragging them onto a toolbar or menu, just as you would any ArcGIS command. To create a new UIControl, click New UIControl and choose one of the four types described below. UIButtonControl: a simple button or menu choice. UIToolControl: use to create a tool. Differs from a button in that the developer has access to mouse and keyboard input while the tool is selected. UIEditBoxControl: a text line (on a toolbar or menu) that allows the user to type some input. UIComboBoxControl: a pulldown list that allows the user to choose existing items (text) or to type his or her own. Once you have created one of these controls, the next step would be to write the Visual Basic code behind the control user events (button clicks, mouse, keyboard, etc.) that make it work. Adding custom commands from file Custom commands are ActiveX controls or libraries stored as OLB, TLB, EXE, OCX, and DLL files. You can add these custom commands from the Customize dialog box by clicking Add From File. Once you add a custom control from file, it will be placed in the appropriate category in the Customize dialog box (sometimes a new category is created). Just like the other controls in the dialog, you must then drag the command to the desired location on the interface. Note: These controls would have been developed in a standalone programming environment such as Visual Basic or C++, and cannot be created in VBA. Introduction to Programming ArcObjects with VBA

14 Setting control properties
Customize dialog box must be open Right-click a control to view and change properties Characteristics that define appearance Name Image Display text or image Begin a group Command properties While the Customize dialog is open, the user interface is in design mode. To access command properties, simply right-click on a command and use the context (popup) menu that appears. With the dialog open, you can modify the following command properties. Name The text that appears for a command if Text Only or Image and Text is chosen for display. Changing the Name property does not affect how the command is referred to in code. Button image You can choose a new icon for any command (including menu choices) by selecting one from the menu or browsing to one of your own. If you create your own image, it must be a bitmap (.bmp) that is 16 x 16 pixels. Text and image There are three ways in which a command can be displayed on a toolbar: Text only (see the Name property described above), Image only, or both Image and Text. Menu commands (choices) may be displayed as Text or Image and Text; you may not use the Image only choice for menu choices. Groups Beginning a group adds a separator line to the left of the selected control. Use groups to visually organize related commands. Introduction to Programming ArcObjects with VBA

15 Accessing your customizations
ArcMap has three levels of storage 在启动的时候模板将按顺序的加载 ArcCatalog 只使用Normal模板 This Document(*.mxd) Base Template(*.mxt) Normal Template 影响所有使用该模板的文档 影响当前文档 影响所有的文档 Templates In ArcMap, there are three levels at which you can store your customizations: the Normal template (Normal.mxt), an intermediate (or base) template (*.mxt), and the current map document (*.mxd). Each level of customization is represented by a document. Upon opening a map, these documents are read from top to bottom in the graphic above in order to incorporate customizations from all levels. The read order is important because changes in one template can affect other templates and the current map. For example, the Normal template may have the AddData command turned off, but a base template may turn on the AddData command. Normal template The Normal templates contain all the original ArcMap (Normal.mxt) and ArcCatalog (Normal.gxt) graphical user interface (GUI) settings. Every time an application starts, the Normal template is read. The Normal templates are stored in the user’s Windows NT Profiles directory, so each user can have different customizations stored in the Normal templates even if they are running the same installation of ArcGIS. In ArcCatalog, all customizations are stored in the Normal.gxt template. If the Normal template is deleted, it is re-created when the application starts. Base template Base templates allow you to store map elements for the creation of standard maps. When initially creating a new ArcMap map document, you can choose to base your map on a template. While there are several predefined base templates that come with ArcGIS, you can actually save any map document as a template (*.mxt). Templates can also store customizations, which will apply to all maps subsequently produced from them. Introduction to Programming ArcObjects with VBA

16 Storing your customizations
All customizations are saved Normal template, Base template, or the current document 当前地图将越过任何的模板 For example, controls can be added or removed Storing your customizations All ArcMap customizations are stored at one of the three levels described on the last slide. Everything from new Visual Basic forms and programs to simply changing a command’s image is saved in Normal.mxt, a base template (*.mxt), or with the current map document (*.mxd). When a map is opened, these three documents are read in the following order. Normal template The Normal template is always read first when opening a map. Because the Normal template is stored in the Windows user profiles directory, customizations stored here are global to a specific login. If the Normal template does not exist when ArcMap or ArcCatalog is started, an out-of-the-box version is re-created. As a precaution, you should make periodic backups of the Normal template if you are storing a lot of customizations there. Base template Base templates are designed primarily to store a set of map layout elements, such as north arrows, scale bars, and base layers, to aid in the production of standard maps. These templates may also contain customizations such as specialized controls or scripts. As an example, your organization might work with parcel maps that all have a custom property value calculator control inherited from their common template. Maps that were not produced from this template would not have the custom control. Current map If customizations are saved in a map document, they will only be available in that particular document. For example, you might have a map document that contains sensitive information such as archaeological site locations. You could protect this particular document with a custom startup routine that prompts for a password when the map document is opened. Save in: Normal.mxt Introduction to Programming ArcObjects with VBA

17 查看控件的源代码 命令拥有各种事件 (e.g., Click, Double-click, MouseUp, KeyDown, KeyUp)
当事件触发的时候,相应的代码将被运行 Control source code The code behind a command is called the source code or sometimes simply the source. By right-clicking on a custom control (UIControl or Macro) and choosing View Source, you can view (and edit) its source code. Because the existing ArcGIS commands have been compiled as DLLs (and were written in C++ anyway), you cannot view or edit an existing command’s source code. Code window When you first create a UIControl, it only knows how to be a control but has no real code to make it work. It other words, if it is a button it will click like any other button, if it is an edit box it will allow you to type text in it, and so on. It will have all the properties of a control (such as an image and a name) but will not do anything when it’s interacted with. To add functionality to a control, you can choose View Source as shown above to access the control’s associated code document (module). Once you are in the control’s code module, you can write Visual Basic programs that are associated with user events (e.g., a button click). Introduction to Programming ArcObjects with VBA

18 示范 Using the Customize dialog box to … Create a new toolbar
Add existing commands to the interface 重排界面命令顺序 Create a new UIControl Change command properties 重新设置工具条到初始状态 Demonstration: Using the Customize dialog box Your instructor will now use the Customize dialog box to perform some of the simple user interface customizations discussed in this lecture. Introduction to Programming ArcObjects with VBA

19 使用VB编辑器 The VBA development environment Customize dialog box
Create new toolbars and commands Add, delete, and move commands Set control properties Storing and distributing customizations Visual Basic Editor Code storage Modules Procedures Visual Basic statements Overview The first half of this lecture introduced you to the Customize dialog box. While the Customize dialog is used to modify the user interface and to add new controls, the Visual Basic Editor is where you write code to make new controls work. You can also use the Visual Basic Editor to produce standalone programs (macros) and user forms. In this half of the lecture, you will learn how to access and use the Visual Basic Editor, how code is stored and organized in ArcMap and ArcCatalog, as well as some basic VB-related terminology (e.g., module, procedure, macro). Finally, you will learn to write Visual Basic statements and how to use some simple Visual Basic functions. Introduction to Programming ArcObjects with VBA

20 The Visual Basic Editor
Project Explorer Projects Working with the Visual Basic Editor The Visual Basic Editor is where you will write code and design user forms. There are several utilities here for writing, testing, and debugging your VB programs. Before looking at VB editing utilities, let us examine how code is organized in the Editor. Project Explorer The Visual Basic Project Explorer window organizes all code written for a particular ArcMap document or for the ArcCatalog application into three kinds of projects: the Normal template, a base template (if one is referenced), and the current project, also known as your currently opened map document. Use the Project Explorer to access all available Visual Basic programs. Projects Projects are like root directories that organize several subfolders of code documents. In ArcMap, the projects define the level of customization for code you write (Normal versus the current document). When developing in ArcCatalog, the Normal template will be the only project listed in the Project Explorer. In ArcMap, you will also have the current map document and perhaps a base template project. Modules A module is simply a document that contains code. In the Visual Basic Editor, you can work with three types of modules: form, standard, and class. The details of these three module types will be described later. Code Modules Procedures Introduction to Programming ArcObjects with VBA

21 Understanding ArcMap software’s code storage
Project Explorer: Organizes projects (levels of customization) Project: Folder that stores modules (e.g., Normal.mxt) Module: Document that stores code Procedure: A block of code (e.g., macros) Statement: A line of code Contains Contains Contains Contains Module Components of ArcGIS VBA code storage All code written for an ArcMap document or for ArcCatalog can be accessed from the Visual Basic Editor’s Project Explorer window. The Project Explorer organizes all projects that might contain Visual Basic code, and these projects are analogous to the levels of customization discussed earlier (Normal template, base template, map document). By using the Project Explorer, you can access existing code documents (or modules) stored with the document or application, or create new ones. Visual Basic code always lives inside a module, which is nothing more than a document for writing code. Modules, in turn, consist of procedures, which are VB programs (macros). The smallest unit of Visual Basic code that can be executed is the statement. Statements are simply lines of code. Compact disk analogy The code organized in the Visual Basic Editor is like your music collection. The Project Explorer is the rack that contains all your compact disks. To access any of your music, you must start at the CD rack. Just as the Project Explorer may have several Projects, your music rack may have several sets of CDs: your CDs and your spouse’s, for example. Each CD in turn contains several songs, just like a code module may contain several procedures. Individual songs are composed of lines of lyrics, just as procedures are built from lines of code. { Statements Procedure Introduction to Programming ArcObjects with VBA

22 Writing Visual Basic statements
Carry out actions Written inside procedures May have arguments Multiple arguments are separated with commas Some arguments are optional Private Sub ShowMsgBox() Beep MsgBox "ESRI" End Sub Statements The smallest unit of Visual Basic code that can be executed is a statement. Statements are simply lines of code, and each statement carries out some simple action. Statements, therefore, are the building blocks for constructing sub procedures and functions. Although individual statements can be executed in the Immediate window, for practical purposes all statements will exist inside of a procedure. Statements may or may not have arguments. An argument is simply some extra piece of information that must be specified for a statement to work correctly. In the second statement above, for example, the MsgBox statement has the string ESRI as an argument. Without this argument, a message could not be displayed. Multiple arguments can be specified as a comma-delimited list, as shown below. '3 arguments: a Message, a Style, a Title MsgBox "Continue?", vbYesNo, "Abort operation?" I don’t want to argue You will often hear the terms argument and parameter used interchangeably, but they are not exactly the same thing. As a programmer using a function or sub procedure, you specify arguments. As a programmer writing a sub or function, you define parameters. In other words, they are called arguments when they are passed and parameters when they are received. 'Argument (intDollarAmount) … intTotalTax = CalcTax (intDollarAmount) 'Parameter (Amount) … Public Function CalcTax (Amount As Integer) As Integer CalcTax = Amount * 0.07 End Function Introduction to Programming ArcObjects with VBA

23 Some common Visual Basic functions
InputBox to get information MsgBox to report a message Combine (concatenate) strings with & … Get the Date or Time … InputBox "Enter the new Landuse Code: " MsgBox "ArcMap is Great!" MsgBox "The date is " & Date Visual Basic functions There are several predefined Visual Basic functions that you can use to do things like get the current date and time from the operating system, display several types of message and input boxes, concatenate strings, and convert data types. Open the Visual Basic help topic Visual Basic Language Reference > Functions for an alphabetical listing of VB functions. Message boxes To display various types of message boxes, use the Visual Basic MsgBox function. This function has only one required argument, a message (prompt) to display. By specifying values for the optional arguments below, you can further define the appearance of your message box. Buttons: Use any combination of Visual Basic MsgBox constants to specify the type of buttons, icons, or both to appear on the message box. To use several of these options, you can simply add the constants together. A sample of these constants is shown below. vbYesNo—place a Yes and a No button on the message box vbYesNoCancel—display a Yes, a No, and a Cancel button vbExclamation—display an exclamation mark image on the message box vbInformation—display an I image on the message box Several others Title: provide a string to appear on the message box title bar The code below will display a message box with Yes and No buttons, an exclamation image, and a title. MsgBox "Continue?", vbYesNo + vbExclamation, "Yes or No?" MsgBox "The time is " & Time MsgBox "The date and time is " & Now Introduction to Programming ArcObjects with VBA

24 过程类型Procedure types 事件过程Event procedures 子程序(SUB)和功能( Functions )过程
有一个相关联的对象Have an associated object (e.g., control) 当相应的事件发生时运行代码Code runs when the corresponding event occurs (e.g., click) 子程序(SUB)和功能( Functions )过程 没有相关联的对象No associated object 必须被调用才能运行Must be called 功能过程返回一个值Functions return a value Procedures All procedures are blocks of Visual Basic code and are simply a group of VB statements that are executed sequentially. There are some important distinctions that can be made about specific types of procedures, however, as described below. Event procedures Event procedures are associated with objects. More specifically, they are associated with an object event. Execution of these procedures is triggered when the associated event occurs. For example, when UIButtonControl3 is clicked, the code in the UIButtonControl3_Click event procedure executes. When the mouse cursor hovers over UIButtonControl3, the UIButtonControl3_ToolTip event procedure executes to display a tool tip. Every control, form, and the document itself has a suite of events for which you can provide code. Subs and functions Subs and functions are essentially no different than event procedures in that they are collections of Visual Basic statements that run sequentially as a unit of code. Subs and functions, however, are not directly associated with an object event. These procedures will only execute when they are explicitly told to run. Procedures carry out an action (adding a layer to a map, for example) but are not able to pass back a value. Functions, on the other hand, are generally used to produce some value to pass back to the procedure that called it (calculating and returning a total area, for example). You will learn more about these procedures in the next lesson. 'Run a Sub called AddLayer Call AddLayer 'Run a Function called CalcTotalValue, store a returned value in intTotalValue … intTotalValue = CalcTotalValue (intValueA, intValueB, intValueC) Introduction to Programming ArcObjects with VBA

25 Running an event procedure
控件(Controls)有预先定义的一组事件 你可以选择相应的事件去添加代码 当一个事件被激发,相关的代码将被运行 Click ! Controls respond to events All controls have a predefined set of events that they can respond to. A control responds to an event by running the associated event procedure—this does not mean you need to write code for every event that a control supports, however, only those required to make your control work. A UIButtonControl, for example, has five events that can be coded, but it is quite typical to write code only for the Click event. Each control type will have different available events available to code. A UIEditBoxControl, for example, has a Change and a KeyDown event for responding to user keyboard input, while a UIToolControl has events, such as MouseDown, MouseUp, and MouseMove, to capture user input from the mouse. The example When the control above (UIButtonControl1) is clicked by the user, its Click event code is executed (UIButtonControl1_Click), which reports the name of a layer in a message box. Introduction to Programming ArcObjects with VBA

26 UIButtonControl1 is clicked
在模块中浏览事件过程 Choose a control in the Object box Object box Procedure box Choose an event in the Procedure box 自动添加事件过程的封装行 Finding a procedure To start coding (or just to find) an event procedure in a particular module, select an object and an event procedure from the respective dropdown lists. The Object box (upper left) contains all the objects available in the module (e.g., UIControls), while the Procedure box (upper right) lists all the event procedures for the object selected in the Object box. If you choose an object and an event procedure for which there is already code, the module will scroll to this procedure. Otherwise, a new event procedure definition will be created. Wrapper code If the event procedure you chose does not exist, wrapper code will be automatically produced for you. Wrapper code (sometimes called stub code or template code) simply provides the procedure definition; the code you provide inside (between) the wrapper lines will be executed when the event is triggered. The example In the example above, UIButtonControl1 was chosen in the object list. Upon pulling down the procedure list, the five available event procedures for UIButtonControl1 are displayed. After Click is chosen from the procedure list, wrapper lines are automatically added to the code module (Private Sub … End Sub). The code inside the wrapper lines will execute when UIButtonControl1 is clicked and will simply display a message box that says ‘Hi’. MsgBox "Hi!" Write code to run when UIButtonControl1 is clicked A Introduction to Programming ArcObjects with VBA

27 The ThisDocument module
与一个文档相关的代码可以包含在: Normal template Current map document (mxd) Base template (optional) 可以在任何一个层次中客户化 How many documents do I have? As the name implies, the ThisDocument code module is associated with a document. You may become confused, however, on opening an ArcMap document to find three ThisDocument code modules. When you think of templates as documents, however, it makes perfect sense. Each level of ArcMap customization is represented by a document: Global customizations are stored in the Normal.mxt template, customizations applied to a set of map documents may be stored in a base (intermediate) template, and customizations meant for a single map document are stored in that map document itself. By writing code in the appropriate ThisDocument module, you are controlling the scope for your programs. What kind of code goes into a ThisDocument module? You may write any macros you want in ThisDocument, but perhaps most importantly, all code powering your UIControls will be written in one of the ThisDocument code modules. Remember that before adding a UIControl to the ArcMap interface, you must indicate (in the Customize dialog) where you want to store the new control (normal template, base template, or in the current document). Once you have made your choice, the code you write for the control will be in the corresponding ThisDocument module. For example, you create a new UIButtonControl, and save it in Normal. When you right-click the new interface control and choose View Source, you will find yourself writing code for the control in the ThisDocument code module under the Normal project heading. Introduction to Programming ArcObjects with VBA

28 Creating a new module Module (标准模块): 包含常量、子程序、功能过程等
Class module: 包含一个类的定义 UserForm: 包含代码、窗体的布局等 Creating a new code module New code modules can be added to your Visual Basic project by using the Insert menu on the Editor interface or by choosing Insert from the Project Explorer context menu (as shown above). When adding a new code module, be especially aware of where you are placing it (Normal, Base template, Current document). There are three types of modules you may add, which are described below. Module (standard module) Standard modules are used to write standalone procedures that you might want to call from other Visual Basic programs. The most common use of standard modules is to contain code that you use a lot. Instead of having to constantly rewrite the code to add a layer to a map, for example, you could place the code in a standard module in your Normal.mxt, then reference the procedure whenever it is needed. Class module Class modules are used to design custom classes. The ArcObjects library already has classes such as Maps, Layers, Symbols, and PageLayout. By writing code in a class module, you can define your own class to use in your programs. The specifics of programming a custom class will be discussed in more detail in Lesson 4. UserForm Module UserForm modules are code modules associated with a form (dialog). In the Visual Basic Editor, you can design a form by adding and rearranging controls (CommandButtons, TextBoxes, OptionButtons, etc.) and setting their properties. After the form layout is designed, you can write code in the associated form code module to make the controls work. You will design and write code for a UserForm in the next lesson. Introduction to Programming ArcObjects with VBA

29 Creating a new sub or function procedure (macro)
Scope: Public or Private Sub or Function: Functions return a value Parameters: List all required inputs Return Type: Type of data returned (functions only) Return Type Name Parameter List Scope Creating a new procedure To add a new procedure to a code module, you can choose Procedure from the Visual Basic Editor’s Insert menu, or you can simply type the procedure definition directly into the module. When defining a new procedure, you need to provide the following information. Scope Scope defines how widely a procedure may be used and can be defined as either Public or Private. A procedure that has a public scope can be called from any code module in the same project, while a private procedure can only be called from within the same code module. Sub versus Function The two basic types of procedures are Subs (sub procedures) and Functions. If you only need to perform some action and do not need to return a value, define your procedure as a sub. Functions can also carry out some action but also have the ability to return a value. For example, you could write a sub to add a layer to a map. The sub could simply take a pathname from the user and add that data as a new layer. By writing the same procedure as a function, you could add the data as a new layer, then also return a Boolean (true or false) value that describes whether the operation was successful or not. Parameters The parentheses following the procedure name are a required part of the procedure definition, even if they are empty. A sub or function might require some additional input to work properly, and this is where any required inputs (parameters) can be defined. If you were creating an AddLayer procedure, for example, you would probably define a layer as a required parameter. Notice that the parameters are defined with a name (e.g., Total) and a data type (e.g., As Double). Introduction to Programming ArcObjects with VBA

30 Defining procedure scope
Public:可以在任何模块中调用该过程 Private: 只能被同一个模块中其它过程调用 Procedure scope Sub procedures and functions can be defined as public or private in scope. A public procedure can be called from any module in the same project, while a private procedure can only be called from a sub or function inside the same module. When you define a new procedure, you need to consider whether or not the procedure should be called from outside its own code module. A procedure that enables controls on a particular user form would probably have a private scope because no other form would need to call that procedure. A procedure that calculates a total area value would probably have a public scope because this procedure would be useful for other modules to use. Running a procedure as a macro The following slides will describe how you can run your procedures as macros. In order to see your macros listed in the macros dialog (Tools > Macros > Macros) or in the Customize dialog box (Macros category), you need to make sure they have a public scope. Procedures defined as private will not appear (and therefore cannot be run) as a macro. Introduction to Programming ArcObjects with VBA

31 Running a sub() or function() procedure
没有事件去激活这些过程的运行 必须调用这些过程 通过宏菜单运行:从界面进行调用 调用过程的申明: 从代码中进行调用 Running a procedure Unlike event procedures, there is no object event to signal a subroutine or function procedure to execute. In fact, these procedures will never run unless they are explicitly told to. You can tell a subroutine or function procedure to execute in one of the following ways. From the interface To execute a procedure from the interface, choose Macros from the Tools menu. On the Macros submenu, again choose Macros. In the dialog that is launched, select the procedure you want to execute, then click Run. From code Subroutine and function procedures can be called from other code in your project, depending on where it is being called from and the scope of the procedure (review the previous slide on procedure scope). To execute a procedure with code, you can use statements like those below. 'With the Call statement Call MyOtherProcedure 'Simply call it using its name MyOtherProcedure Introduction to Programming ArcObjects with VBA

32 Adding a macro to a toolbar
Macros category of the Customize dialog Macro becomes a button on the toolbar Edit the control’s properties Adding a macro to a toolbar Macros that are defined with a public scope can be added to the ArcMap or ArcCatalog interface as a button on a toolbar or a menu choice. To access your macros and add them to the interface, launch the Customize dialog and open the Macros category on the Commands tab. Macros you find there can simply be dragged onto the interface like any other command in the Customize dialog. When it is placed on the interface, the macro will be given a default icon. To change this image, you may right-click the macro and choose Change Button Image. Adding a tool tip to a macro on a toolbar Unlike UIControls, macros added to the interface do not have events such as Enabled, ToolTip, and Message for you to code. However, there are ways to get at some of these properties programmatically. The VBA Sub below changes the tool tip and message for a macro called Project.NewMacros.Test. Private Sub ChangeToolTip( ) Dim pItem As ICommandItem Set pItem = _ ThisDocument.CommandBars.Find("Project.NewMacros.Test") pItem.ToolTip = "My ToolTip" pItem.Message = "My Message for the status bar." End Sub Introduction to Programming ArcObjects with VBA

33 Getting help F1 key for context-sensitive help
Visual Basic Help Topics ArcObjects Developer Help ESRI Web site Getting help ArcGIS and Visual Basic provide many ways to get help. There is help documentation available for Visual Basic as well as help specific to using ArcObjects. In addition to the traditional sources for help described below, there are several utilities available in the Visual Basic Editor for helping you write code. You will be exposed to several resources for help throughout the course. Context-sensitive help You can obtain context-sensitive help by highlighting a word in your code and pressing the F1 key on your keyboard. If the word you highlight is related to Visual Basic, the Visual Basic Help will launch and take you directly to the appropriate Help page; if the highlighted piece of code is related to ArcObjects, the appropriate ArcObject Help page will open. Otherwise, you will be told that no help is available. ArcGIS Developer Help When you install ArcGIS, you have the option of also installing the ArcObjects Developer Help. If you installed the Developer Help, you can access it from the Windows Start menu > Programs, in the ArcGIS program group. In addition to help on individual ArcObjects classes, the ArcObjects Developer Help has plenty of sample code that you can borrow and modify for your own applications. ArcObjects Online An online version of the ArcObjects Help is available from the ESRI Web site. ArcObjects Online contains updated code samples and documentation. You can even download the most recent version of the ArcObjects Help from here. You will find ArcObjects Online at the URL listed below: Introduction to Programming ArcObjects with VBA

34 Exercise 2 overview Explore the Visual Basic Editor
Navigate event procedures Add a new code module Run procedures Export code to a file on disk Exercise 2: Design a user form In this exercise you will do the following: Explore the Visual Basic Editor. Write simple VB statements in the Immediate window. Add a new control to the interface. Write code in various project modules. Run a macro from the interface. Run a macro from code. Export code. Introduction to Programming ArcObjects with VBA

35 Visual Basic code: How, where, and when?(II)
Introduction to Programming ArcObjects with VBA

36 在VBA中怎么编写代码 How? Where? When? Object-oriented programming
Visual Basic syntax Application and ThisDocument variables Where? Creating forms and controls When? Document, control, and form events Overview This lesson will discuss some of the fundamentals of writing Visual Basic code. You will learn about object-oriented programming, basic VB syntax, creating user forms, and coding various user events. This lesson will answer the following questions. How … … does object-oriented programming work? … do I write a Visual Basic statement? Where … … do I begin? … can I write code? … can I save customizations? When … … will my code execute? Introduction to Programming ArcObjects with VBA

37 Object-oriented programming
对象是 … Visual Basic: Forms, text boxes, command buttons, … ArcObjects: Maps, layers, symbols, tables, … 操作对象 Properties: Characteristics of an object Methods: Things an object knows how to do Events: Actions that an object can respond to Treat them like objects The (perhaps over-used) term object-oriented programming simply means that your programs work by using objects. Objects are basically anything you use in your Visual Basic code, whether visible or not. Things like maps, layers, symbols, and spatial references are all examples of ArcGIS objects, while UserForms, CommandButtons, and ComboBoxes are examples of Visual Basic objects. In object-oriented programming, you can work with existing objects (e.g., get the current map the user is working in), or you can create new objects (e.g., make a new layer to add to the map). Once you have referenced or created the objects you want to work with, you can manipulate them by using their properties, methods, and events. Properties: A property is a characteristic (noun) of an object that, as a programmer, you will be able to read (get) or write (set). As an everyday example, a computer might have properties such as RAM, disk space, and monitor size. Methods: A method is an action (verb) that an object can carry out. A computer might have methods such as boot up, log in, or crash. Events: Like methods, events are actions (verbs). Instead of actions that an object carries out, however, events are actions that an object responds to (usually actions triggered by the user). Events that a computer might have: type, move mouse, click mouse. Introduction to Programming ArcObjects with VBA

38 Example: Object-oriented terms
Map Car Property 地图单位 马力 Method 添加图层 加速 Event 选择集改变 踩刹车 Object-oriented programming terms Part of learning anything new, of course, is learning new terminology. Some common terms that you will hear throughout this course for describing object-oriented concepts are listed here. The objects you work with in your Visual Basic code are, in reality, nothing like real-world objects; they are simply blocks of code that are held in memory. Conceptually, however, they are very much like everyday objects in that they have characteristics (properties), actions they can perform (methods), and actions that they can respond to (events). The syntax for working with object properties and methods is described on the following page. Properties As described on the previous page, properties are characteristics of an object and are generally nouns (color, for example). When working with object properties, you can either get (read) them or set (write) them. In the example above, the ArcObject called Map has a property MapUnits. Notice that the property is a noun, indicating that it is some characteristic that the Map has. Similarly, an everyday object like car has a horsepower characteristic. Methods Methods are actions that an object knows how to perform. A car, for example, can accelerate when you tell it to. The ArcObject Map has a method called AddLayer. If a programmer wants to add a layer in ArcMap, he or she can ask a Map to do it. Events Events are another type of action that is associated with an object. Instead of being actions that the object performs, however, these are actions that an object can respond to. When you press the brake pedal in your car, for example, the car will respond by stopping (hopefully). Likewise, a Map can respond to the user making a new selection by executing some code that you provide (events will be covered in more detail in a later lesson). Introduction to Programming ArcObjects with VBA

39 How: Visual Basic syntax
Get the value of a property with Object.Property Assign a value to a property with Object.Property = value Call methods with Object.Method arg1, .., argN ArcObject events will be covered in Lesson 15 MsgBox "The map name is " & myMap.Name myMap.Name = "Zaire.mxd" myMap.AddLayer CityLayer myMap.SelectFeature CityLayer, KahembaPoint myMap.ClearSelection Visual Basic syntax Regardless of the object with which you are working, the VB syntax is basically always the same: the name of the object variable, followed by a dot ( . ), followed by one of the object’s methods or properties. Properties Follow the syntax below to set (assign) a new value to an object property. myObjectVariable.SomeProperty = ANewValue To get (read) an object property, use this simple syntax. myObjectVariable.SomeProperty Keep in mind that you may not be able to set (assign a new value to) all properties of an object. Oftentimes, you will find properties that cannot logically be given a new value. A Map, for example, has a LayerCount property. While it makes sense to get this property, it does not make sense to (and therefore you cannot) directly set a new value for LayerCount. Instead, this property will only be updated when layers are added to or removed from the map. Oddly enough, you will actually encounter some properties that can be set but cannot be read. (Look at the IFieldEdit interface for some examples.) Use the Visual Basic or ArcObjects help resources to learn whether or not you can get a given property, set a given property, or do both. Introduction to Programming ArcObjects with VBA

40 Preset ArcObjects variables
在VBA环境下的ArcObjects变量的全局变量 Application ThisDocument 作为编程的一个起始点 More about variables in the next lesson MsgBox "You are currently working in " & Application.Name MsgBox "The current map is " & ThisDocument.Title Where to begin? In ArcMap and ArcCatalog, you have two preset variables that will serve as the starting point for much of your code: Application and ThisDocument. These object variables are always available as soon as you launch ArcMap or ArcCatalog. While the number of methods and properties that are available on these variables is fairly limited, they serve as a stepping stone to other objects you might want to program with (maps, layers, files, etc.). Application Application is a preset variable that points to (you guessed it) the current application. In ArcMap, Application refers to the ArcMap application, while in ArcCatalog, it refers to ArcCatalog. In either environment, the Application variable will always have the same methods and properties. Below is a sample of some methods and properties available on Application. Caption: a read/write property to get or set the text that appears on the application’s title bar Name: a read-only property that will always return the name of the application as a string (ArcMap or ArcCatalog) RefreshWindow: a method to redraw the application window ThisDocument The ThisDocument preset variable points to the document that is currently open in the application. In ArcCatalog, ThisDocument always refers to the Normal.gxt template, while in ArcMap it refers to the current map document (.mxd). Unlike the Application preset variable, there are some differences in the methods and properties available on ThisDocument in ArcCatalog and ThisDocument in ArcMap. Object Property Introduction to Programming ArcObjects with VBA

41 Press Tab, Enter, or Space
VBA的自动代码完成功能 列出可用的属性和方法 当一个对象名被输入的时候自动显示 如果没有显示出自动完成的列表,则表示该对象没有被认证 使用 Tab, Enter, or Space 去选择所需的属性和方法 Press Tab, Enter, or Space Those who finish with the fewest keystrokes win One of the best ways to avoid getting errors in your Visual Basic code is to be lazy. The Visual Basic Editor has several utilities that help you write code by providing timely help, helping you navigate through code, and even completing some of your code for you. When you let Visual Basic automatically complete such code as variable names, methods, and properties, you avoid the possibility of making simple typographical errors that may cause run-time errors in your code. Auto Quick Info Auto Quick Info is a feature that was discussed briefly in the last lecture. As you type a statement that Visual Basic recognizes, a box (that looks like a tool tip) will pop up with the proper syntax required. You will be able to see all arguments required for the statement, as well as any optional ones (shown in square brackets). If the statement you are typing returns a value, you will also see the return data type (e.g., As Integer). Automatic code completion Upon typing an object variable that Visual Basic recognizes, followed by a dot, a list of all methods and properties available for that object will appear. You can then scroll through the list manually or type the first few letters to choose the method or property you want to use. Upon pressing Tab, Enter, or Space, the highlighted method or property will be added to your code. This automatic code completion feature is good not only because it saves you some typing, but also because it helps catch errors. If the code completion list does not appear when it should, it means that Visual Basic does not recognize the object variable you typed, and it’s likely that you made a mistake earlier in your code. Introduction to Programming ArcObjects with VBA

42 Where: Controls, documents, and forms
Create UIControls Store macros with the document 创建用户交互窗体(Form) 构建比message boxes and input boxes更复杂的用户界面 Where to write code The previous lesson discussed using the Visual Basic Editor to write standalone procedures (macros) and how to use the customize dialog to add macros or UIControls to the ArcMap or ArcCatalog interface. Another place you may want to write code is inside of a form module. Forms are nothing more than windows (dialogs) that contain a set of controls. Forms are ideal for certain types of user interaction, especially where a lot of data input may be required. Instead of having to pop up several message boxes or input boxes in your code, you can simply launch a single form to prompt for many pieces of information at once. Forms are also much more intuitive for a user to work with: There are various types of controls you can place on a form, each designed for a particular type of data input. Some common form controls are listed below (there are many others). TextBox: Displays or allows the entry of text. Use TextBoxes to display information or more commonly, to allow a user to type some input. In the example above, TextBoxes are used to accept latitude and longitude values from the user. OptionButton: Allows one selection to be made from a group of possible choices. OptionButtons are sometimes referred to as RadioButtons, as they function like the station preset buttons on old car radios: Upon selecting one OptionButton, all others automatically become unselected. In the example above, OptionButtons are used to indicate latitude (North, South) and longitude (East, West). Only one from each group may be selected at a given time. CheckBox: Displays the selected state of an item (checked=selected, unchecked=unselected). Use CheckBoxes to have the user answer yes/no questions. Introduction to Programming ArcObjects with VBA

43 Working with forms Form = window of controls + associated code
Code module Properties window Visual Basic forms When you add a UserForm module to your Visual Basic project, you are really adding two things: a form designer, in which you can add and position controls for the form, and a form code module that stores all the code required to make the form work. Adding a new form module To add a new form to the Visual Basic project, click the Insert menu on the editor interface or right-click in the Project Explorer window and choose Insert > UserForm from the context menu. When adding a form to an ArcMap document, be sure to add it to the proper project (e.g., normal.mxt or the current mxd) by highlighting the desired level of storage in the project explorer. All forms you add to an ArcCatalog project will be stored in the normal template (normal.gxt). Designing a form Remember that a form consists of a design window and a code module. A new user form will simply be an empty form designer to which you can add controls and an associated empty code module. By clicking and dragging from the toolbox to the form designer window, you can add several types of controls to the form. At design time for a form (in the form design window), controls behave like graphics: They can be added, removed, repositioned, and resized. All form controls will also have a set of properties that a programmer can define using the Properties window. Writing code for a form After the desired controls have been added to the form, positioned so they are intuitive for the user to work with, and their desired properties set, the next step is to write code to power them. Every control on a form will have a set of events for which you may provide code, as will the form itself. By providing code in the appropriate control event procedures, you can prepare the form for the anticipated user interaction. Form Designer Toolbox Introduction to Programming ArcObjects with VBA

44 Setting properties at design time
Select a control View or change properties with the Properties window Appearance: Caption, Font, BackColor Behavior: TabIndex, Locked, Enabled NAME Setting form and control properties The Properties window displays design time properties for the selected object (control or form) in the form designer. Upon selecting an object (by clicking it on the form designer or by choosing it from the Properties window dropdown list), you can set any of its design time properties by clicking in the Properties window. To set a common property for several controls at once, you can hold down the shift key or click and drag a box to select several controls. When more than one control is selected in the form designer, you will only see those properties common to all selected controls in the Properties window. Varying with the type of property, there are several ways in which they are set. Properties such as Name and Caption, for example, are set by simply typing in a new text value. Font, on the other hand, is set by launching the Font Properties dialog and defining font style, font size, bold, italic, and so forth. Some properties will toggle between true and false (e.g., Enabled), some will require numbers (e.g., Height and Width), and others will allow you to choose from a finite list of possible values (e.g., BackStyle). Naming controls One property that is common to all controls (and to the form itself) is the Name property. While the user will never care (or even know) what your controls are named, this property is very important to the programmer. In your code, you will always refer to controls by name. When a control is added to a form, a default name is assigned that simply consists of the type of control and the order in which it was added (e.g., CommandButton1). Ideally, controls should be named so the type and purpose of the control is apparent from the name alone. As a suggestion, name controls with a three-letter prefix that indicates the control type, followed by a description of what the control does (often this description will correspond to the control’s caption property). Note: If you will not need to reference a control in your code, it’s OK to keep the default name. Introduction to Programming ArcObjects with VBA

45 Writing code for a form UserForms 由一个设计器和一个代码模块组成 双击一个 control 去展开它的代码
Each control on a form has several event procedures Code Module Form Designer Writing code for a form and controls Each form has a code module that stores its associated code. All code that powers a form (including each form control) is stored in the form code module. After using the form designer, the form toolbox, and the Properties window to design your form, the next step is to write the code required to make the form work. Just as each type of control has a different set of design time properties for you to set, they also have a unique set of events for which you can write code. As a programmer, you do not need to write code for every control event, only the ones that are required to make your form work. There are several ways to access a form’s code module. The easiest way is to simply double-click a control in the form designer, which opens the form’s code module and places your cursor in the default event for that control (e.g., the Click event for a CommandButton). Optionally, you can toggle between the form designer and its code module by choosing Code or Object from the Visual Basic Editor’s View menu (as shown above). The Project Explorer window also has controls (at the top) for switching between these two components of your form. Introduction to Programming ArcObjects with VBA

46 Using control properties at run time
Get/Set properties with code while the form is running Syntax: Object.Property Controls are objects Private Sub cmdApply_Click() strFTemp = ( txtCelsius.Text * 9 / 5 ) + 32 lblFahrenheit.Caption = "Fahrenheit: "& strFTemp End Sub Getting and setting control properties at run time The properties you set in the form designer are used primarily to control the appearance of a form when it is first launched. When a user begins to interact with your form, however, it may also become necessary to get and set control and form properties during run time. Syntax for getting and setting control properties Remember that controls are Visual Basic objects, and the syntax for working with object properties is Object.Property. In the example above (when the form’s Apply button is clicked), the Celsius temperature entered by the user is referenced using the TextBox control’s Text property (txtCelsius.Text). A temperature in Fahrenheit is calculated and then placed on one of the form’s labels by setting the Label control’s Caption property (lblFahrenheit.Caption = "Fahrenheit: " & strFTemp). Run-time versus design time properties Most control properties can be set either at design time or at run time. Indeed, you will often provide an initial value at design time, only to change it in your code at run time. There are, however, some properties that may only be set at design time. Although you can get these properties at run time, you will receive an error if you try to set a new value at run time. Perhaps the best example of this is the Name property that each control has. If you provide a name at design time, you cannot change the name at run time. Controls that are added at run time, however, can also have their name set at run time. Consult the Visual Basic Help for control properties that are read-only at run time. Introduction to Programming ArcObjects with VBA

47 When: Form and control events
Code runs when an event fires Different controls have different sets of events Form events KeyPress Change Click Control events Every Visual Basic control has a set of events to which it can respond. As a programmer, you need to anticipate how your user will interact with the form and then write your code accordingly. Each type of control has a different set of events for which you can write code, although you do not need to code every control event. Below are some common control events and the type of code you might write for them. Control Event Example UserForm Initialize Set variables, fill combo or list boxes TextBox Change Enable/Disable controls according to what is entered KeyPress Check for a valid character before writing it to the TextBox (e.g., numeric values only) CommandButton Click Execute code with values on the form (e.g., TextBoxes), close the form OptionButton Click Update contents of list or combo boxes, enable/disable appropriate controls Initialize Click Click Introduction to Programming ArcObjects with VBA

48 When: Map document events
Available in the ThisDocument module Normal, base template, or current map (.mxd) Event procedures for the MxDocument object Open, close, new, change, etc. Object List Procedure List Document events In both ArcMap and ArcCatalog, code can be associated with events related to the document. In ArcCatalog, the document is simply the Normal template (normal.gxt), and code written here will execute every time the appropriate ArcCatalog event fires. In ArcMap, document events can be coded for one of three documents: the Normal template (normal.mxt), a base template (*.mxt), or the map document itself (*.mxd). Scope of ArcMap document events The three documents for which events can be coded in ArcMap represent different levels of customization. By writing your event code for the appropriate document, you can control the scope of ArcMap customization, as described below. Document event code in ArcMap’s Normal template will execute for all maps when the corresponding event occurs; this is a global customization. For example, you may want to display a custom splash screen with your company logo each time a map document is opened. To accomplish this, you would supply code in normal.mxt’s OpenDocument event. Document event code in an ArcMap base template (*.mxt) will execute only for map documents that were based on that particular template. You may have several parcel maps, for example, that will be produced from a template called ParcelMap.mxt. When a user of a parcel map changes to PageLayout view, you may want to display a custom toolbar. You would write such code in the ParcelMap.mxt ActiveViewChanged event procedure, thus providing this behavior for all future maps that are created from the template. For document event code that is specific to a single map, you can provide document event code in the map document itself (*.mxd). If you have one map that contains restricted information, for example, you could code the map’s OpenDocument event procedure to require a password before opening it. No other maps would exhibit this behavior. Introduction to Programming ArcObjects with VBA

49 Saving your work Save modules with a document Export modules
ArcCatalog normal template ArcMap normal template ArcMap template (*.mxt) Map document (*.mxd) Export modules Form file (*.frm): designer and code Standard and class modules Can be imported into other projects Saving maps and templates The primary difference between VBA and regular Visual Basic is that code in VBA must always be stored in a document. Unlike a programmer using standalone Visual Basic, a VBA programmer has no way of compiling his or her code into a DLL or EXE, for example. Therefore, in ArcMap and ArcCatalog (or any other application that uses the VBA development environment), all code is saved with a document of some sort. In ArcCatalog, all customizations are stored in a single document: Normal.gxt (in the user’s profiles). In ArcMap, remember that customizations (including code) can be stored at three different levels and with various types of documents. Whenever you write code in ArcCatalog or ArcMap, you are storing that code in some document on disk, whether you realize it or not. All ArcGIS code is stored in either a normal template (normal.gxt, normal.mxt), a base template (*.mxt), or a map document (*.mxd). When programming in ArcMap, you need to be especially careful where you place your code, as this will affect the scope of your customizations. Exporting code modules In addition to storing your code in one of the documents listed above, you also have the option of exporting code to a separate file on disk. To export a code module (user form, standard, or class module), right-click the desired module in the Project Explorer and choose ‘Export …’ from the context menu that appears. You will be prompted for a name and a location on disk for the exported file. When exported, a module’s extension will indicate whether it is a user form (*.frm), a standard module (*.bas), or a class module (*.cls). These files can then be imported into other projects such as another ArcMap document, ArcCatalog, or even a standalone Visual Basic project. Note that although you can easily export your code modules to disk, the code cannot be executed except in the context of an application such as ArcMap or ArcCatalog. Introduction to Programming ArcObjects with VBA

50 Exercise 3 overview Create a form Set initial control properties
Test and debug the form Work with preset variables Application ThisDocument Save your work Exercise 3: Design a user form In this exercise you will: Create a new user form. Add controls to the form. Set control properties at design time. Write code to convert degrees/minutes/seconds values on the form to decimal degrees. Test your form with actual latitude and longitude values. Write code using the preset Application and ThisDocument variables. Export your form to its own file on disk. Save your map. Introduction to Programming ArcObjects with VBA

51 Using variables(III) Introduction to Programming ArcObjects with VBA

52 在VBA中使用变量 变量定义 使用变量: 申明, 赋值, 比较 过程的参数传值和返回值 比较两个变量的值 分支: 判断语句 变量的作用域
Overview This lesson will cover the use of variables in your Visual Basic code. Basics of working with variables Declaring Setting Evaluating Storing values in a variable What kinds of data can be stored in a variable? Using variables to pass and return values. Using relational operators with variables. Decision-making structures If Then Select Case Variable scope Procedure Module Public This will discuss the use of variables to contain simple data types, such as numbers and text. The use of object variables will be covered in a later lesson. Introduction to Programming ArcObjects with VBA

53 Variables An empty box for storing values
Of a specific type (integer, date, string, etc.) The value stored can change 'the VB version of: a² + b² = c², is … dblCSquare = (dblA * dblA) + (dblB * dblB) ‘转换温度的计算 … intTempCelsius = InputBox ("Enter temperature (C): ") intTempFahrenheit = (intTempCelsius * 1.8) + 32 Remember 7th grade algebra? Variables are simply containers (like an empty box) that can contain a value, and if you have done any type of programming before you probably had to work with variables. The values stored by a variable may be numeric (bytes, integers, double-precision floating point decimals, etc.), text (string), dates, or even objects (such as forms, controls, maps, and layers). Variables (as the name implies) can change their value. For example, a variable called ‘myAge’ might have a value of 33 at one point and then be changed to store the value 43 shortly thereafter. According to the Visual Basic help, a variable is … “ … a named storage location that can contain data that can be modified during program execution. Each variable has a name that uniquely identifies it within its scope. A data type can be specified or not.” Uses for variables in a Visual Basic program Storing a value returned by a function or calculation datThreeWeeksFromToday = Date 'Date is a Visual Basic function that returns the current date from the OS Looping a specified number of times (covered in Lesson 7) For intCount = 0 To 200 Storing an object property intLayerCount = theParcelMap.LayerCount Storing user input theAnswer = MsgBox ("Format your hard drive?", vbYesNo) 'Using parentheses forces a return value. Representing constant values PI = Introduction to Programming ArcObjects with VBA

54 Working with variables
Declaring: Create a variable Setting: Store a value Evaluating: Get the value myDog Sparky Dim myDog As String myDog = "Sparky" MsgBox myDog Sparky myDog Working with variables Continuing with the variable-as-an-empty-box analogy, there are three things you will need to do in order to work with your box. To start with, you will need to create your box (define its size and the type of items it can store). You will then need to know how to place something inside it or get something out of it when you need it. Declaring variables To create a variable, you can declare it. Declaring a variable accomplishes two things: first, it specifies the name for your variable, and second, it defines the type of data to be stored in the variable. Although it is not technically required, it is good programming technique to declare all variables before you use them (and it is very poor programming technique not to declare them). The example above declares a variable called ‘myDog’, which will contain a string (text) by using the Dim statement (more about Dim on the following slide). Storing a value in a variable To store a (simple data type) value in a variable, use the equal sign ( = ). Whatever is evaluated on the right side of the equal sign will be stored in the variable. The example above is a simple assignment statement; the text Sparky is stored in the variable called myDog. Here are some more examples of assigning a value to a variable. strName = InputBox ("What’s your name?") 'The text typed from the user is stored in strName intMySistersAge = intMyAge – 'Whatever my age is, my sister will always be 2 years younger strApplicationName = Application.Name 'ArcMap or ArcCatalog? A Introduction to Programming ArcObjects with VBA

55 Dim (dimension) statement
申明一个变量 指定变量的类型 'Declare variables Dim strFilePathName As String Dim datSparkysBirthday As Date Dim intCount As Integer 'Other ways to declare variables (to be discussed later).. Private strFilePathName As String Public datSparkysBirthday As Date Static intCount As Integer Dim statement To declare a variable in Visual Basic, it is common to use the Dim keyword. Dim is short for Dimension (although using the word Dimension would give you an error). As the name implies, Dim defines what will be stored in your variable and therefore the amount of memory required for it. There are three parts to a Visual Basic variable declaration statement: the declaration keyword (Dim, Private, or Public), the name of the variable, and the type of data (or object) to be stored. The significance of using the Dim, Private, or Public keywords will be discussed shortly. When using the Dim statement, it is a good practice to declare all variables using mixed case with the first letter in lower case. Using mixed case in variable names will allow for easier debugging later (as you will soon discover). Listed below are the simple data types that you can dimension a variable to store, as well as the amount of memory allocated. Type (bytes) Sample value String (10+length) Elm Street Boolean (2) True or False Date (8) 1/1/100 to 12/31/9999 Byte (1) 0 to 255 Integer (2) to 32767 Long Integer (4) -2,147,483,648 to 2,147,483,647 Single (4) E-45 to E38 positive Double (8) E308 maximum Variant (>16) Any type Introduction to Programming ArcObjects with VBA

56 ! 变量赋值 直接赋值或通过返回值赋值 如果是一个功能过程的返回值赋值,使用圆括号 'Assign values directly
intCount = 23 'Assign a function return value strFilePathName = InputBox("File to open: ") 'Assign an object property strMapName = ThisDocument.Title ! Assigning a value to a variable To assign a value to a variable, use the equal sign. Whatever appears or is evaluated on the right side of the equal sign will be stored in the variable. Variables may be given a value explicitly, or may derive a value from a calculation, function, or object property. Fun with variables It is safe to say that most pitfalls encountered when debugging an application can be directly attributed to variables. Below are illustrated some common problems. Order of evaluation is always left to right. Use parentheses to change this order. dblAnswer = 2 * / 4 – 1 'This evaluates to dblAnswer = (2 * 4) + 8 / (4 – 1) 'This evaluates to Storing a decimal number in an integer variable will not give an error; instead, the number will be rounded behind your back. Dim intAnswer As Integer intAnswer = 3 / 4 'intAnswer now contains the value 1 A value will not be returned from a function unless you place parentheses around the argument list. intAnswer = MsgBox "Will you marry me?", vbYesNo, "A Proposal" 'This will give an error intAnswer = MsgBox ("Will you marry me?", vbYesNo, "A Proposal") 'This works. Introduction to Programming ArcObjects with VBA

57 Function procedures Functions return a value
… by assigning a value to the function name Syntax for calling a function: Value = Function ( arguments ) 'Call the TotalPrice function Private Sub Purchase() dblPrice = InputBox ("Enter price before tax:") dblTotal = TotalPrice(dblPrice) MsgBox "Here is the price including tax: " & dblTotal End Sub 'The function procedure TotalPrice Private Function TotalPrice(Price As Double) As Double TotalPrice = Price * End Function Function procedures Remember that the only difference between a vanilla-flavored sub procedure and a function is that a function procedure has the ability to return a value. Visual Basic has some built-in functions that you have already worked with such as MsgBox and InputBox. As a programmer using these functions, you can treat them simply as black boxes; you know what needs to be put in, you know what you will get out, but you do not need to be concerned with how the function actually works. In addition to using the standard Visual Basic functions, you may want to write your own. Functions can make your life easier as a programmer because they give you the ability to centralize useful pieces of code into reusable units. For example, you might write a function that returns the average area for a polygon layer. Anytime you need this functionality, you can simply call your function, passing in the required layer argument, instead of having to rewrite the functionality (sub procedures can also be reused to perform common tasks; they cannot, however, return a value). Returning a value from a function As a programmer writing a function procedure, you have the ability to return a single value or object (however, this single object could be a Collection object that contains several objects). In the function definition, the programmer specifies the type of object or value to be returned, as well as any required inputs (parameters). Inside the function, the programmer can refer to values passed to the function by the names listed in the function definition. In the code above, for example, Price is listed as a required function parameter (as a double). Inside the function procedure, the variable Price will refer to whatever was passed in when the function was called, regardless of what this variable may have been named in the calling procedure. To pass a value back from a function, the programmer simply sets the name of the function equal to the value he or she wants to return. Introduction to Programming ArcObjects with VBA

58 比较变量的值 Use relational operators ( <, >, <>, = ) Functions
Return a Boolean result (true/false) Functions IsDate IsNumeric IsNull TypeName intAnswer = MsgBox ("Delete File?", vbYesNo) MsgBox intAnswer = vbYes MsgBox "Number? " & IsNumeric(VagueVariable) strType = TypeName (VagueVariable) MsgBox "Variable is of data type " & strType Boolean expressions evaluate to True or False In order to make decisions in your code at run time, you might need to evaluate certain conditions. Common decision making in Visual Basic uses a Boolean value (True or False) in order to run corresponding sets of code. To evaluate a variable and return a True or False result, you can use familiar relational operators such as < (less than), > (greater than), = (equal to), and <> (not equal to). Visual Basic MsgBox constants The Visual Basic message box function does not return a Boolean result. Instead, it returns a numeric value that can be referred to by a constant name. The Visual Basic MgBox constants are: vbYes, vbNo, vbCancel, vbAbort, vbIgnore, vbRetry, and vbOK. If you need a Boolean value, you can compare the message box result with a particular constant (as shown in the first example above). Connectors In order to check several criteria and return a single Boolean value, you can string together more complex expressions by using connectors such as and, not, and or. To return a True result, both conditions of an and statement must be true; only one condition of an or expression needs to be true to return a True result. The not connector is used to reverse the result of an expression. Introduction to Programming ArcObjects with VBA

59 判断语句: The If Then statement
根据条件分支执行 Use a Boolean expression 作出决定如何执行 ? 'Syntax example: If a condition is true Then 'do something... End If If intLayerCount < 1 Then MsgBox "There are no layers in your map!", vbExclaimation End If If Then The If Then statement in Visual Basic is used to provide a decision making mechanism in your code. There may be situations in which your program will break under certain conditions such as dividing by zero. In order to avoid such pitfalls and to gracefully handle these situations, you can write an If Then statement like the one below. Dim intNumber As Integer intNumber = InputBox ("Enter a number to divide 10 by") If intNumber = 0 Then MsgBox "No division by zero!!" 'This code only 'executes if intNumber = 0 'Code here to exit the procedure .. End If MsgBox "Ten divided by " & intNumber & " is " & 10 / intNumber ' intNumber can never be 0 at this line above Any expression or variable that evaluates to a Boolean value (True or False) may be used as the basis of an If Then statement, like all of those shown below. IsNumeric (strApples) MsgBox ("Continue?", vbYesNoCancel) = vbYes myMap.LayerCount > 0 And Not IsNull (intParcels) blnAnswer True Note: Parentheses may be used for clarity but are not a required part of the If Then syntax. If (strName = "Paxton") Then works the same as … If strName = "Paxton" Then Introduction to Programming ArcObjects with VBA

60 Controlling If Then Exit Sub: Exits procedure before completion
ElseIf: Check another condition Else: Code for a False condition Private Sub WelcomeUser() If strUser = "Mark" Then MsgBox "Welcome Mark" ElseIf strUser = "Dana" Then MsgBox "Welcome Dana" Else MsgBox "You are not an authorized user!" Exit Sub End If 'Code here to add layers to the map … 'Code here to start an edit session … End Sub Controlling the flow of an If Then statement If Then statements in Visual Basic can be more complex that those that simply evaluate a single condition. If needed, a programmer can evaluate numerous conditions in a single If Then block by using keywords such as ElseIf and Else. Inside an If Then block, execution of the entire procedure may also be terminated early by using Exit Sub. Exit Sub When the Exit Sub line of code is encountered, execution of the procedure is terminated immediately. Exit Sub will generally only appear inside of an If Then block in the context described below. Often, the purpose of an If Then statement in your Visual Basic code is to check for a condition that will cause a run-time error. If your code asks the user to input a currency amount, for example, you would want to verify that the input is numeric (e.g., instead of $20.00, or twenty) before attempting to use it in a mathematical operation. If the value is not numeric, you need to stop execution of the procedure before an error occurs, as shown below. dblPrice = InputBox ("Please enter a price (without a dollar sign or commas)" ) If Not IsNumeric (dblPrice) Then ' check to see if the input is NOT 'numeric MsgBox "Please enter only numbers!", vbExclaimation, "Exiting" Exit Sub '**Stop execution of the procedure if the error- 'causing condition is true!** End If dblDiscount = dblPrice * ' calculate a 20% discount on the 'price, this line will only execute if dblPrice is numeric Introduction to Programming ArcObjects with VBA

61 判断语句: The Select Case statement
根据一个变量的值来进行分支 可以是一个值的范围或者一个值的列表 大小写敏感 相当于几个IF Then 语句 Select Case someVariable Case Is = someValue 'Do this Case someValueA, someValueB, someValueX 'Do that Case startValue To endValue 'Do the other Case Else MsgBox "Invalid entry!" End Select Select Case In addition to the If Then branching construct, a Visual Basic programmer can also use a Select Case statement to make decisions in his or her code. Unlike an If Then statement, Select Case makes decisions based on the value of a variable instead of using Boolean expressions. These values do not have to be numeric; a Select Case statement could also use variables that contain strings, dates, and so on. For this reason, Select Case is better suited for evaluating a value against a range or list of values, as shown in the example below. intBirthDay = InputBox("Enter your age on your next birthday") Select Case intBirthDay Case Is < ' **evaluate a relationship MsgBox "C’mon! You aren’t even born yet??!!" Case 1 To ' **evaluate against a range MsgBox "Enjoy yourself before you begin school!" Case 16, 18, ' **evaluate against a list MsgBox "Your next birthday will be a landmark!" Case ' **evaluate against a single value MsgBox "Congratulations! You’re now eligible for the Senior ‘Discount!" Case Is > ' **evaluate a relationship MsgBox "Willard Scott will read your name on the air!" Case Else ' **if none of the cases above are true MsgBox "There’s nothing interesting about your next birthday" End Select Introduction to Programming ArcObjects with VBA

62 变量作用域层次关系 Procedure-level: Local to a single procedure
Module-level: Local (private) to a single module Public-level: Available to all project modules Module-level Variable scope The term scope, when referring to a variable, describes the lifetime of a variable or how widely it can be used within a Visual Basic project. As you will see, depending on how you declare a variable, it might be available throughout your entire project, within a single procedure, or somewhere in between. In a Visual Basic project, you will work with three levels of variable scope: procedure level, module level, and public level. House pets analogy You can think of variables as house pets, each one with a different scope, or range of territory. Procedure-level variables: Procedure-level variables are local to a single procedure (sub or function). Like the goldfish in the slide above, they are restricted to a single goldfish bowl (procedure), outside of which they cannot live. Module-level variables: Module-level variables are variables that can work within a single module. Like the housecat above, these variables can roam within a single house (module) and can visit each goldfish bowl (procedure) inside the house. The housecat is not allowed outside of the house, however, as she will instantly be hit by a garbage truck. Public-level variables: Public-level variables have the widest scope; they are global to an entire Visual Basic project. Public-level variables are like the dog in the slide above. They can freely roam the neighborhood (project) and are welcomed in every house (module) they come to (OK, so they are not exactly like dogs). Public-level variables are not destroyed until the project closes. Public-level Procedure-level Introduction to Programming ArcObjects with VBA

63 Procedure-level variables
在一个过程中定义 超出过程将不可识别 当过程结束,将被注销 'Procedure1 Private Sub cmdSet_Click() Dim intNumber As Integer intNumber = intNumber + 1 lblnumber.Caption = intNumber End Sub 1 Procedure-level variables Procedure-level variables (often called Local variables) can be seen only in the procedure in which they are created (declared). Procedure-level variables are declared using the Dim statement inside a procedure (sub or function). Any variable that is declared inside of a procedure will automatically be procedure-level in scope. Procedure-level variables are re-dimensioned each time the procedure executes. They are also destroyed each time the procedure ends, which means their value cannot be retained between calls to the procedure (this is not true for Static variables, which will be described later). The example In the example above, the first procedure declares a procedure-level variable called intNumber. When the procedure is executed, the Dim statement will create this variable and initialize it to 0. (In Visual Basic, numeric variables are set to 0 when they are declared; this is not true for many other languages such as C++.) The next line of code increases the value of intNumber by 1. Finally, the value is placed on a label on the form. Because intNumber is a procedure-level variable, however, it is destroyed each time the procedure finishes, then re-created (and set to 0) when it runs again. This means the label will always read ‘1’ no matter how many times the user clicks the button. The next procedure in the example tries to use the intNumber variable. Because intNumber was declared in another procedure, it is not recognized here, and an error is reported when the code is executed. 'Procedure2 Private Sub someOther_Event() lblnumber.Caption = intNumber 'Procedure 2 can’t see it 'and causes an error. End Sub Introduction to Programming ArcObjects with VBA

64 Module-level variables
在模块的定义部分使用 Dim 或 Private 关键字定义 Must initialize (assign a value) within a procedure Available to all procedures in a module Declaration Initialization Module-level variables Module-level variables are variables that can be used throughout an entire code module. Unlike procedure-level variables, module-level variables are not destroyed after the execution of a procedure. Therefore, the values of module-level variables can be retained and referenced (or changed) by any procedure inside the module. The variables declared in a module will, however, be destroyed when (if) the object represented by the module is destroyed (i.e., user forms and classes). Module-level variables, of course, cannot be referenced by procedures in other modules. Module-level variables can be declared in any code module (standard module, form module, or class module). To declare a module-level variable, simply place the declaration statement in the module’s General Declarations section (which is simply the very top of any code module). The declaration statement for a module-level variable can use the familiar Dim keyword or the keyword Private. There is no difference between using Dim or Private in a module-level variable declaration, although the Private keyword is preferred for clarity (you are, after all, declaring a variable that will be private to the module). Although module-level variables must be declared in a module’s General Declarations section, they cannot be initialized (set) there. You can only assign values to a variable within a procedure. Module-level variables in a User Form It is quite common to use module-level variables in a form module. Remember that module-level variables are declared in General Declarations but cannot have values assigned there. When using module-level variables in a form module, therefore, the best (and therefore most common) place to initialize module-level variables is in the UserForm_Initialize event procedure. Because Initialize is the first event procedure to fire for a form, all later event procedures (button clicks, etc.) will have access to the module-level variable values. Introduction to Programming ArcObjects with VBA

65 Public-level variables
如果定义在一个窗体中,则其它模块必须先引用窗体名 工程中的任何位置都是有效的 MsgBox “Hello “ & GetName(frmHello.g_intID) frmHello Module1 Public g_intID As Integer Private Sub SetID() Randomize g_intID = Int(11 * Rnd) 'more code here End Sub Public Function GetName()as String Select Case frmHello.g_intID Case 0 GetName = “Hercules” Case 1 'more code here End Sub Public-level variables Public-level variables have the widest scope of all Visual Basic variables. They can be referenced from any procedure in any module inside the project, making them truly global variables. Public-level variables can be declared in any code module (standard module, form module, or class module). To declare a public-level variable, simply place the declaration statement in the module’s General Declarations section (just as you would for a module-level variable). The declaration statement for a public-level variable must use the Public keyword. Although module-level and public-level variables are always declared in a module’s General Declarations section, they cannot be initialized (set) there. As a reminder, values are always assigned to any variable inside a procedure. Tips for using public-level variables As a general rule, the use of public-level variables should be avoided whenever possible. Public variables will remain in memory for as long as your application is running, unless you explicitly destroy them. This can take up valuable memory resources and may be difficult to manage. If you need to use public variables, it is best to declare them in their own standard module. This way, you can easily keep track of the variables that you have defined with a public scope. You should be careful when declaring public-level variables in a form module because even though they are public-level in scope, these variables will be destroyed when the associated form is unloaded from memory. When referring to a public-level variable that was declared in a form module, you must preface the variable name with the name of the form, as shown in the slide above. Introduction to Programming ArcObjects with VBA

66 静态变量 1 2 3 在过程的第一次运行时被初始化 在过程被调用中,一直保持变量值 仅在过程级的变量中可以定义
Private Sub cmdSet_Click() Static intNumber As Integer intNumber = intNumber + 1 lblNumber.Caption = intNumber End Sub 1 Static variables Static variables are simply another flavor of procedure-level variable. Although static variables can still only be referenced inside the procedure in which they were declared, they have the advantage of remembering their last value. In other words, each time you call a procedure that uses a static variable, you can get at its last value. The Static keyword is used to declare procedure-level variables only. You cannot declare a module-level or public-level variable with the Static keyword. Module-level and public-level variables are, by nature, static. They retain their values until their associated module or project are unloaded from memory. The example Remember the earlier example for procedure-level variables? In that example, the Dim statement was used to declare the variable, which meant that the variable’s value would be destroyed each time the procedure finished and then reinitialized (to 0) when the procedure was called again. In the example above, intNumber is still procedure-level in scope, which means it cannot be recognized outside of this procedure (Private Sub Count). Its value, however, will not be destroyed when the procedure finishes execution. This means that the variable can now act as a counter and effectively keep track of how many times the user calls the procedure (clicks the Set button). 'Click Set a second time: 'Click Set a third time: 2 3 Introduction to Programming ArcObjects with VBA

67 Programming with class(IIII)
Introduction to Programming ArcObjects with VBA

68 使用类来编程 理解类和对象的关系 理解类库 从类中实例化一个对象 申明和使用一个类 创建自定义类 发布自定义类 Overview
This lecture will discuss some of the more important concepts of object-oriented programming. Classes defined The difference between an object and a class Where classes come from Class libraries Referencing additional class libraries How to work with existing classes Using the Visual Basic object browser Instantiating objects Working with object variables How to write your own class Client versus server code How to share your classes with other users Exporting code modules Introduction to Programming ArcObjects with VBA

69 Class 一个创建对象的蓝图 定义了对象的属性和方法 一些类是可以使用New创建的 New Car Car Class Class
A class is really nothing more than a blueprint (or template) that defines how objects created from the class will look and behave. A class defines all the properties and methods that a particular type of object will have. As a familiar example, all the command buttons you have added to your Visual Basic forms belong to the CommandButton class. The CommandButton class defines all properties, methods, and events that any CommandButton object will have. In other words, every CommandButton you create (add to a form) has the same set of properties available in the Visual Basic properties list such as Caption, BackColor, Name, Font, and Height. It has the same set of events that you can write code for such as Click, DblClick, and MouseDown. Does this mean that every CommandButton you create will look exactly the same? Of course not. Although the same properties, methods, and events will be available on each object created from the CommandButton class, they can be coded uniquely. Code that defines a class is stored in a special type of module, called a Class module. Later in this lesson, you will learn how to create your own classes by writing code in a Class module. Car analogy Cars provide a good analogy for classes and the objects they create. You can think of the car factory as the Class. The factory knows how to produce a certain type of car—a Ferrari, for example. The blueprint of the car used by the factory dictates that each Ferrari produced will have certain characteristics and behaviors. The factory can produce new Ferraris, and each one will be made from the same definition. Introduction to Programming ArcObjects with VBA

70 Classes and objects Objects of the Car class Objects of the Map class
Color: Red Engine: V12 Year: 1997 Color: Blue Engine: V12 Year: 1998 Car class Color Engine Year Objects of the Car class Map class Label Extent Layers Scale Projection Classes and objects The terms Class and Object are often used interchangeably, although there is an important difference between the two. Remember that a class is the definition for how an object will look and behave. In this respect, a class is abstract; it is not real. An object, on the other hand, is a concrete thing that has been created from a class. An object, of course, has all the characteristics and behaviors that have been defined on the class, but it is a real object that can be manipulated in your code. In other words, you are able to get and set an object’s properties, call its methods to carry out tasks, or write code to respond to its events. Car analogy continued To continue with the car analogy, the Ferrari factory (Class) will create new Ferraris (Objects) that have identical designs (methods, properties, events). Each Ferrari object that is produced, however, can have different values for its predefined properties. For example, one Ferrari might have the value Blue for its Color property, while the next has the value Red for this same property. Although the Ferrari factory knows how to create new cars, you could not put a key in the factory, start it up, and drive off. Likewise, you could not ask a Ferrari object to make a new Ferrari. An ArcObjects example There is an ArcObjects class called Map. The Map class defines the properties and behaviors that all maps have. Obviously, this does not mean that all maps you work with in ArcMap will be identical—simply that they will all have the same familiar properties such as Scale, Spatial Reference (Projection), and Layers (none, one, or several). Every map is produced from this same mold, ready to be manipulated by the map user. Objects of the Map class Introduction to Programming ArcObjects with VBA

71 Class libraries 类库包括了类的定义 可以应用其它的类库 保存在文件中 (DLL, OLB, TLB, EXE, OCX)
ArcObjects are in esriCore.olb 可以应用其它的类库 ArcMap/ArcCatalog always reference esriCore Class libraries A class library is simply a collection of several classes that are contained within a single file. Class libraries are generally stored in files with extensions such as .DLL, .OLB, .EXE, or .OCX. Visual Basic for Applications has its own library that contains all the classes you work with in VBA such as Strings, Math, and Collection. The Microsoft Forms library contains all the classes you have worked with to create user forms such as Forms, CommandButtons, and TextBoxes. All of the ArcGIS objects are defined in the ArcObjects library (esriCore) and contain classes such as Map, Layer, Polygon, and Table. Referencing a class library As a programmer, you have the ability to control which class libraries you work with in a given project. You can bring in additional libraries or remove existing ones from your Visual Basic project by choosing References from the Tools menu on the Visual Basic Editor toolbar. The References dialog (shown above) allows you to browse available class libraries, remove libraries that are currently referenced, or check libraries to bring them into the project. By referencing additional libraries, you give yourself access to more objects, and you may be surprised by the number of class libraries available on your machine. If you have Internet Explorer, Crystal Reports, or Visio, for example, you can reference and use the classes available in those applications in your own application. Note that when programming an application with VBA, you will always have a default set of class libraries referenced. In ArcMap and ArcCatalog, for example, you will always have a reference to the ArcObjects library, as well as the VBA and the Microsoft Forms library. All classes defined in these libraries will be available in your project as soon as you start the application. You only need to make a reference to a class library if you want to bring in classes that are not defined in one of these default libraries. Introduction to Programming ArcObjects with VBA

72 Exploring class libraries with the Object Browser
Properties and methods Classes list Arguments and return values Library list Search string Search matches The Visual Basic object browser The Visual Basic Editor comes with a utility for browsing the contents of class libraries called the object browser (remember that object and class are often used interchangeably, so it would be more accurate to call this a class browser). This utility can be very helpful for writing your Visual Basic code. It provides a quick reference for which classes are available, as well as what they can do for you. In later lessons, you will explore some other utilities that give you information about classes, such as the ESRI object browser and the ArcObjects object model diagrams. Using the object browser The object browser can be launched by pressing the button shown above or by choosing ‘Object Browser …’ from the View menu. At the top of the object browser is a pulldown list for choosing a class library to search. You will see all referenced class libraries listed here (including the current project and the Normal.mxt file, which are also considered libraries). By default, the object browser will search all referenced libraries. Below the library list is a text box for typing a search keyword. After providing a keyword and pressing enter (or clicking the search button to the right), the object browser will display all matches for the string (whether it appears in a class name, property, method, etc.). By selecting a match in the search results list or a class in the class list, a list of members will be displayed in the object browser. Members are basically methods and properties but could also include events. To get more information about a member, highlight it in the member list and a description of its syntax (e.g., required arguments) will be displayed at the bottom of the browser. Introduction to Programming ArcObjects with VBA

73 Object Browser icons Property Method Event Module Class Others …
The Object Browser uses many different symbols to represent items found in a class library. These icons give you a quick way of distinguishing the various types of things illustrated in the object browser. Although there are several of these symbols, the handful shown above are the ones you will generally be concerned with. Notice that the icons that appear in the Visual Basic Object Browser are the same ones that appear in the Visual Basic code completion list when you are typing your code. Introduction to Programming ArcObjects with VBA

74 Creating objects at design time
ArcMap: Customize dialog box VBA: UserForm Toolbox Objects Class Class Library Design time The term design time refers to the part of the application development process when you are creating forms and controls, changing control properties, modifying the user interface, and so on. At design time, you work in an interactive environment with objects such as forms and controls. Creating objects at design time Whether you realized it or not, you have already created objects in this course. At design time when you add a new UIControl to the ArcMap or ArcCatalog interface, you are creating a new object. When you create a new user form or add new controls to a user form, you are also creating new objects. These objects have been defined in one of the available class libraries, and by placing them on the interface or on a form, you are producing an instance (or object) from that class. The example: classes and objects revisited In the slide above, you can think of the Toolbox as a visual representation of a class library. It contains all the possible controls you can place on a form. Each of the controls on the Toolbox is like a class; they define the methods, properties, and events for each type of control. If you click one of the controls in the Toolbox, does it do anything? Can you change the properties of one of these controls? No—the controls in the Toolbox simply provide the template for actual controls. Once you drag a control from the Toolbox to the form, however, you have created an object (an instance of that particular class of control). Now, working with the object, you can change its properties. You can resize it, change its name and its color, and write code for its click event. If you add another control of the same type (class), it will have the exact same set of methods, properties, and events, but you may choose to use them differently. Object Properties Introduction to Programming ArcObjects with VBA

75 在代码中实例化一个对象 Declare an object variable (As Class) 使用Set关键字对对象进行赋值
Use New to create Use methods and properties Dim myDog As Dog Set myDog = New Dog myDog.Bark DOG Run time The part of the development process dedicated to executing code is referred to as run time. Declaring an object variable Working with objects in code is similar to working with intrinsic data values (such as numbers and strings) in that the first step is to declare a variable. Object variables are declared the same way as variables that store standard data types: by using the Dim, Static, Private, or Public keyword and specifying an object type to store. Just as you would declare a variable as Integer, String, or Date, you can declare a variable as CommandButton, Collection, or IPageLayout (more about interfaces later). Once you have declared a variable as a particular type of object, it will only be able to store that type of object. Instantiating or creating an object variable Setting an object variable equal to a new or existing object is called instantiating an object. Making an object brand new is referred to as creating an object. As you will learn in more detail later, not all classes allow you to create their objects new. Whenever you instantiate any object variable (unlike intrinsic data variables), you must use the Set keyword. As with intrinsic data variables, whatever is evaluated on the right side of the equal sign is stored in the object variable. For classes that allow objects to be created new, use the Visual Basic New keyword. Below are examples of instantiating an object variable with an existing object (a layer in the map) and creating an object with the New keyword (a new Visual Basic Collection object). Bark Name Color Growl CallPet Introduction to Programming ArcObjects with VBA

76 To Set or not to Set? 'Using VB objects Dim myButton As CommandButton
Set myButton = frmMain.cmdApply 'Using ArcInfo objects Dim myMap As IMap Set myMap = New Map 'Using variables of "intrinsic" data types Dim x As Integer x = 1234 '  No SET keyword When to use Set One of the most common pitfalls for new Visual Basic programmers is knowing when—and when not—to use the Set keyword with variables. The answer is really quite simple, although it may take a little practice before it sticks. You must use Set when you are instantiating an object variable of any kind. You must not use Set when you are assigning a value to a variable of a standard data type (strings, numbers, dates, etc.). Can you write it down? A quick way to remember the rule for using Set is to keep in mind that anything you can write down on a piece of paper is an intrinsic (standard) data type. Anything you cannot write down on a piece of paper (drawing pictures does not count) will require the use of the Set keyword. Variable Type Write It? Use Set? datBirthday Date /28/ No intAge Integer No blnMarried Boolean False No strName String Wendy No myMap Object ? Yes Set myMap = New Map Variable naming conventions continued There is one more convention to add to your list of naming standards. In much of the code you encounter (and a lot of it in this course), you will notice that object variables are named with a preceding lowercase ‘p’. This stands for pointer, as object variables do not really contain the object (the way an integer variable contains an integer); instead, they simply point to the referenced object. Introduction to Programming ArcObjects with VBA

77 Coding a class with Visual Basic
Class module Define methods Define properties Use the class Set properties Get properties Call methods Class module: Methods The general procedures of the Dog class module define the class’s methods. In the example, the Bark procedure contains code that will run when any Dog instance calls its Bark method. Class module: Properties A class module also contains property procedures that can store and return values. For example, the Get and Let property procedures below set up storage and retrieval for Dog’s Name property. 'This is server code. Private mDogName as string Public Property Get Name() As String Name = mDogName End Property Public Property Let Name(ByVal vNewName As String) mDogName = vNewName Instantiate a dog and set its Name property: 'This is client code. Dim MyDog as Dog Set MyDog = New Dog MyDog.Name = "Rex" Introduction to Programming ArcObjects with VBA

78 Client and server environment
类是服务端的代码 Class modules, class libraries (e.g., ArcObjects) 客户端的代码使用定义好的类 ArcObjects Library Map Layer Table MyClass Microsoft Forms Library Command Button Text Box Form Server Client Client and server relationships In COM there is a relationship between client code and server classes. The server provides functionality that a client uses. COM facilitates the communication between components. In a COM system, the client, or user of functionality, is completely isolated from the server, or provider of that functionality. All the client needs to know is that the functionality is available. With that knowledge, the client can make calls to the server and expect the server to honor them. In this way COM acts as a contract between client and server. If the server breaks that contract, the system may not respond as expected. In this way COM development is based on trust between the implementer and the user of functionality. A developer using ArcObjects can assume all these properties and methods have been fully implemented and are there to use if they are present on the object diagrams.  Server storage: EXEs and DLLs The client and its servers can exist in the same process or in a different process space. In process servers are packaged in DLL form and loaded into the client’s address space when the client first accesses the server. Out of process servers are packaged in EXEs and run in their own address spaces. There are diametrically opposed pros and cons to each packaging method. DLLs load into memory faster, and DLL functions are faster to call. Executables, on the other hand, provide a more robust solution (if the server fails, the client will not crash) and better security because the server has its own security context. In a distributed system, EXEs are more flexible, and it does not matter if the sever has a different byte ordering to the client. Introduction to Programming ArcObjects with VBA

79 发布你定义的类 Save the class in a map or template
Save the class module in its own file Export to create a CLS file Others can load CLS file into their project Create a DLL, OCX, or EXE file Cannot do this with VBA Use Visual Basic 6, C++, or similar program Export a class file You can share your class with others by exporting your class (CLS) file. Anyone with Visual Basic can import the file. If your file is dependent on any libraries, anyone importing the class file will also need those libraries. Save a map When you save a map, all code modules are saved with that map. Your class can be used by anyone opening a map with class modules. The same goes for saving modules to template files. Anyone using a template has access to that template’s code modules. Introduction to Programming ArcObjects with VBA

80 演示: Creating a simple class
Create a class module to define a Dog Define some simple properties (public variables) Define a Bark method (function) Define a RespondToCall method (sub) Use the class in a form’s code Instructor demonstration Your instructor will now demonstrate how to create your own class using Visual Basic for Applications. Introduction to Programming ArcObjects with VBA

81 Exercise 5 overview Create a class that defines a Country object
Use objects of your class in a client form Set properties and call methods Modify your class to define additional properties and methods Exercise 5: Create your own class In this exercise, you will: Create a new class module. Write code to represent a country object. Use a country object in some client code. Introduction to Programming ArcObjects with VBA

82 VBA客户化练习例子

83 1、创建一个宏实现地图的放大 显示“Customize”对话框。 选择“Command”页面。 选择“Macros”条目。
在“Tools”菜单中,选择“Macros”菜单中的“Macros”子菜单。 在“Marcros”对话框中,输入“MyZoomIn”作为名称,点击“Create”创建一个宏。 在弹出的代码窗口输入以下代码: Sub 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 切换回到ArcMap程序。 选择“MyZoomIn”宏,单击“Run”,观测显示效果。 显示“Customize”对话框。 选择“Command”页面。 选择“Macros”条目。 选择“MyZoomIn”条目,拖放到目标工具条上。

84 2、调用内建命令 创建名为“FullExtentlus”的宏。显示代码窗体。输入如下代码: Sub FullExtentPlus()
'macro:FullExtentPlus Dim IntAns As Integer Dim PItem As ICommandItem With ThisDocument.CommandBars Set PItem = .Find(ArcID.PanZoom_FullExtent) IntAns = MsgBox("Zoom to previous extent?", vbYesNo) If IntAns = vbYes Then Set PItem = .Find(ArcID.PanZoom_ZoomToLastExtentBack) PItem.Execute Else End If End With End Sub 运行该宏,观察运行结果。

85 3、添加一个“Button”风格的工具 在“Tools”菜单中,选择“Customize”菜单。
选择“Command”页面的“UIControls”条目。 单击“New UIControl”按钮,选择“UIButtonControl”。 单击“New”按钮创建一个“Normal.UIButtonControl1”条目。 双击该条目进入代码窗体。 在代码窗体中输入如下代码: Private Sub UIButtonControl1_Click() MsgBox "TestUIButtonControl", vbOKCancel, "Test" End Sub 把该条目添加到工具条,点击运行,观察运行结果。

86 4、添加一个“Tool”风格的工具 Private Function UIToolControl1_Enabled() As Boolean
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 End Function Private Function UIToolControl1_CursorID() As Variant UIToolControl1_CursorID = 3 'crosshair Private Function UIToolControl1_ToolTip() As String UIToolControl1_ToolTip = "Zoom to rectangle" Private Function UIToolControl1_Message() As String UIToolControl1_Message = "Zooms to a designated rectangle" 把该条目添加到工具条,点击运行,观察运行结果。 Private Sub UIToolControl1_MouseDown(ByVal button As Long, ByVal shift As Long, ByVal x As Long, ByVal y As Long) 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 End Sub

87 5、使用VB创建一个COM组件 1、创建一个ActiveX DLL 工程 启动VB,在创建新工程的时候选择“ActiveX DLL”类型。
修改Class1类模块名称为“AdjacentTool”。 修改“Project1”工程名称为“Tutorial”。 导入“ArcID”模块。 保存类“AdjacentTool”为“Tutorial_ AdjacentTool.cls”文件。保存工程为“Tutorial.vbp”文件。 2、引用对象库 在VB的“Project”菜单,选择“References”菜单条。 在“References”对话框,选择ArcMap Object Library 和 ESRI Object Library。 (如果在条目中没有该两项,则查找引用EsriMx.olb和EsriCore.olb)单击 “OK”按钮。 3、实现所需的接口 在“AdjacentTool”类模块代码窗体顶部添加如下代码: Option Explicit Implements ICommand Implements ITool Dim pApp As esriMx.Application 'ArcMap app Dim pDoc As ImxDocument 在代码窗口的左边组合框中选择“Icommand”条目。在代码窗口的右边组合框中选择每一个方法或属性去创建空的过程。对“Itool”条目重复以上两项,创建每一个方法或属性的空过程。

88 5、使用VB创建一个COM组件 4、增加工具的区别代码
Private Property Get ICommand_Category() As String 'Category属性表现为在“Customize”对话框的“Commands”页面的左边列表中。 ICommand_Category = "Tutorial" End Property Private Property Get ICommand_Caption() As String 'Category属性表现为在“Customize”对话框的“Commands”页面的右边列表中。 ICommand_Caption = "AdjacentTool" Private Property Get ICommand_Name() As String ICommand_Name = "Tutorial_AdjacentTool" 5、增加工具的描述代码 Private Property Get ICommand_Message() As String '鼠标移动经过时在状态条上显示的信息。 ICommand_Message = "Selects features " & "Adjacent to the feature you click on" End Property Private Property Get ICommand_Tooltip() As String '鼠标移动经过时显示的信息。 ICommand_Tooltip = "Select adjacent features"

89 5、使用VB创建一个COM组件 6、增加工具的可用性代码
Private Sub ICommand_OnCreate(ByVal hook As Object) Set pApp = hook Set pDoc = pApp.Document End Sub Private Property Get ICommand_Enabled() As Boolean With pDoc.FocusMap If .LayerCount > 0 Then ICommand_Enabled = True ElseIf .LayerCount = 0 Then ICommand_Enabled = False End If End With End Property Private Function ITool_Deactivate() As Boolean ’其他按钮按下是是否失效,缺省为False ITool_Deactivate = True End Function

90 5、使用VB创建一个COM组件 7、增加工具的功能实现代码 '定义空间过滤条件
'create a SpatialFilter to be used in 'a point in polygon selection Set pSpatialFilter = New SpatialFilter With pSpatialFilter Set .Geometry = pPt .GeometryField = _ pLayer.FeatureClass.ShapeFieldName .SpatialRel = esriSpatialRelWithin End With '空间查询 Set pFeatureCursor = _ pLayer.Search(pSpatialFilter, False) 'pFeature is a polygon feature Set pFeature = pFeatureCursor.NextFeature 'create a SpatialFilter to be used in the 'search for polygons adjacent to pFeature Set .Geometry = pFeature.Shape .SpatialRel = esriSpatialRelTouches Set pFeatureSelection = pLayer 'QI '空间选择 pFeatureSelection.SelectFeatures _ pSpatialFilter, esriSelectionResultNew, False pFeatureSelection.SetSelectionSymbol = True Private Sub ITool_OnMouseDown(ByVal Button As Long, ByVal Shift As Long, ByVal X As Long, ByVal Y As Long) Dim pScreenDisp As IScreenDisplay Dim pDt As IDisplayTransformation Dim pPt As IPoint Dim pMap As IMap Dim pLayer As IFeatureLayer Dim pSelEnv As ISelectionEnvironment Dim pSelection As ISelection Dim pEnumFeat As IEnumFeature Dim pFeature As IFeature Dim pFeatureCursor As IFeatureCursor Dim pSpatialFilter As ISpatialFilter Dim pFeatureSelection As IFeatureSelection Dim pFillSymbol As ISimpleFillSymbol Dim pColor As IRgbColor Dim psym As ISymbol '把屏幕坐标点转换成地图坐标点 Set pScreenDisp = pDoc.ActiveView.ScreenDisplay Set pDt = pScreenDisp.DisplayTransformation 'get the MouseDown location in map units Set pPt = pDt.ToMapPoint(X, Y) '引用一个图层 'the tutorial expects the first layer to 'serve as the target Set pMap = pDoc.ActiveView.FocusMap Set pLayer = pMap.Layer(0) pLayer.Selectable = True

91 5、使用VB创建一个COM组件 8、编译成DLL库
'定义颜色及符号 Set pColor = New RgbColor pColor.RGB = vbRed Set pFillSymbol = New SimpleFillSymbol pFillSymbol.Color = pColor pFillSymbol.Style = esriSFSSolid '显示选择结果 Set psym = pFillSymbol 'QI Set pFeatureSelection.SelectionSymbol = psym Dim pitem As ICommandItem pDoc.ActiveView.Refresh '使用内建命令统计选择集合 'finish by displaying 'statistics for the adjacent features 'ArcID is a VB module that was exported from 'ArcMap Set pitem = pApp.Document.CommandBars _ .Find(ArcID.Query_SelectionStatistics) pitem.Execute End Sub 在VB的“Project”菜单中,选择“Tutorial Properties”,然后选择“Component”页面。选择“Binary Compatibility”选项。单击“OK”。保存工程。在“File”菜单中,选择“Make Tutorial.dll”。 9、使用ArcMap注册该组件库 启动ArcMap在“Tools”菜单中选择“Customize”。点击“Customize”对话框中的“Add from file”按钮。双击“Tutorial.dll”。单击“OK”按钮。可以看出在“Customize”对话框的“Commands”页面的左边增加了一个名为“Tutorial”的条目。在该条目中有一个“AadjacentTool”的命令。 10、把组件添加到文档并使用。 把上面注册的“AdjacentTool”命令拖放到一个工具条上。使用该工具条,观察工具效果。(使用USA的STATES数据作为例子数据。)

92 6、框架对话框对象调用 ProgreseDialog 进程条对话框:动态显示进程
CoordinateDialog 坐标对话框 :输入X、Y坐标。 GetStringDialog 字符串对话框:取得字符串 NumberDialog 数字对话框 :输入一个数值 ListDialog 列表对话框:列表显示数值或字符值 MessageDialog 消息对话框 :显示消息。 GetUserAndPassWordDialog 用户密码对话框:取得用户和密码。 以CoordinateDialog 坐标对话框为例的VBA宏例子: Public Sub CoordDlg() '定义一个坐标对话框 Dim pCoordDlg As ICoordinateDialog Dim boolValid As Boolean Set pCoordDlg = New CoordinateDialog '显示该对话框,接受坐标输入 boolValid = pCoordDlg.DoModal("Enter X & Y coordinates", 1, 1, 3, Application.hWnd) If boolValid Then '如果是有效输入 MsgBox "X: " & pCoordDlg.X & vbNewLine & "Y: " & pCoordDlg.Y Else '如果是无效输入 MsgBox "Bad entries." End If End Sub

93 第二天

94 7、空间书签管理(添加空间书签) Private Sub AddSpatialBookMark_Click() '定义文档对象 Dim pMxDoc As IMxDocument '定义地图对象 Dim pMap As IMap '定义活动视图对象 Dim pActiveView As IActiveView '定义空间书签对象 Dim pAreaOfInterest As IAOIBookmark '定义地图书签集合对象。因为所有的空间书签都是由Map对象来管理的。 Dim pMapBookmarks As IMapBookmarks '取得文档对象 Set pMxDoc = Application.Document '取得焦点Map对象 Set pMap = pMxDoc.FocusMap '设置当前活动视图 Set pActiveView = pMap '创建一个新的空间书签对象,并设置它定位到焦点地图的当前可视范围 Set pAreaOfInterest = New AOIBookmark Set pAreaOfInterest.Location = pActiveView.Extent '设置空间书签的名称属性 pAreaOfInterest.Name = "My bookmark" '取得当前地图书签集合对象 Set pMapBookmarks = pMap '把空间书签加入到集合中 pMapBookmarks.AddBookmark pAreaOfInterest End Sub Spatial Bookmark保存的是地图的范围。就像书签一样可以快速地定位到一个预先定义好的相关主题区域去。空间书签的管理主要是增加、调用、删除空间书签。以下代码实现了空间书签的增加功能和空间书签的调用功能。

95 7、空间书签管理(调用空间书签) Do While Not pBookmark Is Nothing '判断是否是目标书签
If pBookmark.Name = "My bookmark" Then '如果是目标书签则调用目标书签的ZoomTo方法,把当前地图可视范围设置成书签范围. pBookmark.ZoomTo pMxDoc.FocusMap '刷新文档的活动视图 pMxDoc.ActiveView.Refresh '退出过程 Exit Sub End If '取得下一条空间书签 Set pBookmark = pEnumBookmarks.Next Loop End Sub Private Sub ZoomToBookmark_Click() '定义文档对象 Dim pMxDoc As IMxDocument '定义地图书签集合对象 Dim pMapBookmarks As IMapBookmarks '定义空间书签集合 Dim pEnumBookmarks As IEnumSpatialBookmark '定义空间书签 Dim pBookmark As ISpatialBookmark '取得文档对象 Set pMxDoc = Application.Document '取得地图书签集合 Set pMapBookmarks = pMxDoc.FocusMap '取得空间书签集合 Set pEnumBookmarks = pMapBookmarks.Bookmarks '重置空间书签集合,把索引指针归到最开始 pEnumBookmarks.Reset '取得第一个空间书签 Set pBookmark = pEnumBookmarks.Next '一直执行直到遍历了所有空间书签

96 8、调用放大镜窗口 在ArcMap的框架中我们可以通过菜单的“Windows”菜单来打开放大镜窗口。我们也可以在代码中实现这功能。以下代码显示怎么在程序中调用这个窗口。 Private Sub CreateMagnifierWindow_Click() '定义一个MapInset对象.在这里用来控制放大的比例. Dim pMapInset As IMapInset '定义一个MapInsetWindow对象.该对象从ArcMap的Magnifier窗口对象继承而来.用来在焦点视图上显示一个放大镜视图窗体。 Dim pMapInsetWindow As IMapInsetWindow '定义一个DataWindowFactory对象,用来根据应用程序对象生成一个数据窗体对象. Dim pDataWindowFactory As IDataWindowFactory '生成一个新的MapInsetWindowFactory对象. Set pDataWindowFactory = New MapInsetWindowFactory '判断是否可以根据当前应用程序生成MapInsetWindow对象. If pDataWindowFactory.CanCreate(Application) Then '如果可以,则根据当前应用程序生成MapInsetWindow对象. Set pMapInsetWindow = pDataWindowFactory.Create(Application) '取得MapInsetWindow对象的MapInset对象的引用. Set pMapInset = pMapInsetWindow.MapInset '设置当前放大比例为当前比例的200% pMapInset.ZoomPercent = 200 '显示放大镜窗体 pMapInsetWindow.Show True End If End Sub

97 讨论和操作实践


Download ppt "ArcObjects的开发."

Similar presentations


Ads by Google