240 likes | 396 Views
Events, Methods, Functions, and More. Advanced GIS 10-23-03. Objects/Methods/Events.
E N D
Events, Methods, Functions, and More Advanced GIS 10-23-03
Objects/Methods/Events • Visual Basic objects have properties, methods, and events. Properties can be thought of as an object's attributes, methods as its actions, and events as things that happen to the object. You write code to execute when events occur. • An event is always associated with an object. You make an application work by setting object properties, and perform actions using object methods. • In Visual Basic, the easiest type of object to conceptualize is a control with which users interact. In the graphic below, command buttons, labels, and text boxes are all examples of control objects. The form itself is also an object. • Other less tangible Visual Basic constructs, like collections, are also objects. An object is an object if it can be controlled or manipulated with code by setting properties, invoking methods, or responding to events. In ArcInfo 8, you will find objects like Maps, PageLayout, and Layers. In MapObjects, objects include Map controls, MapLayer, and symbols. Not all objects have events; for example, in MapObjects, only the Map control has events
Properties • Properties describe an object's characteristics. In Visual Basic, examples of an object's properties include Name, Appearance, and BorderStyle. The Map object in ArcInfo 8 has properties of Scale and MapUnits. A MapLayer object in MapObjects has properties including Extent and Visible. • You can set many object properties at design time in the Properties window. Below, Form1's BackColor and Caption properties are set in the Properties window. The BackColor has been set to a red color, and the Caption, which appears in the form's title bar, has been set to "My Form." • The Properties window is used here to set two properties of the form object, Caption and BackColor.
Properties -2 • Some properties, such as Left, Top, Width and Height, change automatically when you move or resize controls. During run time, you cannot change object properties in the Properties window. Rather, you must change them using Visual Basic code. The syntax for setting a property is: • Object.Property = Value • Not all properties can be set (written) at run time; however, almost all properties can be evaluated (read). The Name property for any object, for example, can be set only at design time. It is said to be read-only at run time. • The following example shows how to set and read Label1's Caption property and assign the result to Text1's Text property. The Text property of a text box object is the text displayed in the text box. • Label1.Caption = "Welcome to VB"Text1.Text = Label1.Caption
Methods • Methods are actions which objects know how to do. In Visual Basic, objects come equipped with the code to perform predefined methods. The syntax for using methods is: • Object.Method (Arguments) • The example below shows a list box using an AddItem method to add items to itself. "Hello" is the argument for the AddItem method. • Some methods, like AddItem, have arguments, while others do not. Not all methods need arguments. For example, a list box's Clear method does not need an argument to remove all the contents from the list box. • List1.Clear • When a method returns a value that you accept (i.e., assign to a variable and use in the code), you must surround its arguments with parentheses, as in the MapObjects example below. There, the AddRelate method requires three arguments. It also returns a True or False value, indicating if the AddRelate action was successfully performed. If you assign the returned value (either True or False) to the bItWorked variable, you need to surround its arguments with parentheses. If you don't want to assign the returned value to a variable, you don't need to include the parentheses.
Is Like Object.Request in Avenue • 'MapObjects example--parentheses required bItWorked = myLayer.AddRelate("APN", parcelTbl, "APN")'MapObjects example--no parentheses requiredmyLayer.AddRelate "APN", parcelTbl, "APN" • Some methods don't return a value by default, like the AddItem method of the list box control. When a method does not return a value, you must not surround its arguments with parentheses: • List1.AddItem "Welcome to VB"
Events • Events are actions that an object can recognize. When a command button object is clicked, the command button reacts according to the code supplied by the programmer. • In Visual Basic, forms and controls have their own associated events. The possible events for forms and controls are listed in the Procedure list box in Code Editor window. For example, a command button can have events such as Click, DragDrop, and DropOver.
Events 2 • The Visual Basic syntax for an event procedure is shown below: • Object_event(arguments) • Some events, such as the Click event, have no arguments: • Command1_Click() • Others, such as the MouseDown event, have several arguments: • Command1_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) • Any argument of an event can be used programmatically within the event procedure. • Although many events happen as a direct result of user interaction, other events happen indirectly or may be completely removed from any user interaction whatsoever. The Timer control, for instance, has a Timer event that is triggered at regular intervals (e.g., every second), while the Form object has a Load event that occurs when the Form is first initiated.
Procedure • Procedures are the building blocks of a Visual Basic application. Procedures allow you to break the program into smaller logical units and to debug (find errors) easily. Procedures are also useful for repeated or shared tasks. • A simple event procedure is shown below: Private Sub cmdApply_Click() MsgBox "Hello" End Sub • Each procedure has template code as the first and last lines of a procedure. Within the template code (sometime called wrapper code) is the actual executable code. In the above example, a message box displays "Hello" when the command button cmdApply is clicked
Statements • Statements are Visual Basic commands which provide much of the syntax and structure for the Visual Basic language. Statements are the building blocks of a procedure. • Statements initiate an action. Some statements take one or more arguments (sometimes referred to as parameters) that specify how the action is to be performed. • In the example below, the Unload statement needs an argument so it knows which form to unload, while the Beep statement does not need any argument. • 'Statement with argumentUnload Form1'Statement without argumentBeep
Functions • Functions are statements which return a result, or value. There are two types of functions: Visual Basic intrinsic functions and functions created using a function procedure. • Intrinsic functions are provided by the language itself. Examples of intrinsic functions are: • Mathematic function: Sqr, Sin • InputBox function • Time/Date function: Now • The syntax for a function is: • ReturnedValue = Function() • The example below uses the intrinsic function Sin(): • theAngle = Sin(txtAngle.Text) • Functions can be nested. • theAngle = Sin(InputBox("Enter an Angle"))
Functions - 2 • All functions return a value; however, you don't always need to retain the value. If the returned value needs to be saved, parentheses must be used. • In the following example, the MsgBox function returns which button (Yes or No) is clicked by the user. If the value is not saved, you do not have to use parentheses. If you need to track which button is clicked, however, use parentheses. • 'Value not retainedMsgBox "Save changes to the file?", vbYesNo 'Value retainedtheButton = MsgBox("Save changes to the file?", vbYesNo)
Variables • Variables are used to temporarily store values during the execution of a program. In Visual Basic, a variable has a name and a data type. • You declare a variable with the Dim statement. "Dim" is short for Dimension--Dimension means size. In Visual Basic, the equal sign "=" is often used as the symbol of assignment. The statement X = Y means to take value of variable Y and assign it to variable X. Variable X now stores the value of variable Y. • In the following example, an integer variable is used to store the user input information. The information is incremented and reported back to the user. • 'Declare the variableDim intAge As Integer 'Assign the variableintAge=InputBox("Enter your age:")'Increment the variableintAge = intAge +1 'Retrieve the variableMsgbox "Next year you are " & intAge
Constant • A constant is a meaningful name used to replace a fixed number or string that is difficult to understand and remember. For example, colors are stored in Visual Basic using integer numbers. The color red in Visual Basic is 65280, to which a constant vbRed is assigned. To change the background color of a form to red, you can write either of the following two lines of code. • frmColor.BackColor = 65280'orfrmColor.BackColor = vbRed • Obviously, the second example is easier to write and understand. • Hundreds of constants come with Visual Basic, and you can also create your own. • Const conPi = 3.14159265358979Const conVersion = "8.1" • Code created with Visual Basic constants is forward-compatible. According to Microsoft, while the numeric codes might change, the constants will be updated with each new release to point at the correct new number.
Naming convention • Understanding and practicing Visual Basic programming conventions will help you write well-structured and documented code. Following defined conventions makes code easier to understand and maintain.
Controls The following table shows common prefixes and name examples for some common controls. ObjectPrefixExample Form frm frmSelect Label lbl lblSearchString Combo boxcbo cboEditFeature Command button cmd cmdCancel Directory listbox dir dirPath Drive listbox drv drvDrive Image img imgBitmap Listbox lst lstSelectedFile Menu mnu mnuFileSaveAs Option button opt optTopology Timer tmr tmrAlarm Common dialog dlg dlgSaveAs
Comments • Comments are not just for your coworkers and your employer, they can be invaluable to you. If you don't include comments in your code, you might find yourself completely lost, trying to figure out a program that seemed perfectly logical and understandable when you created it a few months ago. Comments are especially important in Visual Basic, because code does not usually flow from top to bottom, which can make it difficult to track. • The single quote is the character that denotes a comment in Visual Basic. By default, commented lines turn green. Comments can follow a statement on the same line or they can occupy an entire line, as shown in the example below: • Name = InputBox("Enter your name") 'Get the name'Get the number of characters in nameGetNameLength = Len(Name)
Comments - 2 • You can use the Edit toolbar to quickly comment and uncomment highlighted blocks of code. The Edit toolbar provides two tools you can use to comment or uncomment highlighted blocks of code at once.
Indenting • You can press Tab and Shift+Tab to indent and outdent code, respectively. The number of spaces to indent is your choice, but a minimum of two spaces is recommended for clarity. To set the Code Editor tab width, choose Options from the Tools menu
Line continuation in code • Often, an individual line of code can become quite long. Some developers feel that code is more readable if long lines are split into several shorter lines. If you split a line of code, you must place an underscore character (_) at the end of the line and after a space, to indicate that the line continues on the next line below. • 'Get the number of characters in user's nameGetNameLength = Len(InputBox _("Please enter your full name.")) • The continuation character cannot be placed inside quotes or be followed by a comment on the same line. • Other developers feel that line continuation can lead to confusion--what is really one line of code appears as several. Whether you use line continuation or not, just remember that readable code is the goal.
Homework 7, 30 points, due on 10/30/03 midnight • You are asked to create a VB form that converts geographic degrees in (degree,minutes,seconds) to decimal degrees. Add label,commands and text box to this form and add code to calculate the conversion. (DD = degrees + minutes/60 + seconds/3600) • Write code in cmdConvert_Click() event • :txtDD = txtDegrees + txtMinutes/60 + txtSeconds/3600 • Remember to have two parts of the code for differentiate into positive and negative degrees. • Add “Clear” and “Exit” commands to the form • Save your project and forms as “DMSConvert” • Use comments to describe each step
Homework 7: continued Control Name Caption Form frmDD Homework 7: DMS to DD Command1 cmdConvert Convert Command2 cmdClear Clear Command3 cmdExit Exit (you need “End”) Label1 lblDegrees Degrees Label2 lblMinutes Minutes Label3 lblSeconds Seconds Label4 lblDecimalDegrees Decimal Degrees Text1 txtDegrees Text2 txtMinutes Text3 txtSeconds Text4 txtDD Notes: Be careful with the negative degrees (such as in western hemisphere). Use Format$(variable, “00,000000”) to set the dd format.
Homework 8Browse files, 20 points, due on 11/1/03, midnight Name Caption Form frmMain Slide Show DriveListBox drvFile DirListBox dirFile FileListBox filFile Label1 lblSlideInShow Slides in show List1 lstSlides Command1 cmdAdd (font)&Add 10 pt Bold Command2 cmdClear (font)&Clear 10 pt Bold • Once user click on the drvFile, the dirFile will refresh the change and then the filFile will refresh its contents accordingly. • The highlighted file in the filFile will be added to the lstSlides if users click on cmdAdd. If cmdClear is clicked, the contents of the lstSlides will be cleared.
Hints • Once user click drvFile, dirFile should have an updated list (use dirFile = drvFile.Drive in the event drvFile_Change()) • Once user click dirFile, filFile should have an updated list (use filFile = dirFile.Path in the event dirFile_Change()). • Once user double-click on the file list, the file will be added to the List (in the event of filFile_DblClick() add the following code- lstSlides.AddItem (filFile.FileName)), or use cmdAdd to add the highlighted file to the list (in the event of cmdAdd_Click()) • In the event of cmdClear_Click() add following tasks: If List1.ListCount = 0 Then MsgBox "No file listed here" ElseIf List1.SelCount = 0 Then MsgBox "Please select file from the list" Else List1.RemoveItem (List1.ListIndex) End If