Visual basic

73
Visual Basic From Wikipedia, the free encyclopedia Jump to: navigation , search This article is about the Visual Basic language shipping with Microsoft Visual Studio 6.0 or earlier. For the Visual Basic language shipping with Microsoft Visual Studio .NET or later, see Visual Basic .NET . Visual Basic Paradigm Object-based and Event-driven Appeared in 1991 Developer Microsoft Stable release VB6 (1998) Typing discipline Static , strong Influenced QuickBASIC

Transcript of Visual basic

Page 1: Visual basic

Visual BasicFrom Wikipedia, the free encyclopediaJump to: navigation, search This article is about the Visual Basic language shipping with Microsoft Visual Studio 6.0 or earlier. For the Visual Basic language shipping with Microsoft Visual Studio .NET or later, see Visual Basic .NET.

Visual Basic

Paradigm Object-based and Event-driven

Appeared in 1991

Developer Microsoft

Stable release VB6 (1998)

Typing

disciplineStatic, strong

Influenced by QuickBASIC

InfluencedVisual Basic .NET, Gambas, REALbasic,

Basic4ppc

OS Microsoft Windows, MS-DOS

Page 2: Visual basic

Website msdn.microsoft.com

Visual Basic (VB) is the third-generation event-driven programming language and integrated development environment (IDE) from Microsoft for its COM programming model. Visual Basic is relatively easy to learn and use.[1][2]

Visual Basic was derived from BASIC and enables the rapid application development (RAD) of graphical user interface (GUI) applications, access to databases using Data Access Objects, Remote Data Objects, or ActiveX Data Objects, and creation of ActiveX controls and objects. Scripting languages such as VBA and VBScript are syntactically similar to Visual Basic, but perform differently.[3]

A programmer can put together an application using the components provided with Visual Basic itself. Programs written in Visual Basic can also use the Windows API, but doing so requires external function declarations.

The final release was version 6 in 1998. Microsoft's extended support ended in March 2008 and the designated successor was Visual Basic .NET (now known simply as Visual Basic).

Contents

[hide]

1 Language features 2 Characteristics 3 History

o 3.1 Timeline 4 Derivative languages 5 Performance and other issues 6 Legacy development and support 7 Example code 8 See also 9 References 10 External links

[edit] Language features

Like the BASIC programming language, Visual Basic was designed to be easily learned and used by beginner programmers. The language not only allows programmers to create simple GUI applications, but can also develop complex applications. Programming in VB is a combination of visually arranging components or controls on a form, specifying attributes and actions of those components, and writing additional lines of code for more functionality. Since default attributes and actions are defined for the components, a simple program can be created without the programmer having to write many lines of code. Performance problems were experienced by

Page 3: Visual basic

earlier versions, but with faster computers and native code compilation this has become less of an issue.

Although programs can be compiled into native code executables from version 5 onwards, they still require the presence of runtime libraries of approximately 1 MB in size. This runtime is included by default in Windows 2000 and later, but for earlier versions of Windows like 95/98/NT it must be distributed together with the executable.

Forms are created using drag-and-drop techniques. A tool is used to place controls (e.g., text boxes, buttons, etc.) on the form (window). Controls have attributes and event handlers associated with them. Default values are provided when the control is created, but may be changed by the programmer. Many attribute values can be modified during run time based on user actions or changes in the environment, providing a dynamic application. For example, code can be inserted into the form resize event handler to reposition a control so that it remains centered on the form, expands to fill up the form, etc. By inserting code into the event handler for a keypress in a text box, the program can automatically translate the case of the text being entered, or even prevent certain characters from being inserted.

Visual Basic can create executables (EXE files), ActiveX controls, or DLL files, but is primarily used to develop Windows applications and to interface database systems. Dialog boxes with less functionality can be used to provide pop-up capabilities. Controls provide the basic functionality of the application, while programmers can insert additional logic within the appropriate event handlers. For example, a drop-down combination box will automatically display its list and allow the user to select any element. An event handler is called when an item is selected, which can then execute additional code created by the programmer to perform some action based on which element was selected, such as populating a related list.

Alternatively, a Visual Basic component can have no user interface, and instead provide ActiveX objects to other programs via Component Object Model (COM). This allows for server-side processing or an add-in module.

The language is garbage collected using reference counting, has a large library of utility objects, and has basic object oriented support. Since the more common components are included in the default project template, the programmer seldom needs to specify additional libraries. Unlike many other programming languages, Visual Basic is generally not case sensitive, although it will transform keywords into a standard case configuration and force the case of variable names to conform to the case of the entry within the symbol table. String comparisons are case sensitive by default, but can be made case insensitive if so desired.

The Visual Basic compiler is shared with other Visual Studio languages (C, C++), but restrictions in the IDE do not allow the creation of some targets (Windows model DLLs) and threading models.

[edit] Characteristics

Visual Basic has the following traits which differ from C-derived languages:

Page 4: Visual basic

Multiple assignment available in C language is not possible. A = B = C does not imply that the values of A, B and C are equal. The boolean result of "Is B = C?" is stored in A. The result stored in A would therefore be either false or true.

Boolean constant True has numeric value −1.[4] This is because the Boolean data type is stored as a 16-bit signed integer. In this construct −1 evaluates to 16 binary 1s (the Boolean value True), and 0 as 16 0s (the Boolean value False). This is apparent when performing a Not operation on a 16 bit signed integer value 0 which will return the integer value −1, in other words True = Not False. This inherent functionality becomes especially useful when performing logical operations on the individual bits of an integer such as And, Or, Xor and Not.[5] This definition of True is also consistent with BASIC since the early 1970s Microsoft BASIC implementation and is also related to the characteristics of CPU instructions at the time.

Logical and bitwise operators are unified. This is unlike some C-derived languages (such as Perl), which have separate logical and bitwise operators. This again is a traditional feature of BASIC.

Variable array base. Arrays are declared by specifying the upper and lower bounds in a way similar to Pascal and Fortran. It is also possible to use the Option Base statement to set the default lower bound. Use of the Option Base statement can lead to confusion when reading Visual Basic code and is best avoided by always explicitly specifying the lower bound of the array. This lower bound is not limited to 0 or 1, because it can also be set by declaration. In this way, both the lower and upper bounds are programmable. In more subscript-limited languages, the lower bound of the array is not variable. This uncommon trait does exist in Visual Basic .NET but not in VBScript.

OPTION BASE was introduced by ANSI, with the standard for ANSI Minimal BASIC in the late 1970s.

Relatively strong integration with the Windows operating system and the Component Object Model. The native types for strings and arrays are the dedicated COM types, BSTR and SAFEARRAY.

Banker's rounding as the default behavior when converting real numbers to integers with the Round function.[6] ? Round(2.5, 0) gives 2, ? Round(3.5, 0) gives 4.

Integers are automatically promoted to reals in expressions involving the normal division operator (/) so that division of one integer by another produces the intuitively correct result. There is a specific integer divide operator (\) which does truncate.

By default, if a variable has not been declared or if no type declaration character is specified, the variable is of type Variant. However this can be changed with Deftype statements such as DefInt, DefBool, DefVar, DefObj, DefStr. There are 12 Deftype statements in total offered by Visual Basic 6.0. The default type may be overridden for a specific declaration by using a special suffix character on the variable name (# for Double, ! for Single, & for Long, % for Integer, $ for String, and @ for Currency) or using the key phrase As (type). VB can also be set in a mode that only explicitly declared variables can be used with the command Option Explicit.

[edit] History

Page 5: Visual basic

VB 1.0 was introduced in 1991. The drag and drop design for creating the user interface is derived from a prototype form generator developed by Alan Cooper and his company called Tripod. Microsoft contracted with Cooper and his associates to develop Tripod into a programmable form system for Windows 3.0, under the code name Ruby (no relation to the Ruby programming language).

Tripod did not include a programming language at all. Microsoft decided to combine Ruby with the Basic language to create Visual Basic.

The Ruby interface generator provided the "visual" part of Visual Basic and this was combined with the "EB" Embedded BASIC engine designed for Microsoft's abandoned "Omega" database system. Ruby also provided the ability to load dynamic link libraries containing additional controls (then called "gizmos"), which later became the VBX interface.[7]

[edit] Timeline

Project 'Thunder' was initiated Visual Basic 1.0 (May 1991) was released for Windows at the Comdex/Windows World

trade show in Atlanta, Georgia.

Visual Basic 1.0 for DOS was released in September 1992. The language itself was not quite compatible with Visual Basic for Windows, as it was actually the next version of Microsoft's DOS-based BASIC compilers, QuickBASIC and BASIC Professional Development System. The interface used a Text user interface, using extended ASCII characters to simulate the appearance of a GUI.

Visual Basic for MS-DOS

Visual Basic 2.0 was released in November 1992. The programming environment was easier to use, and its speed was improved. Notably, forms became instantiable objects, thus laying the foundational concepts of class modules as were later offered in VB4.

Visual Basic 3.0 was released in the summer of 1993 and came in Standard and Professional versions. VB3 included version 1.1 of the Microsoft Jet Database Engine that could read and write Jet (or Access) 1.x databases.

Visual Basic 4.0 (August 1995) was the first version that could create 32-bit as well as 16-bit Windows programs. It also introduced the ability to write non-GUI classes in

Page 6: Visual basic

Visual Basic. Incompatibilities between different releases of VB4 caused installation and operation problems. While previous versions of Visual Basic had used VBX controls, Visual Basic now used OLE controls (with files names ending in .OCX) instead. These were later to be named ActiveX controls.

With version 5.0 (February 1997), Microsoft released Visual Basic exclusively for 32-bit versions of Windows. Programmers who preferred to write 16-bit programs were able to import programs written in Visual Basic 4.0 to Visual Basic 5.0, and Visual Basic 5.0 programs can easily be converted with Visual Basic 4.0. Visual Basic 5.0 also introduced the ability to create custom user controls, as well as the ability to compile to native Windows executable code, speeding up calculation-intensive code execution. A free, downloadable Control Creation Edition was also released for creation of ActiveX controls. It was also used as an introductory form of Visual Basic: a regular .exe project could be created and run in the IDE, but not compiled.

Visual Basic 6.0 (Mid 1998) improved in a number of areas [8] including the ability to create web-based applications. VB6 has entered Microsoft's "non-supported phase" as of March 2008. Although the Visual Basic 6.0 development environment is no longer supported, the runtime is supported on Windows Vista, Windows Server 2008 and Windows 7.[9]

Mainstream Support for Microsoft Visual Basic 6.0 ended on March 31, 2005. Extended support ended in March 2008.[10] In response, the Visual Basic user community expressed its grave concern and lobbied users to sign a petition to keep the product alive.[11] Microsoft has so far refused to change their position on the matter. (but see [12]) Ironically, around this time (2005), it was exposed that Microsoft's new anti-spyware offering, Microsoft AntiSpyware (part of the GIANT Company Software purchase), was coded in Visual Basic 6.0.[13] Its replacement, Windows Defender, was rewritten as C++ code.

VB DOS Logo

[14]

[edit] Derivative languages

Microsoft has developed derivatives of Visual Basic for use in scripting. Visual Basic itself is derived heavily from BASIC, and subsequently has been replaced with a .NET platform version.

Some of the derived languages are:

Visual Basic for Applications (VBA) is included in many Microsoft applications (Microsoft Office), and also in many third-party products like SolidWorks, AutoCAD, WordPerfect Office 2002, ArcGIS, Sage Accpac ERP, and Business Objects Desktop Intelligence. There are small inconsistencies in the way VBA is implemented in different

Page 7: Visual basic

applications, but it is largely the same language as VB6 and uses the same runtime library.

VBScript is the default language for Active Server Pages. It can be used in Windows scripting and client-side web page scripting. Although it resembles VB in syntax, it is a separate language and it is executed by vbscript.dll as opposed to the VB runtime. ASP and VBScript should not be confused with ASP.NET which uses the .NET Framework for compiled web pages.

Visual Basic .NET is Microsoft's designated successor to Visual Basic 6.0, and is part of Microsoft's .NET platform. Visual Basic.Net compiles and runs using the .NET Framework. It is not backwards compatible with VB6. An automated conversion tool exists, but fully automated conversion for most projects is impossible.[15]

StarOffice Basic is a Visual Basic compatible interpreter included in StarOffice suite, developed by Sun Microsystems.

Gambas is a Visual Basic inspired free software programming language. It is not a clone of Visual Basic, but it does have the ability to convert Visual Basic programs to Gambas.

[edit] Performance and other issues

Earlier counterparts of Visual Basic (prior to version 5) compiled the code to P-Code only. The P-Code is interpreted by the language runtime, also known as a virtual machine. The benefits of P-Code include portability and smaller binary file sizes, but it usually slows down the execution, since having a runtime adds an additional layer of interpretation. However, small amounts of code and algorithms can be constructed to run faster than compiled native code.

Visual Basic applications require Microsoft Visual Basic runtime MSVBVMxx.DLL, where xx is the relevant version number, either 50 or 60. MSVBVM60.dll comes as standard with Windows in all editions after Windows 98 while MSVBVM50.dll comes with all editions after Windows 95. A Windows 95 machine would however require inclusion with the installer of whichever dll was needed by the program.

Visual Basic 5 and 6 can compile code to either native or P-Code.

Criticisms levelled at Visual Basic editions prior to VB.NET include:[16]

Versioning problems associated with various runtime DLLs, known as DLL hell Poor support for object-oriented programming [17] Inability to create multi-threaded applications, without resorting to Windows API calls Inability to create Windows services Variant types have a greater performance and storage overhead than strongly typed

programming languages Dependency on complex and fragile COM Registry entries[18]

The development environment is no longer supported by Microsoft.

[edit] Legacy development and support

Page 8: Visual basic

All versions of the Visual Basic development environment from 1.0 to 6.0 have been retired and are now unsupported by Microsoft. The associated runtime environments are unsupported too, with the exception of the Visual Basic 6 core runtime environment, which will be officially supported by Microsoft for the lifetime of Windows 7.[19] Third party components that shipped with Visual Studio 6.0 are not included in this support statement. Some legacy Visual Basic components may still work on newer platforms, despite being unsupported by Microsoft and other vendors.

Development and maintenance development for Visual Basic 6 is possible on legacy Windows XP, Windows Vista and Windows 2003 using Visual Studio 6.0 platforms, but is unsupported. Documentation for Visual Basic 6.0, its application programming interface and tools is best covered in the last MSDN release before Visual Studio.NET 2002. Later releases of MSDN focused on .NET development and had significant parts of the Visual Basic 6.0 programming documentation removed. The Visual Basic IDE can be installed and used on Windows Vista, where it exhibits some minor incompatibilities which do not hinder normal software development and maintenance. As of August 2008, both Visual Studio 6.0 and the MSDN documentation mentioned above are available for download by MSDN subscribers.

[edit] Example code

Here is an example of the language: Code snippet that displays a message box "Hello, World!" as the window Form loads:

Private Sub Form_Load() ' Execute a simple message box that will say "Hello, World!" MsgBox "Hello, World!"End Sub

Event-driven programming

Introduction

Perhaps you're a DOS programmer making the transition to Windows, or a new programmer just getting started with Visual Basic. Regardless of your background, one of the most fundamental concepts you'll need to understand to write programs in Visual Basic is the idea of event driven programming.

Page 9: Visual basic

In traditional procedural programming, the application starts (typically in a procedure named "Main") and from that point onward has complete responsibility for everything that happens. It must handle keyboad input, mouse input, output to the screen, etc. With Visual Basic (and Windows in general), you no longer need to worry about low level input handling. Windows and Visual Basic take care of the details for you, allowing you to concentrate on what the application is supposed to accomplish.

Lets say for example that you want a program to display a message when the user clicks on a button. With a DOS based program, you would need to track the mouse position, display a cursor, detect the mouse click, redraw the button when its clicked, and display the message. Visual Basic and Windows greatly simplify this process. To accomplish the same task, you simply draw a command button on a form, and write a procedure to handle the click event. VB and Windows will take care of the mouse and fire the event when the user clicks on the button. All you need to do is attach the code to the button's click event and write the code that you wish to run when it occurs.

To add an event procedure and attach it a form or control, just pick the form or control from the "Object" combo box in the code window and choose the event from the "Proc" combo box.

VB will create the event procedure for you in the code window. All that's left for you to do is to add the code that you wish to run when the event is fired by VB. Here's the result of our attempt to display a message.

1. Private Sub cmd_Click()2.  3.   MsgBox "Hello World!"4.  5. End Sub

When the user clicks on the button "cmd", the message box will be displayed. That's all there is to it. Once you understand this simple - but not entirely obvious - concept, you're ready to start writing code for your VB applications.

Form Events

Page 10: Visual basic

Visual Basic forms and controls can trigger dozens of events in your applications. Forms, controls, and classes all have events. Let's look at some of the events for forms, and examine how and when they occur.

To demonstrate form events, I created a new form and placed code like this in the event procedure for each of the events:

1. Private Sub Form_Load()2.   Debug.Print "Load"3. End Sub

For each event, the name of the event was sent to the debug window. Here was the output:

1. Initialize2. Load3. Resize4. Activate5. Paint6. ' I closed the form here7. QueryUnload8. Unload9. Terminate

There are other form events also, such as the click event, etc., but those must be triggered by user actions or other code. These are the events that are always triggered for forms and the generic order in which they occur. Let's take a look at each.

InitializeThis event occurs as the form is being loaded, but before the Load event. It gives you the opportunity to initialize data that must be available when the form is loading.

LoadLoad is the event most often used to initialize any dynamic components of the form, such as private data, control arrays, or any other element of the design that needs to be setup at run time rather than in design view.

ResizeThis event occurs whenever the window state (windowed, minimized, or maximized) changes or whenever the form window is resized by the user. Here is where you place code that is dependent on the form size or window state. If, for example, you are building a text editor, you might resize a text box to the internal size of the form in the Resize event.

ActivateThis event occurs whenever the form window gets the input focus. If you have code that tracks the active form in the application, you might use this event for that code.

PaintThis is where VB actually draw the form on the screen. If you are drawing directly on the form with graphics methods, that code might go in this event.

Page 11: Visual basic

QueryUnloadThis event is fired when the form is closed. You can use the event to determine the way the form is being closed (through your own code, by the user, or by Windows) and can also cancel the event and prevent the form from being closed.

UnloadThis event occurs when the form unloads.

TerminateThis event occurs when the form is destroyed.

There is often some confusion over the three events that occur when a form is being destroyed - the QueryUnload, Unload, and Terminate events. Of the three, the QueryUnload event is the only one which can be cancelled. The key to remember is that a form isn't completely removed from memory until after the Terminate event has finished. Compare the following two statements:

1. Unload Form12. Set Form1 = Nothing

The first statement will cause the QueryUnload and the Unload events to fire, but only by using the second statement can you force the Terminate event to fire. If you have form level variables, the values will not be reset after the Unload event has fired. They are only reset after the Terminate event fires and the form is completely removed from memory.

Control Events

Controls also have events, but the events which occur vary by the type of control. Most controls will have a full set of keyboard and mouse events, including KeyUp, KeyDown, KeyPress, MouseUp, MouseDown, MouseMove, Click, and DblClick. The nature of the events is exactly what you would expect given the name of the event. There are also events to support drag and drop operations, including DragDrop and DragOver.

Some other common control events are Change, which occurs when the data in a control is changed, GotFocus and LostFocus, which occur when the user enters or leaves the control using the mouse or keyboard, and the Link... events, which are used for DDE operations.

Among all the control events, the one which is used most often in applications is the click event - normally attached to command button controls and menu controls.

Special Note for Access Programmers

If you have experience programming in Microsoft Access using Access Basic or macros, one of the things you'll find missing are the various BeforeUpdate and AfterUpdate events for forms and controls. If you're used to using these events, you're going to have to find some other means

Page 12: Visual basic

of doing whatever you were doing there. While there is a Change event for controls, the event is fired after every change - meaning after every keystroke while the user is typing.

On the other hand, if you've ever had to write a form level keyboard handler in Access, you'll find the Visual Basic KeyPreview property for forms will greatly simplify your efforts.

From Wikipedia, the free encyclopedia  (Redirected from Event driven programming language)Jump to: navigation, search

This article has multiple issues. Please help improve it or discuss these issues on the talk page.

It may contain original research or unverifiable claims. Tagged since October 2009. Its factual accuracy is disputed. Tagged since October 2009.

Programming paradigms

Agent-oriented Component-based

o Flow-based o Pipeline

Concatenative Concurrent computing Data-driven Declarative (contrast: Imperative)

o Constraint o Functional o Dataflow

Cell-oriented (spreadsheets)

Reactive o Logic

Abductive logic Constraint logic Inductive logic

Event-driven o Service-oriented o Time-driven

Expression-oriented Feature-oriented Function-level (contrast: Value-level) Imperative (contrast: Declarative)

o Procedural

Page 13: Visual basic

Language-oriented o Domain-specific o Grammar-oriented

Dialecting o Intentional

Metaprogramming o Automatic o Generic

Template Policy-based

o Reflective Attribute-oriented

Non-structured (contrast: Structured) o Array (contrast: Scalar)o Iterative

Nondeterministic Parallel computing

o Process-oriented Programming in the large and

programming in the small Structured (contrast: Non-structured)

o Modular (contrast: Monolithic)o Recursive o Object-oriented

Automata-based By separation of concerns:

Aspect-oriented Subject-oriented Role-oriented

Class-based Prototype-based

Value-level (contrast: Function-level) Semantic

This box: view · talk · edit

In computer programming, event-driven programming or event-based programming is a programming paradigm in which the flow of the program is determined by events—i.e., sensor outputs or user actions (mouse clicks, key presses) or messages from other programs or threads.

Event-driven programming can also be defined as an application architecture technique in which the application has a main loop which is clearly divided down to two sections: the first is event selection (or event detection), and the second is event handling. In embedded systems the same

Page 14: Visual basic

may be achieved using interrupts instead of a constantly running main loop; in that case the former portion of the architecture resides completely in hardware.

Event-driven programs can be written in any language, although the task is easier in languages that provide high-level abstractions, such as closures. Some integrated development environments provide code generation assistants that automate the most repetitive tasks required for event handling.

Contents

[hide]

1 Criticism and best practice 2 Event handlers

o 2.1 A trivial event handler o 2.2 Exception handlers o 2.3 Creating event handlers

3 See also 4 References 5 External links

[edit] Criticism and best practice

Event-driven programming is widely used in graphical user interfaces because it has been adopted by most commercial widget toolkits as the model for interaction. The design of those toolkits has been criticized for promoting an over-simplified model of event-action, leading programmers to create error prone, difficult to extend and excessively complex application code:[1]

Such an approach is fertile ground for bugs for at least three reasons:

1. It is hard to learn.2. It is not thread safe.3. It doesn't try to have shared memory problems that can be solved with fancy

algorithms.

Instead of a low level action-reaction, Miro Samek proposes a better approach using finite state machines to control the interaction logic necessary to define the state changes to incoming events. Hierarchical state machines have also been proposed as a high-level model for reactive programs.[2] The UML language in particular provides a complete specification to represent state machines.

[edit] Event handlers

Page 15: Visual basic

[edit] A trivial event handler

Because the code for checking for events and the main loop does not depend on the application, many programming frameworks take care of their implementation and expect the user to provide only the code for the event handlers. In this simple example there may be a call to an event handler called OnKeyEnter() that includes an argument with a string of characters, corresponding to what the user typed before hitting the ENTER key. To add two numbers, storage outside the event handler must be used so the implementation might look like below.

globally declare the counter K and the integer T.OnKeyEnter(character C){ convert C to a number N if K is zero store N in T and increment K otherwise add N to T, print the result and reset K to zero}

While keeping track of history is straightforward in a batch program, it requires special attention and planning in an event-driven program.

[edit] Exception handlers

In some programming languages (e.g. PL/1), even though a program itself may not be predominantly event driven, certain abnormal events such as a hardware error, overflow or "program checks" may occur that possibly prevents further processing. Exception handlers may be provided by "ON statements" in (unseen) callers to provide housekeeping routines to clean up afterwards before termination.

[edit] Creating event handlers

The first step in developing an event-driven program is to write a series of subroutines, or methods, called event-handler routines. These routines handle the events to which the main program will respond. For example, a single left-button mouse-click on a command button in a GUI program may trigger a routine that will open another window, save data to a database or exit the application. Many modern day programming environments provide the programmer with event templates so that the programmer only needs to supply the event code.

The second step is to bind event handlers to events so that the correct function is called when the event takes place. Graphical editors combine the first two steps: double-click on a button, and the editor creates an (empty) event handler associated with the user clicking the button and opens a text window so you can edit the event handler.

The third step in developing an event-driven program is to write the main loop. This is a function that checks for the occurrence of events, and then calls the matching event handler to process it. Most event-driven programming environments already provide this main loop, so it need not be specifically provided by the application programmer. RPG, an early programming language from IBM, whose 1960s design concept was similar to event driven programming discussed above,

Page 16: Visual basic

provided a built-in main I/O loop (known as the "program cycle") where the calculations responded in accordance to 'indicators' (flags) that were set earlier in the cycle

Graphical user interfaceFrom Wikipedia, the free encyclopediaJump to: navigation, search "GUI" redirects here. For other uses, see GUI (disambiguation).

This article has multiple issues. Please help improve it or discuss these issues on the talk page.

Its references would be clearer with a different or consistent style of citation, footnoting or external linking. Tagged since August 2008.

It needs additional references or sources for verification. Tagged since March 2008. It may require general cleanup to meet Wikipedia's quality standards. Tagged since

June 2009.

Screenshot of Mac OS X GUI.

Screenshot of KDE Plasma Desktop GUI.

Page 17: Visual basic

The Macintosh 128K was the first commercially successful personal computer to use a graphical user interface

A graphical user interface (GUI), pronounced gooey,[1] is a type of user interface that allows users to interact with programs in more ways than typing such as computers; hand-held devices such as MP3 players, portable media players or gaming devices; household appliances and office equipment with images rather than text commands. A GUI offers graphical icons, and visual indicators, as opposed to text-based interfaces, typed command labels or text navigation to fully represent the information and actions available to a user. The actions are usually performed through direct manipulation of the graphical elements.[2]

The term GUI is historically restricted to the scope of two-dimensional display screens with display resolutions capable of describing generic information, in the tradition of the computer science research at the Palo Alto Research Center (PARC). The term GUI earlier might have been applicable to other high-resolution types of interfaces that are non-generic, such as videogames, or not restricted to flat screens, like volumetric displays.[3]

Contents

[hide]

1 History o 1.1 Precursors o 1.2 PARC user interface o 1.3 Evolution

2 Components 3 Post-WIMP interfaces 4 User interface and interaction design 5 Comparison to other interfaces

o 5.1 Command-line interfaces 6 Three-dimensional user interfaces

Page 18: Visual basic

o 6.1 Motivation o 6.2 Technologies

7 See also 8 References 9 External links

[edit] History

An early-1990s style Unix desktop running the X Window System graphical user interfaceMain article: History of the graphical user interface

[edit] Precursors

A precursor to GUIs was invented by researchers at the Stanford Research Institute, led by Douglas Engelbart. They developed the use of text-based hyperlinks manipulated with a mouse for the On-Line System. The concept of hyperlinks was further refined and extended to graphics by researchers at Xerox PARC, who went beyond text-based hyperlinks and used a GUI as the primary interface for the Xerox Alto computer. Most modern general-purpose GUIs are derived from this system. As a result, some people[who?] call this class of interface a PARC User Interface (PUI) (note that PUI is also an acronym for perceptual user interface).[4]

Ivan Sutherland developed a pointer-based system called the Sketchpad in 1963. It used a light-pen to guide the creation and manipulation of objects in engineering drawings.

[edit] PARC user interface

The PARC user interface consisted of graphical elements such as windows, menus, radio buttons, check boxes and icons. The PARC user interface employs a pointing device in addition to a keyboard. These aspects can be emphasized by using the alternative acronym WIMP, which stands for windows, icons, menus and pointing device.

[edit] Evolution

Page 19: Visual basic

The Xerox Star Workstation introduced the first GUI operating systems as shown above.

Following PARC the first GUI-centric computer operating model was the Xerox 8010 Star Information System in 1981,[5] followed by the Apple Lisa (which presented the concept of menu bar as well as window controls) in 1983, the Apple Macintosh 128K in 1984, and the Atari ST and Commodore Amiga in 1985.

The GUIs familiar to most people today are Mac OS X, Microsoft Windows, and X Window System interfaces. Apple, IBM and Microsoft used many of Xerox's ideas to develop products, and IBM's Common User Access specifications formed the basis of the user interface found in Microsoft Windows, IBM OS/2 Presentation Manager, and the Unix Motif toolkit and window manager. These ideas evolved to create the interface found in current versions of Microsoft Windows, as well as in Mac OS X and various desktop environments for Unix-like operating systems, such as Linux. Thus most current GUIs have largely common idioms.

[edit] Components

Main article: Elements of graphical user interfacesFurther information: WIMP (computing), Window manager, and Desktop environment

A GUI uses a combination of technologies and devices to provide a platform the user can interact with, for the tasks of gathering and producing information.

A series of elements conforming a visual language have evolved to represent information stored in computers. This makes it easier for people with few computer skills to work with and use computer software. The most common combination of such elements in GUIs is the WIMP ("window, icon, menu, pointing device") paradigm, especially in personal computers.

The WIMP style of interaction uses a physical input device to control the position of a cursor and presents information organized in windows and represented with icons. Available commands are compiled together in menus, and actions are performed making gestures with the pointing device. A window manager facilitates the interactions between windows, applications, and the windowing system. The windowing system handles hardware devices such as pointing devices and graphics hardware, as well as the positioning of the cursor.

Page 20: Visual basic

In personal computers all these elements are modeled through a desktop metaphor, to produce a simulation called a desktop environment in which the display represents a desktop, upon which documents and folders of documents can be placed. Window managers and other software combine to simulate the desktop environment with varying degrees of realism.

[edit] Post-WIMP interfaces

Main article: Post-WIMP

Smaller mobile devices such as PDAs and smartphones typically use the WIMP elements with different unifying metaphors, due to constraints in space and available input devices. Applications for which WIMP is not well suited may use newer interaction techniques, collectively named as post-WIMP user interfaces.[6]

Some touch-screen-based operating systems such as Apple's iOS and Android OS currently use post-WIMP styles of interaction. The iPhone's use of more than one finger in contact with the screen allows actions such as pinching and rotating, which are not supported by a single pointer and mouse.[7]

A class of GUIs sometimes referred to as post-WIMP include 3D compositing window manager such as Compiz, Desktop Window Manager, and LG3D.[citation needed] Some post-WIMP interfaces may be better suited for applications which model immersive 3D environments, such as Google Earth.[8]

[edit] User interface and interaction design

Main article: User interface design

Designing the visual composition and temporal behavior of GUI is an important part of software application programming. Its goal is to enhance the efficiency and ease of use for the underlying logical design of a stored program, a design discipline known as usability. Techniques of user-centered design are used to ensure that the visual language introduced in the design is well tailored to the tasks it must perform.

Typically, the user interacts with information by manipulating visual widgets that allow for interactions appropriate to the kind of data they hold. The widgets of a well-designed interface are selected to support the actions necessary to achieve the goals of the user. A Model-view-controller allows for a flexible structure in which the interface is independent from and indirectly linked to application functionality, so the GUI can be easily customized. This allows the user to select or design a different skin at will, and eases the designer's work to change the interface as the user needs evolve. Nevertheless, good user interface design relates to the user, not the system architecture.

The visible graphical interface features of an application are sometimes referred to as "chrome".[9] Larger widgets, such as windows, usually provide a frame or container for the main

Page 21: Visual basic

presentation content such as a web page, email message or drawing. Smaller ones usually act as a user-input tool.

A GUI may be designed for the rigorous requirements of a vertical market. This is known as an "application specific graphical user interface." Among early application specific GUIs was Gene Mosher's 1986 Point of Sale touchscreen GUI. Other examples of an application specific GUIs are:

Self-service checkouts used in a retail store Automated teller machines (ATM) Airline self-ticketing and check-in Information kiosks in a public space, like a train station or a museum Monitors or control screens in an embedded industrial application which employ a real

time operating system (RTOS).

The latest cell phones and handheld game systems also employ application specific touchscreen GUIs. Newer automobiles use GUIs in their navigation systems and touch screen multimedia centers.

[edit] Comparison to other interfaces

[edit] Command-line interfaces

Modern CLI

GUIs were introduced in reaction to the steep learning curve of command-line interfaces (CLI),[10][11][11] which require commands to be typed on the keyboard. Since the commands available in command line interfaces can be numerous, complicated operations can be completed using a short sequence of words and symbols. This allows for greater efficiency and productivity once

Page 22: Visual basic

many commands are learned,[10][11][11] but reaching this level takes some time because the command words are not easily discoverable and not mnemonic. WIMPs ("window, icon, menu, pointing device"), on the other hand, present the user with numerous widgets that represent and can trigger some of the system's available commands.

WIMPs extensively use modes as the meaning of all keys and clicks on specific positions on the screen are redefined all the time. Command line interfaces use modes only in limited forms, such as the current directory and environment variables.

Most modern operating systems provide both a GUI and some level of a CLI, although the GUIs usually receive more attention. The GUI is usually WIMP-based, although occasionally other metaphors surface, such as those used in Microsoft Bob, 3dwm or File System Visualizer (FSV).

Applications may also provide both interfaces, and when they do the GUI is usually a WIMP wrapper around the command-line version. This is especially common with applications designed for Unix-like operating systems. The latter used to be implemented first because it allowed the developers to focus exclusively on their product's functionality without bothering about interface details such as designing icons and placing buttons. Designing programs this way also allows users to run the program non-interactively, such as in a shell script.

[edit] Three-dimensional user interfaces

Main article: Compositing window manager

For typical computer displays, three-dimensional is a misnomer—their displays are two-dimensional. Semantically, however, most graphical user interfaces use three dimensions - in addition to height and width, they offer a third dimension of layering or stacking screen elements over one another. This may be represented visually on screen through an illusionary transparent effect, which offers the advantage that information in background windows may still be read, if not interacted with. Or the environment may simply hide the background information, possibly making the distinction apparent by drawing a drop shadow effect over it.

Some environments use the techniques of 3D graphics to project virtual three dimensional user interface objects onto the screen. As the processing power of computer graphics hardware increases, this becomes less of an obstacle to a smooth user experience.

[edit] Motivation

Three-dimensional GUIs are quite common in science fiction literature and movies, such as in Jurassic Park, which features Silicon Graphics' three-dimensional file manager, "File system navigator", an actual file manager that never got much widespread use as the user interface for a Unix computer. In fiction, three-dimensional user interfaces are often immersible environments like William Gibson's Cyberspace or Neal Stephenson's Metaverse.

Three-dimensional graphics are currently mostly used in computer games, art and computer-aided design (CAD). There have been several attempts at making three-dimensional desktop

Page 23: Visual basic

environments like Sun's Project Looking Glass or SphereXP from Sphere Inc. A three-dimensional computing environment could possibly be used for collaborative work. For example, scientists could study three-dimensional models of molecules in a virtual reality environment, or engineers could work on assembling a three-dimensional model of an airplane. This is a goal of the Croquet project and Project Looking Glass.[12]

[edit] Technologies

The use of three-dimensional graphics has become increasingly common in mainstream operating systems, from creating attractive interfaces—eye candy— to functional purposes only possible using three dimensions. For example, user switching is represented by rotating a cube whose faces are each user's workspace, and window management is represented via a Rolodex-style flipping mechanism in Windows Vista (see Windows Flip 3D). In both cases, the operating system transforms windows on-the-fly while continuing to update the content of those windows.

Interfaces for the X Window System have also implemented advanced three-dimensional user interfaces through compositing window managers such as Beryl, Compiz and KWin using the AIGLX or XGL architectures, allowing for the usage of OpenGL to animate the user's interactions with the desktop.

Another branch in the three-dimensional desktop environment is the three-dimensional GUIs that take the desktop metaphor a step further, like the BumpTop, where a user can manipulate documents and windows as if they were "real world" documents, with realistic movement and physics.

The Zooming User Interface (ZUI) is a related technology that promises to deliver the representation benefits of 3D environments without their usability drawbacks of orientation problems and hidden objects. It is a logical advancement on the GUI, blending some three-dimensional movement with two-dimensional or "2.5D" vector objects

graphical user interface

Tweet 0diggsdigg

Abbreviated GUI (pronounced GOO-ee). A program interface that takes advantage of the computer's graphics capabilities to make the program easier to use. Well-designed graphical user

Page 24: Visual basic

interfaces can free the user from learning complex command languages. On the other hand, many users find that they work more effectively with a command-driven interface, especially if they already know the command language.

Graphical user interfaces, such as Microsoft Windows and the one used by the Apple Macintosh, feature the following basic components:

pointer : A symbol that appears on the display screen and that you move to select objects and commands. Usually, the pointer appears as a small angled arrow. Text -processing applications, however, use an I-beam pointer that is shaped like a capital I. pointing device : A device, such as a mouse or trackball, that enables you to select objects on the display screen. icons : Small pictures that represent commands, files, or windows. By moving the pointer to the icon and pressing a mouse button, you can execute a command or convert the icon into a window. You can also move the icons around the display screen as if they were real objects on your desk. desktop : The area on the display screen where icons are grouped is often referred to as the desktop because the icons are intended to represent real objects on a real desktop. windows: You can divide the screen into different areas. In each window, you can run a different program or display a different file. You can move windows around the display screen, and change their shape and size at will. menus : Most graphical user interfaces let you execute commands by selecting a choice from a menu.

The first graphical user interface was designed by Xerox Corporation's Palo Alto Research Center in the 1970s, but it was not until the 1980s and the emergence of the Apple Macintosh that graphical user interfaces became popular. One reason for their slow acceptance was the fact that they require considerable CPU power and a high-quality monitor, which until recently were prohibitively expensive.

In addition to their visual components, graphical user interfaces also make it easier to move data from one application to another. A true GUI includes standard formats for representing text and graphics. Because the formats are well-defined, different programs that run under a common GUI can share data. This makes it possible, for example, to copy a graph created by a spreadsheet program into a document created by a word processor.

Many DOS programs include some features of GUIs, such as menus, but are not graphics based. Such interfaces are sometimes called graphical character-based user interfaces to distinguish them from true GUIs

Introduction

There are a variety of university-level computer-human interaction (CHI) programs. Although a few offer breath and diversity, many students graduate from universities that offer only one or two CHI courses. As such, most students have a limited background in the various CHI areas. This article offers a general overview in one area, graphical user interfaces (GUI).  A GUI allows

Page 25: Visual basic

a computer user to move from application to application [26]. A good GUI makes an application easy, practical, and efficient to use, and the marketplace success of today's software programs depends on good GUI design. Consider the Macintosh and the IBM-PC. Computer users view Apple's Macintosh computers as having the best GUI. Correspondingly, their positive view of the Macintosh system is almost double that of the Windows users [1] . Correspondingly, brand loyalty among Macintosh users is almost 20% higher than that for Windows users [26].

The development of a new software is extremely expense. With success or failure of a product and maybe the entire company dependent on the application's GUI reception in the marketplace, a good GUI design is extremely important. Unfortunately, it is not easy to define if an application's GUI is easy, practical, or efficient. These are attributes that do not lend themselves to counting. The marketplace does attempt to access these attributes, however [6], but even after over 10 years of GUI development, there are still questions concerning what is a good GUI design.

For example, the early Macintosh Apple used the Trash Can icon as a metaphor for deleting files. However, one can pull items out of a trash can until the trash person comes. The first trash can icon did not allow this retrieval. This contextual incongruity caused users many problems. As another example, the Windows'95 GUI is the most modern of all GUI. One would expect it to be fairly well developed and relatively error free. However, of the approximately 90 complaints with the Windows'95, none are performance complaints. They are all human factors type complaints, such as how to copy a file and how to get rid of annoying icons [25]. Finally, people have so many complaints about the X-Windowing System, the third major GUI standard, that there is whole book about what is wrong with it [12].

This paper will survey the common definitions of what a GUI is and review the three common, GUI standards in the market today. It will then review three of the many human factor concepts underlying good GUI design, which are visual acuity, limits to absolute memory, and the principle of grouping. The paper will then present the effect of these factors on three GUI design areas, the amount of presented information, the grouping of information, and the placement of this information on the screen. Following this section, the ramifications of bad versus good GUI design will be addressed. Areas for research and likely directions of future GUI design conclude the paper.

GUI

Although there are numerous GUIs in the market today, the exact definition of a GUI is still fuzzy. This may be due to the fact that GUIs are relatively new. There are three de facto GUI-standards that are the basis for all GUIs. This section reviews the common definition of GUIs, the history of GUI development, and GUI standards in the marketplace.

Definition

A GUI is a type of computer human interface on a computer. It solves the blank screen problem that confronted early computer users [19]. These early users sat down in front of a computer and

Page 26: Visual basic

faced a blank screen, with only a prompt. The computer gave the user no indication what the user was to do next. GUI are an attempt to solve this blank screen problem.

At a conceptual level, a computer human interface is a "means by which people and computers communicate with each other" [6, 262]. One can make an analogy between a computer system's GUI and a car's steering wheel. The wheel directly binds the driver to the operation and functionality of the vehicle. When driving, a driver should not have to concentrate on the steering wheel. In the same way, the GUI binds the user of the computer system to the operation and potential of the computer system [6]. A good GUI design removes the impediment of communication with the computer system and allows the user to work directly on the problem at hand [19].

In computer science terms, the GUI is a visual operating display that the monitor presents on the monitor to the computer operator [9]. More specifically, a GUI is a specification for the look and feel of the computer system [6]. GUI usually have common characteristic such as windows, icons, menus, and push-buttons (WIMP). Collectively, WIMP are pictures that bring forth a certain action or an action space. The user issues commands via the GUI to computer applications. GUI usually have three major components. These three components are [10]: a windowing system, an imaging model, and an application program interface (API). The windowing system builds the windows, menus, and dialog boxes that appear on the screen. The imaging model defines the fonts and graphics that appear on the screen. WIMP are products of both the windowing system and imaging model. Finally, the API is the means in which the user specifies how and what windows and graphics appear on the screen.

The historical development of the GUI still impacts the three major GUI paradigms in the market today. Historically, all modern GUI are off-shoots of the Apple Macintosh. This has lead to a great deal of standardization and consistency among GUI design criteria. Therefore, most application's GUI adhere to one of the three major GUI paradigms, the Apple Macintosh, the IBM Systems Application Architecture (SAA), or the X-Windowing System. While none of these GUI designs are perfect, the overall design concepts are good enough to make radical departures counterproductive [19], unless there are significant performance enhancements.

History

Researchers at the Xerox Palo Alto Research Center designed the first application with a GUI, the Xerox Star, in 1977. The Xerox Star was unique because the researchers carefully designed the computer human interface before they began designing the internal workings of the application. Unfortunately, the Xerox Star was too slow, and it was not commercially successful.

However, Steve Jobs visited the Palo Alto Research Center and saw Xerox Star. He returned to Apple Computer and subsequently hired several of the original designers of Xerox Star. They first produced the Apple Lisa. Like the Xerox Star, the Apple Lisa was not commercially successful. In 1984, they developed the commercially successful Apple Macintosh. In the broadest terms, the Macintosh's GUI defined the look and feel of all GUIs today.

De Facto Standards

Page 27: Visual basic

The Apple Macintosh, the IBM SAA, and X-Windowing System are the paradigms for all modern GUI. Because of their influence in the standardization of today's GUI design, a brief description of the major features of each standard is necessary.

Apple Macintosh

Apple introduced the Macintosh as a computer "for rest of us." The GUI was a major part of the overall goal of the Macintosh. All graphical applications copied the Macintosh in its design and usage. The Macintosh introduced the first menu, icons, and point-and-click, mouse driven processing. With these menus and icons, the Macintosh was the first computer system that limited the users to contextual correct answers. For example, once the user made a selection via a menu, the menu limited the user's subsequent actions. The user could no longer choose something meaningless. The Macintosh's GUI has all three major components of a GUI, which are the windowing system, an imaging model, and an API.

IBM SAA

Unlike the Apple Macintosh, the IBM-SAA is more than just a GUI. It is a whole system of interfaces that can span machines from personal to mainframe computers. As such, it includes many functions that most GUIs do not, including a suite of networking and database tools. The SAA's GUI portion has all three GUI components. Another unique item of the SAA is that the user does not need a mouse to interact with the application. All actions can be executed from the keyboard, a functionality not available in the Macintosh GUI. The most common SAA-type GUIs are Windows 3.11 for DOS and the Program Manger for OS/2.

MIT X-Windows System

Although a separate GUI standard, many X-Window based GUI, such as Motif and TCL/TK, have copied the look and feel of the IBM SAA. X-Windows is still the underlying library for these GUI. The X-Windowing System is the most popular GUI for UNIX systems. This is because any X-Windows software can use the X-Windows library, which gives it great portability and standardization across platforms. Figure 1 illustrates a typical X-Windows GUI with three common icons.

Page 28: Visual basic

X-Windows also works directly with networks, which allows the GUI display to be on one computer and the application that the user needs on another computer. It does not matter if the

two computers are in different rooms or on different continents. It addition to the three common GUI components, X-Windows has a collect of application tools and utilities as a built in X-

Library. Figure 2 illustrates a TCL/TK GUI that uses the X-Library utilities. TCL/TK has the IBM SAA "look-and-feel."

Theoretical Background

Although GUI are an integral part of an application, GUIs are not inherently easier to use than command line interfaces. The quality of the design is the overriding issue for all interfaces [4][ 5] . There are several screen design guidelines. On the other hand, there is shortage of empirical studies substantiating these guidelines. This lack of empirical research is especially apparent for modern GUI designs, such as Windows '95, Quicken 7.0, and Dbase 5.

In a narrower sense, there are empirical studies that have identified basic psychological factors that one should consider in the design of good GUI. This paper will narrow the discussion to

Page 29: Visual basic

three primary contributing human factors, which are: the physical limits of visual acuity, the limits of absolute memory, and the Gestalt Principle.

Visual Acuity

Visual acuity is the ability of the eye to resolve detail. The retina of eye can only focus on about on a very small portion of a computer screen, or anything for that matter, at any one time [24]. This is because, at a distance greater than 2.5 degrees from the point of fixation, visual acuity decreases by half. Therefore, a circle of radius 2.5 degrees around the point of fixation is what the user can see clearly.

In the GUI world, this is the Rule of 1.7 [21]. At a normal viewing distance of 19 inches, 5 degrees translates into about 1.7 inches. Assuming a standard screen format, 1.7 inches is an area about 14 characters wide and about 7 lines high [11]. This is the amount of information that a user can take in at any one time, and it limits the effective size of icons, menus, dialogs boxes, etc. If the user must constantly move his eyes across the screen to clearly focus, the GUI design is causing a lot of unnecessary and tiring eye movement.

Information Limits

Once the user has a desired fixation point, there is a limit to the amount of information that the person can process at one time. A GUI design rule of thumb is that the range of options or choices should never be more than five or six [17] [ 21 ] . Seminal work by Miller is the basis for this rule. Miller [ 17] showed that absolute identification using one-dimensional criteria was about seven items, plus or minus two. He showed that this limitation also held for memory span. Miller introduced the concept of recoding as a method that people use to store information. Miller also pointed out that by expanding the identification criteria from one to more dimensions people could handle more choices and remember more. Later researchers expanded on Miller recoding to develop the concept that people chuck information together in order to remember more information [ 2 ] [23] . This research has direct impact on GUI design, especially concerning the number of menu items and icons.

Gestalt Principle

The Gestalt Principle states that people use a top-down approach to organizing data [11] [24 ] . This principle can influence how one should organize graphical information on the screen. The Gestalt school of GUI designers have attempted to identify criteria that cause people to group certain items together in a display. Proper grouping results in a necessary redundancy of selection information that aids the user. For example, if the user knows where one item in a group is on a screen, he will expect other like items to be there also. If one groups the items in line with this expectation, it allows for accurate locating and better transfer of information to the user.

The top-down approach also allows for the development of emergent features. An emergent feature is a global property of a set that is not evident when one views each item locally. Since global processing tends to be automatic, one can argue that an emerged feature reduces the

Page 30: Visual basic

attention demand as a user operates a multi-element display. For this performance enhancement, one must use the Gestalt Principle in the initial placement, and the resulting organization must be compatible with the user's cognitive view of the task [ 24 ] .

GUI Design Considerations

Considering the above psychological factors, one could come to the conclusion that one could easily extrapolate these factors to the design of a good GUI. Empirical studies of GUI show that this intuition this is not always the case. The Rule of 1.7 directly leads to the conclusion that a good GUI would use a lot of icons. Unfortunately, too many randomly placed icons violate the limits of absolute memory. Using the Gestalt Principle, one can group like items together using factors like color to add more informational dimensions. Too many colors, however, destroy the global visual grouping of the items. The user then begins to concentrates on the GUI. Any primary cognitive task attention devoted to the interface may interfere with the primary task [19]. One can derive basis GUI standards from basic human factors, however. These standards are the presentation of information, the grouping of information, and information sequencing.

Amount of Information Presented

The amount of information to present is the most basic of GUI design considerations. H.E. Dunsmore [3] [11] [20] showed that making screens less crowded improves screen clarity and readability. As such, GUI designers usually follow the guidance that the interface should display only what the user needs to perform the current operation. Empirical researchers show that limiting the information to that necessary for the user reduces errors and time to perform tasks. Errors and performance time increase as the GUI presents more information. Of course, it requires a thorough analysis of the tasks that the user must perform in order to display only the necessary amount of information.

Compared to a randomly placed screen, a well-designed screen can reduce time needed to perform a task by as much as 40% [11] [15] . Ways to conserve screen space are:

1. Appropriate use of abbreviations: Many design documents recommend using complete words whenever possible. Due to screen sizing constraints, it is not always possible to use complete words. When complete words are not possible, abbreviations should be contextual and consistent. A good contextual example is "h," which is usually a good abbreviation to use for help. The number of abbreviations should not only be contextual but also be keep to a minimum. As a poor example, in the UNIX system, the "ls" command list files in a directory. The "ls" command has 17 different one-letter abbreviations that change the output options of the "ls" command. The one-letter abbreviations have little contextual link to the options they represent. In fact, the UNIX system is a good example of what not to do.

2. Avoid unnecessary detail: For example, use whole numbers if one does not need decimals. Keep the window and icon designs clear and simple. Even when users prefer more complex icons, elaborate icons add nothing to performance. Studies show, that when icon designs are too complex, time to complete a task actually increases [4]. In

Page 31: Visual basic

studies with 3-D and 2-D graphical displays, users preferred the 3-D displays. There were no differences in performance between the two graphical displays, however [14].

3. Use concise wording: Screens have limited space. Screen designers should avoid the tendency to place additional data on the screen just because the data is available. More objective limits of screen density vary from thresholds of 25% to 80% [11]. There is no empirical research that substantiates any performance enhancement with any specific threshold.

4. Use familiar data formats: With more familiar formats, the user will need less information to complete the task. An example for data entry is the standard USA address format of street, city, state, and zip code. In additional to requiring less instruction, the user will perform the operation faster than if the format is unfamiliar.

5. Use tabular formats with column headings: Tabular formats allow for efficient labeling of related data. It is especially preferable for data location tasks. Simply splitting items on one long line into two lines result in productivity improvements of 20% [21]. Also, LaLomia and Coovert's research [11] showed that locating a data value was quicker in tabular form then in a random or graph format. For trend analysis, a line graph is quicker than raw data [11].

Grouping of Information

Given a set of information to display, there are many ways one can display the information. Proper grouping improves the information's readability and can highlight relationships between the information [ 11] . Tullis' [11 ] [21] experiments in the mid-1980s showed that the best predictors of search time were the number of and size of the groups. Therefore, one should structure displays with the limits of visual acuity in mind. The user needs to be able to take in the different chunks of information at one glance to improve readability. Overall, the best predictors of ease of use were density and item alignment.

Empirical research shows that search time increases as the size of the grouping exceeds 5 degrees of arc and the number of groupings increases above five [11] [24] . With groupings less than 5 degrees, the search duration is directly a function of the total number of groupings on the screen [11]. There are several techniques to aid in the grouping of information, which include:

1. Color: Presenting different groups with different color clearly creates some degree of grouping among the elements of the same color. GUI that utilize color well increase productivity [3]. If like color items are in close proximity, the visual association is stronger than if the like color items are further apart. In addition to changing the item's colors, one can use different colors for the background and foreground. The effectiveness of this technique decreases as the number of screen colors increases [11]. Overuse of color degrades performance, however.

2. Graphical Boundaries: Drawing boundaries around elements is the most common method of grouping elements in GUI. Although there is no empirical evidence to show that these groupings improve performance, users prefer this type of groupings compared to other methods. This technique is especially popular with the IBM SAA systems. Another method of grouping is to group tasks within icons. Icon grouping is easy because many icons can have common attributes. Icons are also small and therefore use less space [22],

Page 32: Visual basic

less than 5 degrees of arc. Another advantage of icons is that recognition is faster for pictures than for text [4]. This makes it easier for the novice to learn a system. Studies also show that icons have smaller error rates than textual interfaces and the same as for menu interfaces [22]. Conversely though, empirical studies have shown that, counter intuitively, icons do not lead to greater increases in performance.

3. Highlighting: Besides color, there are several other methods of highlighting including reverse video, brightness, underlining, and flashing. The most common use of highlighting is reverse video to indicate an item that is currently selected. GUI usually use brightness to show which items are not active at a given time. Underlining is effective if it does not interfere with the legibility of characters. Flashing will both get attention and annoy if the user can not turn off the flashing. Therefore, one should use flashing only to convey an urgent need. The Apple Macintosh uses flashing to signal only program or data destruction. Regardless of which type of highlighting, one needs to apply it conservatively. Overuse of highlighting causes confusion among users and defeats its purpose. Additionally, if one highlights the wrong information, the user has more difficulty detecting the important information [11].

Information Sequencing

One needs to lay out a screen in a manner that allows the user to easily find any information on it. Most designers advocate the use of one the de facto GUI screen standards. This is because many users now expect certain modes of operation in all GUI. For example, most users expect the top of screen to contain the headings for the pull-down menus. The top right is the default location for icons representing the disk availability. In the Macintosh GUI, the bottom right contains the trash icons used for deleting files.

Within a window, there are also many standard modes. A window title is usually at the top. Scroll bars are on the right and bottom for vertical and horizontal window movement. A box for closing the window is at the top left. Icons for resizing the window are at the four corners [11].

Studies show that most users initially scan the screen starting at the upper-left corner. This corner should be the obvious starting point for applications invoked from within the window. This permits a left-to-right and top-to-bottom reading, which is standard for Western cultures.

The optimum sequence for screen presentations is a collection of various factors, including:

1. Sequence of use: One needs to present the user the information in the order that the user will probably utilize it.

2. Conventional Usage: If a common convention is in general usage, the GUI design should continue using it. For example, in the standard window layout, the file option is usually to the far left of the menu bar.

3. Importance: The designer needs to place the more important information a prominent location. For example, if several entries are possible, the GUI should lead off with the required ones and end with the optional ones.

Page 33: Visual basic

4. Frequency of use: One should place the most frequently utilized commands at the beginning. For example, in a menu list, the most frequency utilized commands should be at the top of the list.

5. Generality versus Specificity: The more general items should precede the more specific items, especially when there is a hierarchical relationship among the data.

6. Alphabetical or Chronological: If there is no other rules for ordering data element, then one should adopt some other technique such as an alphabetical or a temporal listing. Card [11] showed that selection time was faster for alphabetical than for any other functional grouping.

The goal of any GUI is to allow the user to work through the computer and application to concentrate on the primary cognitive task. The user should not be concerned with the user interface. Any attention devoted to the interface interferes with the main task [4] [19] .

Ramifications

What are the ramifications of GUI design? One consistent result is that an increased operational knowledge transfer between applications reduces training costs [9]. Training costs are usually one to three times the cost of the actual software and hardware [3] [7] . A good GUI design reduces required training time to 20-30 hours for a user to learn an application [8]. For businesses, this means that a good GUI saves money and time. Additionally, a good GUI improves the user's perception of the application. The user's first 15 minutes of usage formulates the lasting impression of an application [26].

Conclusion

The primary goal of a GUI is to allow the user to concentrate on the task at hand. To do this, the GUI must make the interface between the human and the computer seamless. Modern GUIs adhere to one of three de facto standards, which are the Apple Macintosh, the IBM SAA, and the MIT X-Windowing System. These standards are not perfect, but they are good enough to preclude major deviation. Future GUI will probably utilize one or more of these standards unless major performance enhancements result. Utilizing key psychological factors, GUI designers can achieve a seamless computer human interface.

The three primary human factors that directly affect GUI design are visual acuity, the limits of absolute memory, and the grouping of information. At about 19 inches from an object, a person's visual acuity is about 5 degrees of arc. There appears to be a limit to absolute memory of about 7 items. Grouping of information based on the Gestalt principle appears to aid in information processing.

Use of these factors result in GUI design principles that govern the amount of information to present, the proper way to group this information, and the proper placement and sequencing of this information on the screen. A good GUI should present information that is contextual and consistent. It should avoid unnecessary detail and use concise wording to conserve screen space. If familiar data formats exist, the GUI should utilize them.

Page 34: Visual basic

A GUI needs to group information using color to associate like items. Graphical boundaries are a very effective means to group like items, especially icons. Other highlighting techniques include reverse video, brightness, underlining, and flashing.

One needs to sequence information on the screen to facilitate the user. The presentation of information should follow the sequence that the user needs it. Common information needs to be in common locations across windows and GUI. The most important information needs to precede the lesser important information. Frequently utilized information or commands need to be in the most prominent location. The more general items should precede the more specific items. If no other ordering exists, one should alphabetize.

The ramification of good GUI design results in reduced training time and improved performance. Reduced training time means lower costs and improved user perceptions. Bad GUI design prevents the user from concentrating on the primary cognitive task. This results in user frustrations, decreased performance, higher costs, and possibly product and marketplace failure.

When designing GUI, one need to keep the objectives of the GUI in mind and to generally avoid needless complexity [16]. One must avoid useless innovation [18] and concentrate on improvements that enhance performance. Future trends in GUI are toward voice recognition and hypertext format language [10] [13] [18] . The hypertext trend allows the user to move directly from data and concepts in one application to similar data and concepts in other application. These trends will further remove the GUI as an obstacle between the user and the task.

User-interface standards

Consider preloading forms to increase the responsiveness of your application. Be careful not to preload too many (preloading three or four forms is fine).

Use resource files (.res) instead of external files when working with bitmap files, icons, and related files.

Make use of constructors and destructors to set variable references that are only set when the class is loaded. These are the VB functions Class_Initialize() and Class_Terminate(), or Form_Load() and Form_Unload(). Set all variables to Nothing when the object is destroyed.

Make sure the tab order is set correctly for the form. Do not add scrollbars to the tabbing sequence; it is too confusing.

Add access keys to those labels that identify controls of special importance on the form (use the TabIndex property).

Use system colors where possible instead of hard-coded colors.

Page 35: Visual basic

Variable declaration

Always use Option Explicit (or turn on Require Variable Declaration in the VB Options dialog box). This forces all variables to be declared before use, and thereby prevents careless mistakes.

Use Public and Private to declare variables at module scope, and Dim in local scope. (Dim and Private mean the same at Module scope, however, using Private is more informative.) Do not use Global anymore; it is available only for backward compatibility with VB 3.0 and earlier.

Always provide an explicit type for variables, arguments, and functions. Otherwise, they default to Variant, which is less efficient.

Only declare one variable per line, unless the type is specified for each variable.

This line causes count to be declared as a Variant, which is likely to be unintended.

Dim count, max As Long

This line declares both count and max as Long, the intended type.

Dim count As Long, max As Long

These lines also declare count and max as Long, and are more readable.

Dim count As Long Dim max As Long

Suggested naming standards

The tables below summarize suggested naming standards for the various elements of your Visual Basic projects.

Module Type Prefix

Form frm

Class cls

Standard bas

Project prj

Name your modules according to the overall function they provide; do not leave any with default names (such as, "Form1", "Class1", or "Module1"). Additionally, prefix the names of forms, classes, and standard modules with three letters that denote the type of module, as shown in the table above.

Page 36: Visual basic

Control Type Prefix

Check box chk

Combo box cbo

Command cmd

Common dialog cdl

Form frm

Frame fra

Graph gph

Grid grd

Image img

Image list iml

Label lbl

List box lst

List view lvw

Map control map

Masked edit msk

Menu mnu

OLE client ole

Page 37: Visual basic

Option button opt

Picture box pic

Progress bar pbr

Rich text box rtf

Scroll bar srl

Slider sld

Status bar sbr

Tab strip tab

Text box txt

Timer tmr

Tool bar tbr

Tree view tvw

As with modules, name your controls according to the function they provide; do not leave them with default names, since this leads to decreased maintainability. Use the three-letter prefixes above to identify the type of the control.

Use the following notation for naming variables and constants:

[<libraryName.>][<scope_>]<type><name>

<name> describes how the variable is used, or what it contains.The <scope> and <type> portions should always be lowercase, and the <name> should use mixed case.

Page 38: Visual basic

Library Name

Library

esriCore ESRI Object Library

stdole Standard OLE COM Library

<empty> Simple variable datatype

<libraryName>

Prefix Variable scope

cconstant within a form or class

gpublic variable defined in a class form or standard module

mprivate variable defined in a class or form

<empty> local variable

<scope>

Prefix Data Type

b Boolean

by byte or unsigned char

Page 39: Visual basic

fn Function

h Handle

i int (integer)

l Long

p a pointer

s String

<type>

Parentheses

Use parentheses to make operator precedence and logic comparison statements easier to read.

Result = ((x * 24) / (y / 12)) + 42 If ((Not pFoo Is Nothing) And (Counter > 200)) Then

Order of conditional determination

Visual Basic, unlike languages such as C and C++, performs conditional tests on all parts of the condition, even if the first part of the condition is False. This means you must not perform conditional tests on objects and interfaces that had their validity tested in an earlier part of the conditional statement.

' The following line will raise a runtime error if pFoo is NULL If ((Not pFoo Is Nothing) And (TypeOf pFoo.Thing Is IBar)) then End If

' The correct way to test this code is If (Not pFoo Is Nothing) Then If (TypeOf pFoo.Thing Is IBar) Then ' Perform action on IBar thing of Foo End If End If

Indentation

Use two spaces for indentation, or a tab-width of two. Since there is only ever one editor for VB code, formatting is not as critical an issue as it is for C++ code.

Page 40: Visual basic

Default properties

Avoid using default properties, except for the most common cases. They lead to decreased legibility.

Intermodule referencing

When accessing intermodule data or functions, always qualify the reference with the module name. This makes the code more readable and results in more efficient runtime binding.

Multiple property operations

When performing multiple operations against different properties of the same object, use a With … End With statement. It is more efficient than specifying the object each time.

With frmHello .Caption = "Hello world" .Font = "Pla bill" .Left = (Screen.Width - .Width) / 2 .Top = (Screen.Height - .Height) / 2 End With

Arrays

For arrays, never change Option Base to anything other than zero (which is the default). Use LBound and UBound to iterate over all items in an array.

myArray = GetSomeArray For i = LBound(myArray) To UBound(myArray) MsgBox cstr(myArray(i)) Next I

Bitwise operators

Since And, Or, and Not, are bitwise operators, ensure that all conditions using them test only for Boolean values (unless, of course, bitwise semantics are what is intended).

If (Not pFoo Is Nothing) Then ' Valid Foo do something with it End If

Type suffixes

Refrain from using type suffixes on variables or function names (such as myString$ or Right$(myString)), unless they are needed to distinguish 16-bit from 32-bit numbers.

Page 41: Visual basic

Ambiguous type matching

For ambiguous type matching, use explicit conversion operators (such as CSng, CDbl, and CStr), instead of relying on VB to pick which one will be used.

Simple image display

Use an ImageControl rather than a PictureBox for simple image display. It is much more efficient.

Error handling

Always use On Error to ensure fault-tolerant code. For each function that does error checking, use On Error to jump to a single error handler for the routine that deals with all exceptional conditions that are likely to be encountered. After the error handler processes the error—usually by displaying a message—it should proceed by issuing one of the recovery statements shown on the table below.

Recovery Statement

Frequency Meaning

Exit Sub usually Function failed, pass control back to caller

Raise oftenRaise a new error code in the caller's scope

Resume rarelyError condition removed, re-attempt offending statement

Resume Next

very rarelyIgnore error and continue with the next statement

Error handling in Visual Basic is not the same as general error handling in COM (see the section Working With HRESULTs).

Event functions

Refrain from placing more than a few lines of code in event functions to prevent highly-fractured and unorganized code. Event functions should simply dispatch to reusable functions elsewhere.

Page 42: Visual basic

Memory management

To ensure efficient use of memory resources, the following points should be considered:

Unload forms regularly. Do not keep many forms loaded but invisible, since this consumes system resources.

Be aware that referencing a form-scoped variable causes the form to be loaded. Set unused objects to Nothing to free up their memory. Make use of Class_Initialize() and Class_Terminate() to allocate and destroy resources.

While Wend constructs

Avoid While … Wend constructs. Use the Do While … Loop or Do Until ... Loop instead, because you can conditionally branch out of this construct.

pFoos.Reset Set pFoo = pFoos.Next Do While (Not pFoo Is Nothing) If (pFoo.Answer = "Done") Then Exit Loop Set pFoo = pFoos.Next Loop

The Visual Basic Virtual Machine

The Visual Basic Virtual Machine (VBVM) contains the intrinsic Visual Basic controls and services, such as starting and ending a Visual Basic application, required to successfully execute all Visual Basic developed code.

The VBVM was called the VB Runtime in earlier versions of the software.

The VBVM is packaged as a DLL that must be installed on any machine wanting to execute code written with Visual Basic, even if the code has been compiled to native code. If the dependencies of any Visual Basic compiled file are viewed, the file msvbvm60.dll is listed; this is the DLL housing the Virtual Machine.

For more information on the services provided by the VBVM, see the sections Interacting with the IUnknown Interface and Working With HRESULTs later in this topic.

Interacting with the IUnknown Interface

The topic on COM contains a lengthy section on the IUnknown interface and how it forms the basis upon which all of COM is built. Visual Basic hides this interface from developers and performs the required interactions (QueryInterface, AddRef, and Release function calls) on the developer's behalf. It achieves this because of functionality contained within the VBVM. This simplifies development with COM for many developers, but to work successfully with ArcObjects you must understand what the VBVM is doing.

Page 43: Visual basic

Visual Basic developers are used to dimensioning variables as follows:

Dim pColn as New Collection 'Create a new collection object PColn.Add "Foo", "Bar" 'Add element to collection

It is worth considering what is happening at this point. From a quick inspection of the code it looks like the first line creates a collection object and gives the developer a handle on that object in the form of pColn. The developer then calls a method on the object Add. In the Introduction to COM topic you learned that objects talk via their interfaces, never through a direct handle on the object itself. Remember, objects expose their services via their interfaces. If this is true, something isn't adding up.

What is actually happening is some "VB magic" performed by the VBVM, and some trickery by the Visual Basic Editor in the way that it presents objects and interfaces. The first line of code instantiates an instance of the collection class, then assigns the default interface for that object, _Collection, to the variable pColn. It is this interface, _Collection, that has the methods defined on it. Visual Basic has hidden the fact of interface-based programming to simplify the developer experience. This is not an issue if all the functionality implemented by the object can be accessed via one interface, but it is an issue when there are multiple interfaces on an object that provides services.

The Visual Basic editor backs this up by hiding default interfaces from the intellisense completion list and the object browser. By default any interfaces that begin with an underscore, "_", are not displayed in the object browser (to display these interfaces turn Show Hidden Member on, although this will still not display default interfaces).

You have already learned that the majority of ArcObjects have IUnknown as their default interface, and that Visual Basic does not expose any of IUnknown's methods, namely QueryInterface, AddRef, and Release. Assume you have a class Foo that supports three interfaces, IUnknown (the default interface), IFoo, and IBar. This means that if you were to dimension the variable pFoo as below, the variable pFoo would point to the IUnknown interfaces.

Dim pFoo As New Foo ' Create a new Foo object pFoo.??????

Since Visual Basic does not allow direct access to the methods of IUnknown, you would immediately have to QI for an interface with methods on it that you can call. Because of this, the correct way to dimension a variable that will hold pointers to interfaces is as follows:

Dim pFoo As IFoo ' Variable will hold pointer to IFoo interface Set pFoo = New Foo ' Create Instance of Foo object and QI for IFoo

Now that you have a pointer to one of the object's interfaces, it is an easy matter to request from the object any of its other interfaces.

Dim pBar as IBar 'Dim variable to hold pointer to interface Set pBar = pFoo 'QI for IBar interface

Page 44: Visual basic

By convention, most classes have an interface with the same name as the class with an "I" prefix; this tends to be the interface most commonly used when working with the object. You are not restricted to which interface you request when instantiating an object; any supported interface can be requested, hence the code below is valid.

Dim pBar as IBar Set pBar = New Foo 'CoCreate Object

Set pFoo = pBar 'QI for interface

Objects control their own lifetime, which requires clients to call AddRef anytime an interface pointer is duplicated by assigning it to another variable, and Release anytime the interface pointer is no longer required. Ensuring that there are a matching number of AddRefs and Releases is important, and fortunately Visual Basic performs these calls automatically. This ensures that objects do not "leak." Even when interface pointers are reused, Visual Basic will correctly call release on the old interface before assigning the new interface to the variable. The code below illustrates these concepts; note the reference count on the object at the various stages of code execution.

Private Sub VBMagic() ' Dim a variable to the IUnknown interface on the simple object Dim pUnk As IUnknown

' Co Create simpleobject asking for the IUnknown interface Set pUnk = New SimpleObject 'refCount = 1

' We need access to methods lets QI for a useful interface ' Define the interface we are to request Dim pMagic As ISimpleObject

' Perform the QI operation Set pMagic = punk 'refCount = 2

' Dim another variable to hold another interface on the object Dim pMagic2 As IAnotherInterface

' QI for that interface Set pMagic2 = pMagic 'refCount = 3

' Release the interface pointer Set pMagic2 = Nothing 'refCount = 2

' Release the interface Set pMagic = Nothing 'refCount = 1

' Now reuse the pUnk variable - what will VB do for this? Set pUnk = New SimpleObject 'refCount = , then 0, then 1

' Let the interface variable go out of scope and VB to tidy upEnd Sub 'refCount = 0

See Visual Basic Magic sample on the disk for this code. You are encouraged to run the sample and step though the code. This object also uses an ATL C++ project to define the SimpleObject

Page 45: Visual basic

and its interfaces; you are encouraged to look at this code to learn a simple implementation of a C++ ATL object.

Often interfaces have properties that are actually pointers to other interfaces. Visual Basic allows you to access these properties in a shorthand fashion by chaining interfaces together. For instance, assume that you have a pointer to the IFoo interface, and that interface has a property called Gak that is an IGak interface with the method DoSomething(). You have a choice on how to access the DoSomething method. The first method is the long-handed way.

Dim pGak as IGak Set pGak = pFoo 'Assign IGak interface to local variable pGak.DoSomething 'Call method on IGak interface

Alternatively, you can chain the interfaces and accomplish the same thing on one line of code.

pFoo.Gak.DoSomething 'Call method on IGak interface

When looking at the sample code, you will see both methods. Normally the former method is used on the simpler samples, as it explicitly tells you what interfaces are being worked with. More complex samples use the shorthand method.

This technique of chaining interfaces together can always be used to get the value of a property, but it cannot always be used to set the value of a property. Interface chaining can only be used to set a property, if all the interfaces in the chain are set by reference. For instance, the code below would execute successfully.

Dim pMxDoc As ImxDocument Set pMxDoc = ThisDocument pMxDoc.FocusMap.Layers(0).Name = "Foo"

The above example works because both the Layer of the Map and the Map of the document are returned by reference. The lines of code below would not work since the Extent envelope is set by value on the active view.

pMxDoc.ActiveView.Extent.Width = 32

The reason that this does not work is that the VBVM expands the Inter-face chain in order to get the end property. Because an interface in the chain is dealt with by value, the VBVM has its own copy of the variable, not the one chained. To set the Width property of the extent envelope in the above example, the VBVM must write code similar to this:

Dim pActiveView as IActiveView Set pActiveView = pMxDoc.ActiveView

Dim pEnv as IEnvelope Set pEnv = pActiveView.Extent ' This is a get by value,

pEnv.Width = 32 ' The VBVM has set its copy of the Extent and not ' the copy inside the ActiveView

Page 46: Visual basic

For this to work the VBVM requires the extra line below.

pActiveView.Extent = pEnv ' This is a set by value,

Accessing ArcObjects

You will now see some specific uses of the create instance and query interface operations that involve ArcObjects. To use an ArcGIS object in Visual Basic or VBA, you must first reference the ESRI object library. In a standalone Visual Basic application, always reference esriCore.olb. Inside of ArcMap or ArcCatalog, a reference is automatically made to the esriMx.olb and esriGx.olb libraries when you start the application, so no external referencing to esriCore.olb is required.

You will start by identifying a simple object and an interface that it supports. In this case, you will use a Point object and the IPoint interface. One way to set the coordinates of the point is to invoke the PutCoords method on the IPoint interface and pass in the coordinate values.

Dim pPt As IPoint Set pPt = New Point pPt.PutCoords 100, 100

The first line of this simple code fragment illustrates the use of a variable to hold a reference to the interface that the object supports. The line reads the IID for the IPoint interface from the ESRI object library.

IID is short for Interface Identifier, a GUID.

You may find it less ambiguous (as per the coding guidelines), particularly if you reference other object libraries in the same project to precede the interface name with the library name, for example:

Dim pPt As esriCore.IPoint

That way, if there happens to be another IPoint referenced in your project, there won't be any ambiguity as to which one you are referring to.

The second line of the fragment creates an instance of the object or coclass, then performs a QI operation for the IPoint interface that it assigns to pPt.

A QI is required since the default interface of the object is IUnknown. Since the pPt variable was declared as type IPoint, the default IUnknown interface was QI'd for the IPoint interface.

Coclass is an abbreviation of component object class.

With a name for the coclass as common as Point, you may want to precede the coclass name with the library name, for example:

Set pPt = New esriCore.Point

Page 47: Visual basic

The last line of the code fragment invokes the PutCoords method. If a method can't be located on the interface, an error will be shown at compile time.

This is the compilation error message shown when a method or property is not found on an interface.

Working With HRESULTs

So far you have seen that all COM methods signify success or failure via an HRESULT that is returned from the method; no exceptions are raised outside of the interface. You have also learned that Visual Basic raises exceptions when errors are encountered. In Visual Basic, HRESULTs are never returned from method calls, and to confuse you further when errors do occur Visual Basic throws an exception. How can this be? The answer lies with the Visual Basic Virtual Machine. It is the VBVM that receives the HRESULT; if this is anything other than S_OK, the VBVM throws the exception. If it was able to retrieve any worthwhile error information from the COM error object, it populates the Visual Basic Err object with that information. In this way, the VBVM handles all HRESULTs returned from the client.

When implementing interfaces in Visual Basic, it is good coding practice to raise an HRESULT error to inform the caller that an error has occurred. Normally this is done when a method has not been implemented.

' Defined in Module Const E_NOTIMPL = &H80004001 'Constant that represents HRESULT

'Added to an method not implemented On Error GoTo 0 Err.Raise E_NOTIMPL

You must also write code to handle the possibility that an HRESULT other than S_OK is returned. When this happens, an error handler should be called and the error dealt with. This may mean simply telling the user, or perhaps it may mean automatically dealing with the error and continuing with the function. The choice depends on the circumstances. Below is a very simple error handler that will catch any error that occurs within the function and report them to the user. Note the use of the Err object to provide the user with some description of the error.

Private Sub Test() On Error GoTo ErrorHandler ' Do something here Exit Sub ' Must exit sub here before error handler

Page 48: Visual basic

ErrorHandler: Msgbox "Error In Application – Description " & Err.DescriptionEnd Sub

Working with properties

Some properties refer to specific interfaces in the ESRI object library, and other properties have values that are standard data types, such as strings, numeric expressions, Boolean values, and so forth. For interface references, declare an interface variable and use the Set statement to assign the interface reference to the property. For other values, declare a variable with an explicit data type or use Visual Basic's Variant data type. Then, use a simple assignment statement to assign the value to the variable.

Properties that are interfaces can either be set by reference or set by value. Properties that are set by value do not require the Set statement.

Dim pEnv As IEnvelope Set pEnv = pActiveView.Extent 'Get extent property of view pEnv.Expand 0.5, 0.5, True 'Shrink envelope pActiveView.Extent = pEnv 'Set By Value extent back on IActiveView

Dim pFeatureLayer as IfeatureLayer Set pFeatureLayer = New FeatureLayer 'Create New Layer Set pFeatureLayer.FeatureClass = pClass 'Set ByRef a class into layer

As you might expect, some properties are read-only, others are write-only, and still others are read/write. All the object browsers and the ArcObjects Component Help (found in the ArcObjects Developer Help system) provide this information. If you attempt to use a property and either forget or misuse the Set key word, Visual Basic will fail the compilation of the source code with method or data member not found error message. This error may seem strange since it may be given for trying to assign a value to a read-only property. The reason for the message is that Visual Basic is attempting to find a method in the type library that maps to the property name. In the above examples, the underlying method calls in the type library are put_Extent and putref_FeatureClass.

Working with methods

Methods perform some action and may or may not return a value. In some instances, a method returns a value that's an interface, for example, in the code fragment below, EditSelection returns an enumerated feature interface:

Dim pApp As IApplication Dim pEditor As IEditor Dim pEnumFeat As IEnumFeature 'Holds the selection Dim pID As New UID 'Get a handle to the Editor extension pID = "esriCore.Editor" Set pApp = Application Set pEditor = pApp.FindExtensionByCLSID(pID) 'Get the selection

Page 49: Visual basic

Set pEnumFeat = pEditor.EditSelection

In other instances, a method returns a Boolean value that reflects the success of an operation or writes data to a parameter; for example, the DoModalOpen method of GxDialog returns a value of True if a selection occurs and writes the selection to an IEnumGxObject parameter.

Be careful not to confuse the idea of a Visual Basic return value from a method call with the idea that all COM methods must return an HRESULT. The VBVM is able to read type library information and setup the return value of the VB method call to be the appropriate parameter of the COM method.

Working with events

Events let you know when something has occurred. You can add code to respond to an event. For example, a command button has a Click event. You add code to perform some action when the user clicks the control. You can also add events that certain objects generate. VBA and Visual Basic let you declare a variable with the keyword WithEvents. WithEvents tells the development environment that the object variable will be used to respond to the object's events. This is sometimes referred to as an "event sink." The declaration must be made in a class module or a form. Here's how you declare a variable and expose the events of an object in the Declarations section:

Private WithEvents m_pViewEvents as Map

Visual Basic only supports one outbound interface (marked as the default outbound interface in the IDL) per coclass. To get around this limitation, the coclasses that implement more than one outbound interface have an associated dummy coclass that allows access to the secondary outbound interface. These coclasses have the same name as the outbound interface they contain, minus the I.

Private WithEvents m_pMapEvents as MapEvents

Once you've declared the variable, search for its name in the Object combo box at the top left of the Code window. Then, inspect the list of events you can attach code to in the Procedure/Events combo box at the top right of the Code window.

Not all procedures of the outbound event interface need to be stubbed out, as Visual Basic will stub out any unimplemented methods. This is different from inbound interfaces, where all methods must be stubbed out for compilation to occur.

Before the methods are called, the hookup between the event source and sink must be made. This is done by setting the variable that represents the sink to the event source.

Set m_pMapEvents = pMxDoc.FocusMap

Page 50: Visual basic

Pointers to valid objects as parameters

Some ArcGIS methods expect interfaces for some of their parameters. The interface pointers passed can point to an instanced object before the method call or after the method call is completed.

For example, if you have a polygon (pPolygon) whose center point you want to find, you can write code like this:

Dim pArea As IArea Dim pPt As IPoint Set pArea = pPolygon ' QI for IArea on pPolygon Set pPt = pArea.Center

You don't need to create pPt because the Center method creates a Point object for you and passes back a reference to the object via its IPoint interface. Only methods that use client-side storage require you to create the object prior to the method call.

Passing data between modules

When passing data between modules it is best to use accessor and mutator functions that manipulate some private member variable. This provides data encapsulation, which is a fundamental technique in object-oriented programming. Public variables should never be used.

For instance, you might have decided that a variable has a valid range of 1–100. If you were to allow other developers direct access to that variable, they could set the value to an illegal value. The only way of coping with these illegal values is to check them before they get used. This is both error prone and tiresome to program. The technique of declaring all variables private member variables of the class, and providing accessor and mutator functions for manipulating these variables, will solve this problem.

In the example below, these properties are added to the default interface of the class. Notice the technique used to raise an error to the client.

Private m_lPercentage As Long

Public Property Get Percentage() As Long Percentage = m_lPercentageEnd Property

Public Property Let Percentage(ByVal lNewValue As Long) If (lNewValue >= 0) And (lNewValue <= 100) Then m_lPercentage = lNewValue Else Err.Raise vbObjectError + 29566, "MyProj.MyObject", _ "Invalid Percentage Value. Valid values (0 -> 100)" End IfEnd Property

Page 51: Visual basic

When you write code to pass an object reference from one form, class, or module to another, for example:

Private Property Set PointCoord(ByRef pPt As IPoint) Set m_pPoint = pPt End Property

Your code passes a pointer to an instance of the IPoint interface. This means that you are only passing the reference to the interface, not the interface itself; if you add the ByVal keyword (as follows), the interface is passed by value.

Private Property Let PointCoord(ByVal pPt As IPoint) Set m_pPoint = pPt End Property

In both of these cases the object pointed to by the interfaces is always passed by reference. In order to pass the object by value, a clone of the object must be made and that is passed.

Using the TypeOf keyword

To check whether an object supports an interface, you can use Visual Basic's TypeOf keyword. For example, given an item selected in ArcMap's table of contents, you can test whether it is a FeatureLayer using the following code:

Dim pDoc As IMxDocument Dim pUnk As IUnknown Dim pFeatLyr As IGeoFeatureLayer Set pDoc = ThisDocument Set pUnk = pDoc.SelectedItem If TypeOf pUnk Is IGeoFeatureLayer Then ' can we QI for IGeoFeatureLayer? Set pFeatLyr = pUnk ' actually QI happens here ' Do something with pFeatLyr End If

Using the Is operator

If your code requires you to compare two interface reference variables, you can use the Is operator. Typically, you can use the Is operator in the following circumstances.

To check if you have a valid interface.

Dim pPt As IPoint Set pPt = New Point If (Not pPt Is Nothing) Then 'a valid pointer? ... ' do something with pPt End If

To check if two interface variables refer to the same actual object, say you've got two interface variables of type IPoint, pPt1 and pPt2. Are they pointing to the same object? If they are, then pPt1 Is pPt2.

Page 52: Visual basic

The Is keyword works with the COM identity of an object. Below is an example that illustrates the use of the Is keyword when finding out if a certain method on an interface returns a copy of or a reference to the same real object.

In the following example, the Extent property on a map (IMap) returns a copy, while the ActiveView property on a document (IMxDocument) always returns a reference to the real object.

Dim pDoc As IMxDocument Dim pEnv1 As IEnvelope, pEnv2 as IEnvelope Dim pActView1 As IActiveView Dim pActView2 as IActiveView Set pDoc = ThisDocument Set pEnv1 = pDoc.ActiveView.Extent Set pEnv2 = pDoc.ActiveView.Extent Set pActView1 = pDoc.ActiveView Set pActView2 = pDoc.ActiveView ' Extent returns a copy, ' so pEnv1 Is pEnv2 returns False Debug.Print pEnv1 Is pEnv2 ' ActiveView returns a reference, ' so pActView1 Is pActView2 Debug.Print pActView1 Is pActView2

Iterating through a collection

In your work with ArcMap and ArcCatalog, you'll discover that in many cases you'll be working with collections. You can iterate through these collections with an enumerator. An enumerator is an interface that provides methods for traversing a list of elements. Enumerator interfaces typically begin with IEnum and have two methods, Next and Reset. Next returns the next element in the set and advanced the internal pointer, and Reset resets the internal pointer to the beginning.

Enumerators can support other methods, but these two methods are common amongst all enumerators.

Here is some VBA code that loops through the selected features (IEnumFeature) in a map. To try the code, add the States sample layer to the map and use the Select tool to select multiple features (drag a rectangle to do this). Add the code to a VBA macro, then execute the macro. The name of each selected state will be printed in the debug window.

Dim pDoc As IMxDocument Dim pEnumFeat As IEnumFeature Dim pFeat As IFeature Set pDoc = ThisDocument Set pEnumFeat = pDoc.FocusMap.FeatureSelection Set pFeat = pEnumFeat.Next Do While (Not pFeat Is Nothing) Debug.Print pFeat.Value(pFeat.Fields.FindField("state_name")) Set pFeat = pEnumFeat.Next LoopSome collection objects, the Visual Basic Collection being one, implement a special interface called _NewEnum. This interface, because of the _ prefix, is hidden, but Visual Basic developers can still use it

Page 53: Visual basic

to simplify iterating though a collection. The Visual Basic For Each construct works with this interface to perform the Reset and Next steps through a collection.

Dim pColn as Collection Set pColn = GetCollection() ' Collection returned from some function Dim thing as Variant ' VB uses methods on _NewEnum to step through For Each thing in pColn ' an enumerator. MsgBox Cstr(thing) Next