Dmc 175745

114
VISUAL PROGRAMMING NOTES 1 ANNA UNIVERSITY CHENNAI UNIT I INTRODUCTION 1.1 INTRODUCTION Windows programming is event driven programming. It uses Hungarian Notation for naming variables. It deals with new data types such as PSTR, HWND etc. PSTR is a pointer to a character string and HWND is a handle to a window. Handle is an address.Device context is introduced using which all drawing are performed. Window messages and resources are introduced in the sections that follow. The need for dynamic link libraries is brought out. The idea of context sensitive help is introduced. Single Document Interface and Multiple Document Interface implications is explained. 1.2 LEARNING OBJECTIVES To define Windows programming To give examples of events To introduce Hungarian Notation To define Device Context To introduce new data types To explain messages To discuss resources To expose document interfaces To explain what is a DLL To introduce SDK programming To introduce Win 32 applications 1.3 WINDOWS PROGRAMMING Windows programming is developing applications using C and the native Win32 application interface (API) or C++ and the class libraries such as Microsoft Foundation Classes (MFC) or Microsoft’s Visual Basic.

description

Dmc 175745

Transcript of Dmc 175745

Page 1: Dmc 175745

VISUAL PROGRAMMING

NOTES

1 ANNA UNIVERSITY CHENNAI

UNIT I

INTRODUCTION

1.1 INTRODUCTION

Windows programming is event driven programming. It uses Hungarian Notationfor naming variables. It deals with new data types such as PSTR, HWND etc. PSTR is apointer to a character string and HWND is a handle to a window. Handle is anaddress.Device context is introduced using which all drawing are performed. Windowmessages and resources are introduced in the sections that follow. The need for dynamiclink libraries is brought out. The idea of context sensitive help is introduced. Single DocumentInterface and Multiple Document Interface implications is explained.

1.2 LEARNING OBJECTIVES

To define Windows programming To give examples of events To introduce Hungarian Notation To define Device Context To introduce new data types To explain messages To discuss resources To expose document interfaces To explain what is a DLL To introduce SDK programming To introduce Win 32 applications

1.3 WINDOWS PROGRAMMING

Windows programming is developing applications using C and the native Win32application interface (API) or C++ and the class libraries such as Microsoft FoundationClasses (MFC) or Microsoft’s Visual Basic.

Page 2: Dmc 175745

DMC 1755

NOTES

2 ANNA UNIVERSITY CHENNAI

1.3.1 Event-Driven Programming

Event-driven programming allows the program to respond to different inputs or events.An action on a graphical component is an event. For example, clicking on a commandbutton is an event. Event-driven programs make use of an event handler and dispatcher.The dispatcher waits for an event to occur and that event calls the event handler.

1.3.2 Hungarian Notation

Hungarian Notation was invented by Charles Simonyi from Microsoft. It is a namingconvention. It is a reminder of the type of a variable. Handles have a ‘h’ prefix (eg hWnd)- this is a shorthand notation for ‘handle_of_Window’. Similarly ‘nLines’ is a short handnotation for ‘number_of_lines’, ‘pData’ is a short hand notation for ‘pointer_to_data’.This notation produces readable code.

1.3.3 Graphics Device Interface - GDI

GDI is a windows API. The GDI uses a set of generic graphics objects to draw to thescreen, to memory and printers. So the programmer need not know anything about thevideo hardware the programmer is using to display graphics.

1.3.4 Device Contexts

Device Context (DC) is represented by the data type HDC (Handle to DeviceContext). An HDC is a handle to something you can draw on; it can be the entire screen,an entire window, the client area of a window, a bitmap stored in memory or a printer. Theclient area is the region where drawing can be done.

1.3.5 Data types

New data types where defined using typedef or #define statements. This was toenable transition from 16 bit to 32 bit system. Some of the new data types areHINSTANCE, PSTR , MSG, UINT, LPARAM, WPARAM, WNDCLASSEX,LRESULT , HDC and HWND. The meaning of the new data types are as follows.

HINSTANCE is an Handle to an instance which is the program itself.PSTR is a pointer to a character string ,ie, char *.HWND is an Handle to a windowMSG is a message structure.UINT is unsigned int.WNDCLASSEX is a window class structure.LRESULT is of type LONG.HDC is Handle to Device Context

Page 3: Dmc 175745

VISUAL PROGRAMMING

NOTES

3 ANNA UNIVERSITY CHENNAI

When Windows was 16 bit WPARAM was a WORD which was a 16 bit unsignedshort integer and LPARAM was LONG which was a 32 bit signed long integer. So onlythe ‘W’ and ‘L’ prefix. In Windows 95 WPARAM is UINT and LPARAM is LONG.Both of them are 32 bit values.

1.4 RESOURCES

Icons, bitmaps, cursors, accelerators, dialog, menu, string table and tool bar are thevarious resources The resources are compiled by a resource compiler. The linker will bindobject (*.obj) files and resource (*.res) files into executable (*.exe) file.

1.4.1 Cursor

Cursor points to some element on the screen. On character-based screens cursoris a blinking rectangle or an underline symbol. On Windows it could be an I-beam or anarrow.

1.4.2 Icon

An icon is a small image which represents a program, file, link to a Web page,picture, or other type of information stored on a computer. Double-clicking on an iconcauses the program, file, Web page or picture to open.

1.4.3 Bitmap

Bitmap is the method of storing information that maps an image pixel, bit by bit. Thebitmapped file formats are .bmp, .pcx, .pict, .pict-2, .tiff, .tif and so on.

1.4.4 Accelerator

Accelerators are short cut keys. It is a key combination such as Alt+F9, Alt+0,Ctrl+A to activate a task.

1.4.5 Toolbars

Toolbars are buttons for activating functions in the application. The floppy symbolis a tool bar for saving. They will be associated with corresponding menu items. A toolbaris a window that contains a row of command buttons. Clicking the button will issue apredefined command. For selecting a menu item you can click a toolbar corresponding tothe menu item. The toolbar buttons are bitmaps and are arranged in a row.

1.5 MESSAGES

Windows-based applications do not make explicit function calls to obtain input. Theywait for the system to pass input to them. The system passes input to the various windowsin the application. Each window has a function, the window procedure, which is called bythe system whenever it has input for the window. The window procedure processes the

Page 4: Dmc 175745

DMC 1755

NOTES

4 ANNA UNIVERSITY CHENNAI

input and returns control to the system. The system passes input to a window procedure inthe form of messages.

Messages are generated by both the system and applications. The system generatesa message for each input event — for example, when the user types, moves the mouse orclicks a control such as a list box. The system also generates messages in response tochanges in the system brought about by an application, such as when an application resizesone of its windows. An application can generate messages to direct its own windows toperform tasks or to communicate with windows in other applications.

When a window procedure receives a message, it uses a message identifier to determinehow to process the message. The message identifier WM_PAINT tells the windowprocedure that the window’s client area has changed and must be repainted. WM is forgeneral window messages.

1.5.1 Message Routing

The system posts messages to a first-in, first-out queue called a message queue or itsends messages directly to a window procedure. Messages posted to a message queueare called queued messages. They are the result of user input entered through the mouse orkeyboard, such as WM_RBUTTONDOWN , WM_KEYUP. Messages, sent directly tothe window procedure are nonqueued messages.

Nonqueued messages are sent immediately to the destination window procedure,bypassing the system message queue and thread message queue. The system sendsnonqueued messages to notify a window of events that affect it. For example, when theuser activates a new application window, the system sends the window WM_ACTIVATE,WM_SETFOCUS and WM_SETCURSOR messages. These messages notify the windowthat it has been activated, that keyboard input is being directed to the window, and that themouse cursor has been moved within the borders of the window. Nonqueued messagesoccur when an application calls certain system functions. For example, the system sendsthe WM_WINDOWPOSCHANGED message after an application uses theSetWindowPos function to move a window.

1.6 DOCUMENT INTERFACES

Single document interface (SDI) and Multiple document interface (MDI) are thedocument interfaces. MDI based applications can have several child windows under oneparent window. In SDI based applications each window is separate.

1.7 DYNAMIC LINK LIBRARY - DLL

DLL are files that can be called when needed by another program that is running inthe computer. DLL files that support specific device operation are known as device

Page 5: Dmc 175745

VISUAL PROGRAMMING

NOTES

5 ANNA UNIVERSITY CHENNAI

drivers.The advantage of DLL files is that, space is saved in RAM since they don’t getloaded into random access memory (RAM) together with the main program. For example,if a user is editing a document using Microsoft Word, the printer DLL file does not need tobe loaded into RAM. When the user decides to print the document, then the Wordapplication causes the printer DLL file to be loaded and run. A DLL file is often given a“.dll” file name suffix. DLL files are dynamically linked with the program that uses themduring program execution rather than being compiled with the main program.

1.8 CONTEXT-SENSITIVE HELP

Context-sensitive help provides online help for the situation that is associated withthat state.Context-sensitive help can be implemented using tooltips which display a completetopic from the help file.

1.9 WINDOWS 32 BIT (WIN 32) APPLICATIONS

Win 32 based applications are the applications developed for the windowsfamily of operating systems. Win 32 applications respond to events. They arecomposed of Win 32 Application Programming Interface (API) which are DLLs. TheWin 32 API is a collection of function calls, data structures and messages. The Win 32API are written in C. The Win 32 based program uses Win 32 API to interact with thewindows based operating system. The Operating System responds to the programs usingthe API as given in Fig 1.1.

Win 32 Based program

| |

| |

Win 32 API

| |

| |

Windows based OS

Figure 1.1 Relationship between Win 32 program and API

Page 6: Dmc 175745

DMC 1755

NOTES

6 ANNA UNIVERSITY CHENNAI

1.10 ARCHITECTURE OF WIN 32 PROGRAM

Figure 1.2 Working of Win 32 Program

The hardware events in Fig 1.2 are the mouse related events such as mouse move,left button down etc or keyboard events such as character press or release. The eventsare stored in the system queue and it is dispatched to the appropriate message queue ofthe application. Every program will have the message loop which will retrieve the eventsfrom the queue and call the window procedure which will contain the handler. If the handleris not incorporated in the application the default window procedure will be called. Thedefault window procedure Default Wnd Proc in Fig 1.2 implements the behaviorssuch as minimizing, restoring or maximizing a window or displaying menu resources.

1.11 SDK PROGRAMMING

SDK programming is developing Win 32 based programs using Win 32 API whichdirectly interact with the hardware. So the execution of SDK programs are fast. A sampleSDK program for displaying a window is given. MSG is a structure. CreateWindow,ShowWindow, UpdateWindow are examples of SDK functions. HWND is a handle tothe window. The created window’s address is stored in hWnd. The first parameter “button”is the class name. The second parameter “hello” is the window name. BS_PUSHBUTTON

Hardware Events | |

| | System Queue | | | |

-------------------------------------------------------------------------- |

| Application Message Queue | Message loop | | | Window Proc

| | Default Wnd Proc

Page 7: Dmc 175745

VISUAL PROGRAMMING

NOTES

7 ANNA UNIVERSITY CHENNAI

is the style. BS stands for button style. The next 4 parameters indicate the size of thewindow. The 8th parameter indicates that the created window has no parent. The nextparameter indicates that there is no menu. ShowWindow displays the window.

#include <windows.h>int WINAPI Winmain(HANDLE hInstance, HANDLE hprevInstance, LPSTRlpszCmdLine, int nCmdshow){HWND hWnd;MSG msg;hWnd=CreateWindow(“button”,”hello”,BS_PUSHBUTTON,10,110,100,100,NULL,NULL,hInstance,NULL);ShowWindow(hWnd, nCmdshow);UpdateWindow(hWnd);while (GetMessage(&msg, hWnd, 0, 0)){

{TranslateMessage(&msg);DispatchMessage(&msg);

}}

return(0);}

1.12 MESSAGE LOOP

The message loop is the code in Win 32 based application. It retrieves messagesfrom the application’s message queue and passes these to the associated windowprocedure. The messages are retrieved in FIFO (First – In, First Out order). The codesnippet above illustrates the message loop. The message received for the window denotedby hWnd is read and stored in the structure msg. The functions TranslateMessage andDispatchMessage are responsible for moving the window by clicking on the title.

SUMMARY

This unit discusses about event driven programming, the various windows resources, the naming convention adopted in windows programming , namely, the Hungarian notation.The new data types are introduced. The device context for drawing has been dealt. Themessages have been introduced and some messages have been explained. Dynamic linklibrary has been covered. A program has been incorporated to illustrate window creation.The message loop is also explained.

Page 8: Dmc 175745

DMC 1755

NOTES

8 ANNA UNIVERSITY CHENNAI

SHORT QUESTIONS

1. What is windows programming?2. What is Win 32 API?3. What is an event?4. What is event driven programming?5. Name any 2 events.6. Name some hardware events.7. Give 2 examples for Hungarian Notation naming convention.8. Name the various Windows resources.9. What are toolbars?10. What are accelerators?11. Name the different kinds of messages.12. Give any 2 instances which lead to message generation.13. Name any 2 nonqueued messages.14. Name any 2 queued messages.15. What are DLLs?16. What are device drivers?17. What is default window procedure?

Answers to short questions

1. Windows programming is developing applications using C and the nativeWin32 application interface (API) or C++ and the class libraries such as MicrosoftFoundation Classes (MFC) or Microsoft’s Visual Basic.

2. The Win 32 API is a collection of function calls, data structures and messages.They are written in C.

3. An action on a graphical component is a event. An example of an event is clickingthe command button.

4. Event-driven programming allows the program to respond to different inputs orevents.

5. a. character press is an event.b. Moving of the mouse.

6. Mouse related events such as mouse move, mouse left button down, key boardevents such as character press are examples of hardware events.

7. ‘nLines’ is short for ‘number_of_lines’.‘pData’ is short for ‘pointer_to_data’

8. The various Windows resources are icons, bitmaps, cursors, accelerators, dialog,menu, string table and tool bar.

9. Toolbars are buttons for activating functions in the application.

Page 9: Dmc 175745

VISUAL PROGRAMMING

NOTES

9 ANNA UNIVERSITY CHENNAI

10. Accelerators are short cut keys. It is a key combination such as Alt+F9 to activatea task.

11. The different kinds of messages areQueued messages andNon queued messages.

12. Messages are generated when user input is entered through the mouse or keyboard.When the user activates a new application window, messages are generated.

13. WM_ACTIVATE, WM_SETFOCUS.14. WM_RBUTTONDOWN , WM_KEYUP.15. Dynamic link library (DLL) are files that are called when needed by another

program that is running. Space is saved in RAM since they don’t get loaded intothe RAM along with the main program.

16. DLL files that support specific device operation are known as device drivers.17. The default window procedure Default Wnd Proc implements behaviors such as

minimizing, restoring, maximizing a window or displaying menu resources.

Page 10: Dmc 175745

DMC 1755

NOTES

10 ANNA UNIVERSITY CHENNAI

Page 11: Dmc 175745

VISUAL PROGRAMMING

NOTES

11 ANNA UNIVERSITY CHENNAI

UNIT II

CONTROLS AND TOOLBARS

2.1 INTRODUCTION

Visual Basic programming is event driven programming. In a form objects calledcontrols are placed. We can set the properties of the controls and associate events withthe control. Accelerators are short cut keys. Tooltips are messages that would be displayedwhen the mouse is positioned on the control. How to associate accelerators and tooltipswith the controls are explained. A project comprising of command buttons and text box ispresented. Some of the events associated with these controls are handled. The usage ofcontrols such as list box and combo box are introduced. The inclusion of menus and toolbars in a project are explained.

The various files, data types, control statements associated with a Visual Basicproject are explained. You can add modules to your project and you can control thestartup object which will be the starting point for execution. These features are incorporatedin this unit.

The concept of control arrays and the various file system controls are explored.

2.2 LEARNING OBJECTIVES

To explain the various intrinsic controls, some of their properties and events. To introduce the default properties of the controls. To introduce events, accelerators and tooltips. To explain how to place controls on the form. To introduce Text, Font, Fontsize properties of Textbox control. To explain the usage of With keyword. To introduce command buttons, caption property and click event. To introduce Listbox control and methods AddItem, Remove Item, ListCount. To introduce Listbox control events such as click, double click. To expose all the files in a Visual Basic project. To introduce different data types in VB.

Page 12: Dmc 175745

DMC 1755

NOTES

12 ANNA UNIVERSITY CHENNAI

To introduce different numeric data types in VB. To introduce fixed length and variable length strings. To introduce variant data type. To introduce different control statements. To learn how to incorporate menus and tool bars in your project. To introduce modules. To change the startup object. To learn about control arrays. To know the file system controls. To introduce MDI form. To use data controls.

2.3 INTRINSIC CONTROLS

Intrinsic controls are the built-in controls. Some of the controls are Check box, Combobox, Command Button, Label etc. The controls have properties associated with them.The Caption, Tool tip text, Tab stop, Tab index, Mouse pointer, Font are some of theproperties associated with controls.

2.3.1 Properties

Every control has a default property associated with it. The default property need notbe named when you are working. The control Check box as value has the defaultproperty. The control Combo box as text has the default property. The control image aspicture has the default property. The control label as caption has the default property.The control menu as enabled has the default property. Read only properties cannot bechanged programmatically. They can be set only at design time. For instance name of acontrol is read only property. For changing the read only property edit the property window.For instance type “add” for name property of the command button in the propertywindow. As a result in the drop down list of the property window the control will be listedas add Command Button. For changing the caption of a label control, set the captionproperty using control name.property; test is made as the caption of the control, label,represented by label1. The statement is given below.

Label1.Caption = “test”

2.3.2 Events

Controls are placed on a form and then to make them functional an “event procedure”is associated with the control object. An event procedure is what happens in response toa user action such as a “mouse click” or a “key press”.

Page 13: Dmc 175745

VISUAL PROGRAMMING

NOTES

13 ANNA UNIVERSITY CHENNAI

2.3.3. Accelerators

Accelerators are short cut keys. Accelerators are created by placing an ampersandbefore any of the characters of the Caption. As a result the letter following the ampersandwill be underlined. The underlined letter along with the ALT key should be used to activatethe Control. Pressing the ALT key and the corresponding letter key is equivalent to clickingthe control with the mouse.

For instance if the caption is Command2 for the second command button, placing‘&’ before C in the caption as given &Command2, would display the caption asCommand2. To activate the Command2 button you either click on the Command2 buttonor press ALT and C together.

2.3.4 ToolTip

The ToolTip property is used to flash a message about a control object when themouse pointer moves over that object for a couple of seconds. Select a control and clickF4 key to navigate to the property window of that control. To set tooltip move down toToolTips property and double click in the space to the right of ToolTips property. Thentype the message without quotation marks. Execute your program by using F5(short cutmethod) or use the Run option in the menu. Place the mouse over the control for which youhave set the tooltip and the tooltip message would be flashed. Tooltips are used to indicatefor what purpose the control is used.

2.4 PROJECT TO DISPLAY DISTANCE MCA

2.4.1 Controls used

The various controls used in this project are as follows.Text Box to display Distance MCA.Command Button to display hello.Command Button to clear the Text Box.Command Button to exit the project.

2.4.2 Creating the project

1. Open Visual Basic 6.0.2. Choose a Standard .exe project.3. Maximize the form by clicking on the middle maximize button.4. Choose View option and click project explorer.5. Click on the project name to select it.6. Right click and choose properties.7. Type the project name you want.

Page 14: Dmc 175745

DMC 1755

NOTES

14 ANNA UNIVERSITY CHENNAI

2.4.3 Placing the text box on the form

1. Select the text box control inside the tool box to the left of the work area.2. Double-clicking on the text box places the text box onto the form.3. Size the text box control using the resizing handles.4. Drag the control to place it on the form using the left mouse button.5. Clear the contents of the text box(Text1) by selecting the contents of the text box

and press the delete key.6. Type in the contents as Distance MCA for the text box control.

2.4.4 Placing the command buttons on the form

1. Place the 3 command buttons on the form.2. Set the caption for the first command button as &hello.3. Set the caption for the second command button as &clear.4. Set the caption for the third command button as &exit.5. Add events to the controls (command buttons).6. The coding should be done in the code window.

2.4.5 Adding Events

Double click on the command button with caption hello.

Private Sub command1_Click()and End Sub would beinserted. Type your coding within this construct.

Text1.Text = “Hello”Private Sub command1_Click()

Text1.Text = “Hello”With Text1

Font=”Times New Roman”.FontSize = 24

End WithEnd Sub

The With command associates the properties that follow with the control. (in this caseText1).It is equivalent to writing Text1.Font, Text1.FontSize.

Double click on the command button with caption clear.

Type the following code.Private Sub command2_Click()

Text1.Text = “ “End Sub

Page 15: Dmc 175745

VISUAL PROGRAMMING

NOTES

15 ANNA UNIVERSITY CHENNAI

Double click on the command button with caption exit.Type the following code.

Private Sub command3_Click()endEnd Sub

This project has created the form in Fig 2.1 with a textbox and 3 command buttons.The buttons have been associated with click events.

Figure 2.1 A Form with Command Buttons, Text Box and Accelator

2.4.6 Including List Box control in your project

A list box is used for presenting the users with data. You can choose the data from thelist box for data entry. No editing is possible in a list box. If you want to edit you should usea combo box control.

2.4.6.1 A Project To Illustrate The Use of List Box

Start a new Project by choosing File and then New ProjectLet the project type be Standard EXEAdd a list box and text box to the formDouble click on the form. Add the coding given below

Private Sub Form_Load()List1.AddItem “a”List1.AddItem “b”List1.AddItem “c”

Page 16: Dmc 175745

DMC 1755

NOTES

16 ANNA UNIVERSITY CHENNAI

List1.AddItem “d”

End Sub

This will create a list box as given in Fig 2.2 with contents a,b,c and d.

5. Associate the click event with the list boxPrivate Sub List1_Click()Text1.Text = List1.TextEnd Sub

When you click on an item in the list box, the contents will be transferred to the textbox.

Figure 2.2 A Form with List Box control2.4.6.2 A Project To Illustrate The Use of Combo Box

1. Start a new Project by choosing File and then New ProjectLet the project type be Standard EXEAdd a combo box and text box to the form as in Fig 2.3Initialize the combo box as follows

Private Sub Form_Load()Combo1.AddItem “apple”Combo1.AddItem “orange”Combo1.AddItem “grapes”End Sub

Page 17: Dmc 175745

VISUAL PROGRAMMING

NOTES

17 ANNA UNIVERSITY CHENNAI

2 Handle click event for the combo boxPrivate Sub Combo1_Click()Text1.Text = Combo1.TextEnd Sub

Figure 2.3 A Form with Combo Box Control

The above code initializes the text box with the selected item from the combo box.

2.5 FILES IN A VB PROJECT

The project file has the extension .vbp. The form in which we draw has the extension.frm; .mod represents the module file; .cls represents the class file; .res represents theresource file; .exe represents the executable file. If only one form is associated with aproject it is a SDI project.

2.6 DATA TYPES

The various primitive data types are Boolean, Byte, Char, Date, Decimal, Double,Integer, Long, Sbyte, Short, Single, String, Uinteger, Ulong and Ushort. To declare variablesthe DIM statement is used. For instance to say a variable sum is of integer type, either ofthe following statements can be used.

Dim sum As IntegerDim sum%

The general syntax for declaring a variable is Dim (keyword) followed by variablename (user defined) followed by As (keyword) followed by datatype which is again akeyword. Table 2.1 gives an idea of the other data types.

Page 18: Dmc 175745

DMC 1755

NOTES

18 ANNA UNIVERSITY CHENNAI

Dim is Used for declaring variables in procedures. Each time the procedure is called, thedata stored in the variables declared with this keyword are reset (eg. an Integer data typewill be reset to zero). Static is used to declare variables in procedures. Each time theprocedure is called, the data stored in static variables are retained.

Public is Used to declare variables within a module. The variable is available to allprocedures in the project

Private is Used to declare variables within a module. The variable is only available toprocedures within the project.

ReDim: The ReDim keyword is used to re-dimension an array.Table 2.1 The various data types in visual basic

Data Type Example Description

Byte Dim tn As Byte

It stores an integer in the range 0 to 255 (8 bits).

Boolean Dim As Boolean

It stores a value that is either True or False.

Integer Dim As Integer

It stores an integer (whole number) in the range -32768 to + 32767 (16 bits). In VB.Net, the Integer data type is 32 bits. A new data type, "Short", has been introduced to represent 16-bit numbers.

Long Diml As Integer

It stores an integer in the range -2,147,483,648 to +2,147,483,647 (32 bits). In VB.Net, the Long data type is 64 bits.

Currency Dim As Currency

It stores a real number in the range -922,337,203,685,477.5808 to +922,337,203,685,477.5807.

Single Dimg As Single

It stores a single-precision floating point number, accurate to 8 significant digits (32 bits).

Double DimA As Double

It stores a double-precision floating point number, accurate to 16 significant digits (64 bits).

Date Dim to As Date

It stores a Date.

String Dims As String

It stores a sequence of up to 63,000 characters.

Variant Dimu As Variant

The data type will change depending on what value is assigned to the variable. If no data type is specified, this is the data type that will be used. In VB.Net, the Variant data type is no longer supported, and should be replaced by the "Object" data type.

Page 19: Dmc 175745

VISUAL PROGRAMMING

NOTES

19 ANNA UNIVERSITY CHENNAI

2.6.1 Option Explicit Declaration

If option explicit is used necessarily all variables will have to be declared. Otherwiseerror will be reported saying that the variable is not declared. The option explicit declarationis found under Tools, options, editor option. Declaring variables gives readability and alsothe code executes faster.

2.6.2 Numeric data types

Integer, long integer are used for whole numbers. Single and double are associatedwith floating point numbers. Currency is associated with numbers dealing with money. Thecode below illustrates the five different numeric data types and their effect. Integer canstore upto 32767 only. Trying to store a value beyond 32767 will result in overflow error.

Variable a is of type Single. When 8.97655467787088 is stored in a, the actualvalue stored would be 8.976555 only. When the data type is Single and the value stored is100000000 it would be displayed as 1E+08 using Scientific notation. When the data typeis Currency and the value stored is 100000000 it would be displayed as 100000000.These are the 5 different numeric data types available in VB.

2.6.3 Strings

2.6.3.1 Variable Length Strings

Strings can be declared using As or $ as given in the code below; msg and msg1 are2 strings and they are assigned values using ‘=’. The value of msg string is displayedfollowed by space followed by msg1 contents. The output would be distance mca.

Private Sub Command1_Click()Dim msg As StringDim msg1$msg = “distance”msg1 = “mca”Form1.Print msg$ & “ “ & msg1$End Sub

2.6.3.2 Fixed length strings

Fixed length strings are declared by specifying the size of the string. For instance togive a length of 20 for the string place, the following declaration would be used.

Dim place as String * 20

Private Sub Command1_KeyDown(KeyCode As Integer, Shift As Integer)

Dim m As String * 20

Page 20: Dmc 175745

DMC 1755

NOTES

20 ANNA UNIVERSITY CHENNAI

m$ = “chennai is the capital of tamilnadu”

Form1.Print m$

When any key is pressed during execution, a fixed length string m of size 20 is created.The string “chennai is the capital of tamilnadu” is assigned to m. When you print the stringm the output would be as “chennai is the capit”. Only 20 characters including the spacein between is displayed.

2.6.4 Variant Type

If no data type is associated with VB variables, it takes the default variant type. Thevariable x will be of variant type when the following two declarations are used.

Dim xDim x as Variant

A variant type can take numeric, string, date, null or Boolean values.

Private Sub Form_MouseDown(Button As Integer, Shift As Integer, X As Single, Y AsSingle)

Dim i As IntegerDim j As LongDim a As SingleDim b As DoubleDim c As SingleDim c1 As Currency

i = 32767 ‘ range is upto 32767 beyond that overflow occursj = 97400Form1.Print “integer i is”; iForm1.Print “long j is”; ja = 8.97655467787088 ‘8.976555b = 0.876554677870879c = 100000000 ‘1E+08c1 = 100000000Form1.Print “single a is”; aForm1.Print “double b is”; bForm1.Print “single c is”; cForm1.Print “currency c1 is”; c1End Sub

Page 21: Dmc 175745

VISUAL PROGRAMMING

NOTES

21 ANNA UNIVERSITY CHENNAI

2.7 CONTROL STATEMENTS

A conditional expression uses a comparison operator which results in true or falsevalue. If the comparision is valid it results in true, other wise it results in false. Here’s asimple conditional expression:

Price < 100

If the Price variable contains a value that is less than 100, the expression evaluates toTrue. If Price contains a value that is greater than or equal to 100, it evaluates to False.You can use the comparison operators given below to create conditional expressions:

Comparison Operators

= Equal to

< > Not equal to

> Greater than

< Less than

> = Greater than or equal to

< = Less than or equal to

Select case, If then Else, For .. Next repetition statement, Do While loop statementand Do Until loop control statements are explained.

2.7.1 Select Case

Select Case is used for handling multiple paths. Select Case evaluates the expressionand depending on the value the corresponding Case statement executes.

Select Case expression

   Case value1

        Block of one or more VB statements

   Case value2

        Block of one or more VB Statements

   Case value3

        Block of one or more VB statements

   Case value4       .

   Case Else

Page 22: Dmc 175745

DMC 1755

NOTES

22 ANNA UNIVERSITY CHENNAI

        Block of one or more VB Statements

End Select

A function WeekDay(Now) is used which reads the day, date and time from thecomputer to illustrate the use of select case.

2.7.2 Aim

To display what is the day when the second command button is clicked and to clearthe screen when the first command button is clicked. The working of this program is givenin Fig 2.4.

1. Handle click event for the first command button.2. Handle click event for the second command button.3. The Cls method clears the form.4. Type the following coding in the first command button event handler.

Private Sub Command1_Click()Form2.ClsEnd Sub

5. Type the following coding in the second command button event handler.Private Sub Command2_Click()Select Case Weekday(Now)Case vbSunday

Form2.Print “sunday”Case vbMonday

Form2.Print “Monday”Case vbTuesday

Form2.Print “Tuesday”Case vbWednesday

Form2.Print “Wednesday”Case vbThursday

Form2.Print “Thursday”

Case vbFridayForm2.Print “Friday”

Case vbSaturdayForm2.Print “Saturday”

Page 23: Dmc 175745

VISUAL PROGRAMMING

NOTES

23 ANNA UNIVERSITY CHENNAI

End SelectEnd Sub

Figure 2.4 The Resultant of clicking the command button and caption week day

The function Weekday(Now) returns the current day. If the day is Sunday vbSundaywould be returned. Therefore the corresponding block would execute. So Sunday wouldbe displayed on the screen. Select Case and End Select represents the block.

2.7.3 If Then Else

The control statement If Then Else is used for evaluating a condition and taking actionbased on the condition. If the condition is true the then part will execute otherwise the elseblock will execute.

If .. Then…Else

If  condition Then

Block of VB Statements

Else

Page 24: Dmc 175745

DMC 1755

NOTES

24 ANNA UNIVERSITY CHENNAI

Block of VB Statements

End If

To use If then Else construct you can place a button and text box on the form as givenin Fig 2.5. Run the project and enter value in the text box. Then click the button. The eventhandler given below executes and if the value entered exceeds 50 it displays pass, otherwiseit displays fail.

Private Sub Command1_Click()

If Val(Text1.Text) > 50 Then

Form1.Print “pass”

Else

Form1.Print “fail”

End If

End Sub

Figure 2.5 Illustration of If then Else

2.7.4 For ..... Next Repetition Statement

To illustrate the working of for .. next control statement, place a command button anda label control on the form. Handle click event for the command button. Type the codinggiven below as the event handler.

Page 25: Dmc 175745

VISUAL PROGRAMMING

NOTES

25 ANNA UNIVERSITY CHENNAI

Private Sub Command1_Click()

Label1.Caption = “for loop illustration”

For i = 1 To 10

Form1.Print “ the value of i is”; i

Next

End Sub

Label control cannot be navigated. When you press the tab key during execution, theorder in which the controls will be visited will be highlighted for every tab press. This isknown as the tab order. Label control will not have a tab order. Mainly Label control isused for displaying heading. You set the caption property of the label control. Duringexecution the caption will be displayed on the form where the label control is placed. Thegeneral syntax of for loop is as follows.

For index = start value to end value (Step value)

    One or more VB statements

Next

The for loop uses a index, namely “i”, in this illustration. The index is assigned thestarting value, namely 1 as given. The keyword “To” tells the range of values the index cantake. The integer following “to” is the final value, which is 10 in this example. So, i, will startwith 1 and increase by 1 till it reaches 10. For each value of i, the statements between forand next would be executed.

When the button is clicked “for loop illustration” will be displayed in the placewhere label control was placed. Also the following output would be displayed on thescreen as given in Fig 2.6

the value of i is 1

the value of i is 2

the value of i is 3

....

the value of i is 10

Page 26: Dmc 175745

DMC 1755

NOTES

26 ANNA UNIVERSITY CHENNAI

Figure 2.6 Illustration of for next control statement

2.7.4.1 Specifying the Step Value

For i = 10 To 1 Step –1

In the earlier for statement Step was not explicitly stated. When it is not explicitlystated it is taken as 1 by default. In the above statement Step is specified as –1. So thevalue will be decremented by 1 for every iteration. The index starts with 10 and isdecremented by 1 for every iteration until it reaches 1. The Step can be any integer.

2.7.5 Do While Loop Statement

The statements within the do…while loop block executes till the condition given inwhile is true.

The working of do…loop is explained with the event Form_MouseDown in Fig 2.7. Whenyou click the mouse on the form, the event handler executes and produces the output asgiven in fig 2.7.

Private Sub Form_MouseDown(Button As Integer, Shift As Integer, X As Single, YAs Single)

Dim i As Integeri = 5

Do While i > 0Form1.Print “i is “ & ii = i - 1

LoopEnd Sub

Page 27: Dmc 175745

VISUAL PROGRAMMING

NOTES

27 ANNA UNIVERSITY CHENNAI

Figure 2.7 Working of do while loop

2.7.6 Do Until Loop Statement

The statements within the do…until loop block executes till the condition given in untilbecomes true. The working of do…until loop is explained with the event Form_ MouseDown.

   Do Until condition

              Block of one or more VB statements

       Loop

When you click the mouse on the form, the event handler executes and produces theoutput as given in Fig 2.8.

Private Sub Form_MouseDown(Button As Integer, Shift As Integer, X As Single, YAs Single)

Dim i As Integeri = 5

Do Until i = 0Form1.Print “i is “ & ii = i - 1

LoopEnd Sub

Page 28: Dmc 175745

DMC 1755

NOTES

28 ANNA UNIVERSITY CHENNAI

Figure 2.8 Do until loop

2.8. MENUS AND TOOL BARS

Menu options can be enabled, disabled, checked and popped up on an object.

2.8.1 The Menu Object

Menu control is used to create a menu in Visual Basic. It has several properties andonly an event. It has no methods. A menu has titles (such as Project). Each title containsmenu items ( for eg Add Form). A separator can be used to group related items within onemenu. The menu editor is used for creating the menu.

2.8.2 The Menu Editor

Select Tools and then Select Menu Editor to open the menu editor. The menu editorwill display the properties as given in Fig 2.9. The important properties are caption, checked,enabled, Name, shortcut and visible. Click on the form to make it the active form. Onlythen, the menu editor will be enabled. Otherwise it will be grayed and it cannot be selected.

2.8.2.1 The Caption Property

The Caption Property is the title name or the item’s name. The text we type as captionbecomes the title or item under the title. You can place an & before any character of thecaption. That character will be the accelerator for that item.

Page 29: Dmc 175745

VISUAL PROGRAMMING

NOTES

29 ANNA UNIVERSITY CHENNAI

2.8.2.2 The Checked Property

The Checked Property will place a check mark next to the menu item. Title’s cannotbe checked. The check mark can be toggled. The checked property can be set to on oroff during run time.

2.8.2.3 The Enabled Property

This property when set to FALSE will disable the menu item. At run time you canenable the property.

2.8.3 A Project To Illustrate Creation of The Menu1. Start a new project by choosing file and then new project2. Choose Standard EXE as the Project type3. Make the Form1 active by clicking on it.4. Select Tools and then Menu Editor to open the menu editor for designing.5. Give the caption as &display (display becomes the menu title)6. Type a name . Let it be Mnudisp. This is user defined.7. To add menu items click the next button in the menu editor8. Give the caption as &square (square becomes the menu item)9. Type a name . Let it be mnusquare. This is user defined.10. Associate a short cut key. A list box will pop up. Choose a key. Say you have

selected Ctrl + G. Than, to activate this menu item you need to press CTRL and Gkeys together.

11. Set the checked property of the menu item square by clicking on the check boxfor the checked property.

12. Double click on the menu item. It takes you to the code window.13. Type the code given below for the menu item square

Private Sub mnusquare_Click()If (Form1.mnusquare.Checked) = False Then Form1.mnusquare.Checked = True Else Form1.mnusquare.Checked = False End IfEnd Sub

14. When you click on square menu item for the first time, the property Checked is setto TRUE. So the else part executes and sets the property Checked to FALSE.The control behaves as a toggle.

Page 30: Dmc 175745

DMC 1755

NOTES

30 ANNA UNIVERSITY CHENNAI

15. To address the controls on the form use the form name (Form1 in this case). Themenu item we want to manipulate is mnusquare (mnusquare is the name weassociated with the menu item during design time). So to access the control wesay Form1.mnusquare. Next we want to manipulate Checked property. So weare qualifying it as Form1.mnusquare.Checked

16. Choose Run option17. Choose Start With Full Compile18. The form will be displayed19. Click on disp menu title20. The sub menu pops up. You have square as the menu item. Notice the check

mark as given in Fig 2.1021. If you click on the menu item square the check mark will disappear during next

execution22. Clicking again will bring the check mark

Figure 2.9 The Menu Editor

Page 31: Dmc 175745

VISUAL PROGRAMMING

NOTES

31 ANNA UNIVERSITY CHENNAI

Figure 2.10 Menu Item Square

2.8.4 Associating Toolbars for the menu

1. Add the tool bar control to your form2. Follow the steps to add the tool bar control to your form3. Right Click on the tool box4. 4.A pop up menu will be displayed5. Choose Components menu item6. The Components Dialog Box will appear7. Check Microsoft Windows Common Controls 5.0 (SP2)8. Click ok9. Steps 3 to 8 includes the tool bar control in the tool box10. Add the tool bar control to your form by clicking on it.11. The default name of the tool bar control would be Toolbar112. Set the align property.13. By default it would be 1- vbAlignTop14. Select the Custom properties of the toolbar object by Clicking15. The Property Pages Dialog box would appear.16. Choose the Buttons tab page17. Click Insert Button. This would place the first button on the tool bar.

Page 32: Dmc 175745

DMC 1755

NOTES

32 ANNA UNIVERSITY CHENNAI

18. Set the Style as 3-tbrSeparator from the drop down box.19. Click insert button to add a new button. Set the Key to menu item (in this case

square)20. You can specify the tool tip. (set it as draw)21. Repeat Steps 17 to 20 to add buttons for the menu items or titles . Only the first

button will be a separator. The rest can have the value 0-tbrDefault

2.8.4.1 Associating Images to Toolbars

1. Add a Imagelist to your form from the tool box2. Choose the custom property of the image list3. Click the images tab4. Choose Insert Picture5. Select an image and say ok6. Associate images with all the buttons7. Select the tool bar object8. Select the customs property9. Choose the general tab page.10. Set the image list with what you have created. It would be ImageList1 if you didn’t

change the name.11. Choose the buttons tab page.12. Set the index property to 2 and set the image property to 1.13. After you associate tool bar with the images click ok.14. Next you need to add handlers for the tool bar.15. Double click on the tool bar16. The following handler will be inserted

Private Sub Toolbar1_ButtonClick(ByVal Button As ComctlLib.Button)Select Case Button.KeyCase Is = “square”MsgBox “sqhello”Case Is = “disp”MsgBox “disphello”End SelectEnd Sub

Page 33: Dmc 175745

VISUAL PROGRAMMING

NOTES

33 ANNA UNIVERSITY CHENNAI

Figure 2.10 Toolbars

When you run the project you can click the tool bar in Fig 2.10 or the menu item ortitle to get the result.

When using the menu editor if all the items are on the same indentation they will bethe menu titles. To create menu items you indent them with the arrow keys.

2.8.4.2 Check Box

A check box control takes the value as on or off or grayed. A grayed one is neitheron or off. The user can change the setting of the grayed check box.

Page 34: Dmc 175745

DMC 1755

NOTES

34 ANNA UNIVERSITY CHENNAI

2.8.4.3 Develop a Project to illustrate the use of check Box

1. Select General in the objects drop down list box andDeclarations in the events drop down list box.

2. Declare 2 Boolean variablesPublic a As BooleanPublic j As Boolean

3. Design the form with 3 check boxes4. Handle Mouse Up event for the check1 control and type the handler as given

belowPrivate Sub Check1_MouseUp(Button As Integer, Shift As Integer, X As Single,Y As Single)

If a And j Then Check1.Value = 1Exit SubEnd IfIf a Or j ThenCheck1.Value = 2Exit SubEnd IfIf Not a And Not j ThenCheck1.Value = 0Exit SubEnd IfEnd Sub

5. Handle click event for check2 controlPrivate Sub Check2_Click()

If Check2.Value = 1 ThenForm1.a = TrueElseForm1.a = False

End IfEnd Sub

6. Handle click event for check3 control

Private Sub Check3_Click()

Page 35: Dmc 175745

VISUAL PROGRAMMING

NOTES

35 ANNA UNIVERSITY CHENNAI

If Check3.Value = 1 ThenForm1.j = TrueElseForm1.j = FalseEnd IfEnd Sub

Initialize as followsPrivate Sub Form_Load()If Form1.a ThenCheck2.Value = 1ElseCheck2.Value = 0End IfIf Form1.j ThenCheck3.Value = 1ElseCheck3.Value = 0End IfEnd Sub

7. Execute the project

8. If check2 or check3 is checked by clicking on it and then check1 is clicked itwould become grayed. In this case the public variables a or j would become 1.This snippet in MouseUp will execute

If a Or j Then

Check1.Value = 2

9. If check2 and check3 are made empty by clicking on them when they are clickedand then check1 is clicked it would become empty. In this case the public variablesa and j would become 0. This snippet in MouseUp will execute

If Not a And Not j Then

Check1.Value = 0

10. If check2 and check3 are checked by clicking on them then check1 wouldbecome checked. In this case the public variables a and j would become 1. Thissnippet in MouseUp will execute

If a And j Then

Check1.Value = 1

Page 36: Dmc 175745

DMC 1755

NOTES

36 ANNA UNIVERSITY CHENNAI

2.9 DIALOG BOXES

Two dialog boxes, namely, the message box and the input box are used in VisualBasic. A message box is used for displaying messages to users and input box is used by theuser for inputting values.

2.9.1 Message Box

The Message Box can be given a title as in Fig 2.11. To specify a title for the messagebox follow the command given below.

Private Sub Command1_Click()

Dim i As Integer

i = 80

MsgBox “i is “ & i, vbOKCancel, “demo”

End Sub

Figure 2.11 Message box

When the command button is clicked a message box is displayed with the contentsas “ i is 80” and OK and Cancel buttons are displayed. The message box is displayedwith a title as demo, which is the third parameter of the MsgBox command.

When the mouse is clicked on the form, the event Form_MouseDown gets executed.The event handler is given below. The contents of the MsgBox would be demo of msgboxand Yes, No buttons would be displayed on the MsgBox as in Fig 2.12. The third parameter,namely sample would be the title of the MsgBox.

Private Sub Form_MouseDown(Button As Integer, Shift As Integer, X As Single, YAs Single)MsgBox “demo of msgbox”, vbYesNo, “sample”End Sub

Figure 2.12 Message box

Page 37: Dmc 175745

VISUAL PROGRAMMING

NOTES

37 ANNA UNIVERSITY CHENNAI

2.9.2 Input Box

To illustrate the use of Input Box in Fig 2.13 consider the example given below.

1. Start a new project2. Choose standard exe3. Add a command button to the form4. handle double click for the command button and code the handler as given

below.Private Sub Command1_Click()Dim r As Stringr = InputBox(“name”)MsgBox “hello “ & rEnd Sub

5. Execute6. The input box asks for an input7. Once the input is entered(say mca) hello mca would be displayed using

the message box; & is used for string concatentation.

Figure 2.13 Input Box2.10 MODULE

Modules are collection of VB statements. It is used to simplify program development.To add a module to your project, Select project tabpage, then right click and choose add,then select module. In response a new dialog will open up. Choose new and a new windowwill open to type your coding. Type the following coding.

Sub Main() Dim sum1 As Integer sum1 = 80sum1 = sum1 + 10MsgBox sum1

Main1

Page 38: Dmc 175745

DMC 1755

NOTES

38 ANNA UNIVERSITY CHENNAI

End SubAdd one more module as Main1. Type the following coding in module Main1.

Sub Main1()Dim sum1 As Integersum1 = 80sum1 = sum1 - 10MsgBox sum1

End Sub

You can choose the Startup object for the project. Select project tabpage, then rightclick and choose properties. Then choose the startup object from the Startup object listbox control. In this case choose Main(). When you execute, Main() will be the startingpoint of execution. It displays sum1, and then a call to function Main1 is encountered. Socontrol gets transferred to the module containing Main1. In Main1 the subtraction is doneand the value is displayed.

2.11 FILE SYSTEM CONTROLS

There are three file system controls as in Fig 2.14. The drive list box, directory listbox and the file list box. The drive list box control is used to display the disk drives on thesystem such as A drive ,C drive ,D drive etc. The down arrow in the control helps you tovisualize all the available drives in the system. The directory list box is used to display thedirectories available in the selected drive. The file list box displays all the files in theselected directory. To test the file system controls follow the steps given below.

2.11.1 A Project to illustrate the use of file system controls.

1. Create a project.2. Drag the drive list box, directory list box and file list box from the tool box and

drop on the form.3. Place a text box on the form.4. Handle change event for the drive list box object. The object would be Drive1 by

default.5. Handle change event for the directory list box object. The object would be Dir1

by default6. Handle click event for the file list box object. The object would be File1 by

default7. CurDir$ is a Visual Basic keyword. It is used to denote the path of the current

directory, drive and file.8. Handle form load event. Code the form_load handler as given below.

Private Sub Form_Load()

Page 39: Dmc 175745

VISUAL PROGRAMMING

NOTES

39 ANNA UNIVERSITY CHENNAI

Drive1.Drive = CurDir$Dir1.Path = CurDir$File1.Path = CurDir$File1.Pattern = “*.*”End Sub

The CurDir$ keyword stores the selected drive’s path in the Drive1 object. Thedata member Drive contains the selected drive’s path. The CurDir$ keyword stores theselected drive’s path in the Drive1 object in the above code snippet. The data memberDrive contains the selected drive’s path . The CurDir$ keyword stores the path of theselected directory in the Dir1 object. The data member Path contains the selecteddirectory’s path. The CurDir$ keyword stores the selected file’s path name in the File1object. The data member Path contains the selected file’s path name.

9. Handle change event for the Drive1 object. Code the handler as given below.Private Sub Drive1_Change()Dir1.Path = Drive1.DriveEnd SubDir1.Path sets the path of the directory from the current drive.

10. Handle change event for the Dir1 object. Code the handler as given below.Private Sub Dir1_Change()File1.Path = Dir1.PathEnd Sub

File1.Path sets the path of the file from the current directory.11. Handle click event for the File1 object. Code the handler as given below.

Private Sub File1_Click()Text1.Text = File1.FileNameEnd Sub

File1.FileName returns the selected file’s name and that is stored in the text boxText1.

Page 40: Dmc 175745

DMC 1755

NOTES

40 ANNA UNIVERSITY CHENNAI

Figure 2.14 File System Control

2.12 MULTIPLE DOCUMENT INTERFACE (MDI) WINDOWS

Single document interface (SDI) support one open window or document at a time.Microsoft’s notepad and paint are examples of single document interface. As we knowSDI applications have limited capabilities. They have limited image and text- editingfeatures. Multiple document interface allows users to edit multiple documents at the sametime as given in Fig 2.15. Adobe Photoshop allows to edit multiple images at the sametime.

Figure 2.15 MDI Window

Page 41: Dmc 175745

VISUAL PROGRAMMING

NOTES

41 ANNA UNIVERSITY CHENNAI

The main window in a MDI program is the parent window. All the other windows ofthe application are child windows. A MDI program will have only one parent window andmany child windows. Only one child window will be open at one time. Uses of childwindows can vary. A child window could be used for editing images, the second childwindow could be used for editing text. Closing or minimizing the parent windowautomatically closes the child windows.

2.12.1 Steps for Creating A MDI Form

1. Create a new form and set IsMdiContainer property to true.2. Create a child form class to add to the form.3. Right click the project in the solution explorer4. Select Add and then select Windows Form5. Create a new child form object and set the MdiParent property to the parent

form.6. Invoke the child form’s Show method.7. Write the coding below to create the child form in a event handler.

Dim childForm As New ChildFormClass()childForm.MdiParent = parentFormchildForm.Show()

2.13 CONTROL ARRAY

A control array is a group of like objects with the same name.

Adding controls with control arrays uses fewer resources than simply adding multiplecontrols of the same type to a form at design time. Control arrays are also useful if youwant several controls to share code. For example, if three option buttons are created as acontrol array, the same code is executed regardless of which button was clicked.

If you want to create a new instance of a control at run time, that control must be amember of a control array. With a control array, each new element inherits the commonevent procedures of the array.

Using the control array mechanism, each new control inherits the common eventprocedures already written for the array. For example, if your form has several text boxesthat each receive a date value, a control array can be set up so that all of the text boxesshare the same validation code.

For example you can have several Text Boxes with the same name and differentiatethem with the help of a subscript. We will see how to create a control array. We are goingto create an array of textboxes. Follow the following steps to create a control array oftextbox.

Page 42: Dmc 175745

DMC 1755

NOTES

42 ANNA UNIVERSITY CHENNAI

1. Create a VB project.2. Click the command button and paste it on the form.3. Drag the Text Box control and place it on the form.4. Copy the Text Box control.5. Paste the copied Text Box control on the form.6. The following message would be displayed7. You already have a control named Text1’. Do you want to create a control

array?8. Select yes and the Text Box control would be pasted on the form.9. Paste as many times as you want. For instance to create a control array with 3

elements paste the control 2 times.10. Handle click event for the command button.11. Include the following code in the event handler.

Private Sub Command1_Click()Dim an As IntegerFor an = 0 To 2Text1(an).Text = Val(Text1(an).Text) + 5Next anEnd Sub

The Val function converts the content of Text1 to numeric. The subscript, an, is usedto access the various text boxes; an(0) would refer to the first text box, an(1) would referto the second text box and an(2) would refer to the third text box.

2.14 DATA CONTROL

The data control is used to connect to a database. Three properties are essential toconnect to a database. The first property is the database name. You can set this in the datacontrol property. The syntax is

Form.datacontrol.DatabaseName = pathname

pathname is the location of the database file name. If the database is ex.mdb, and thedata control is Data1 then to set the DatabaseName property do the following initialization.

Data1.DatabaseName = “C:\ex.mdb”

The second property is the Connect property. The default is Access. If you click thedrop down list box you’ll observe that you can connect to Paradox, Dbase, Excel, Lotusand ODBC. You need to set the Connect property. The third property is the Recordsetproperty. It can be a table, a dyna set type record set or a snap shot type record set.

The Record Source can be a table or a SQL statement.

Page 43: Dmc 175745

VISUAL PROGRAMMING

NOTES

43 ANNA UNIVERSITY CHENNAI

2.14.1 Displaying The Database

Text box, check box, image box, labels, picture box can be bounded to the datacontrol for displaying the data base contents. Two properties are essential for binding tothe data control. The DataSource and the DataField are the essential properties forbinding to the data control. The DataSource refers to the database and the DataFieldrefers to the specific field of the record.

If a text box is used for displaying the names of the customer then the DataFieldproperty of the text box should be initialized as follows.

Txtcust. DataField = “customer name”

2.14.2 A Project to Display a Database

1. Assume there are 5 fields describing a customer. Id, name, address, city andstate.

2. Place 5 text boxes on the form to display the records.3. Place a data control on the form4. Set the DatabaseName property as given below

Data1.DatabaseName = “C:\ex.mdb”5. Set the Record Source for the data control as Customer by selecting the table

from the drop down list box in the property box.6. Set the Record Type to 0 to indicate Customer table of ex.mdb .7. Bind the text boxes to the data control. This is achieved by setting the Data Source

to Data1 for all the text boxes one at a time.8. Set DataField property for each text box and set to the different fields of the

Customer table.9. Run the project.10. The records of the Customer table would be displayed.

2.14.3. The Refresh Method

The refresh method moves to the first record in the record set. To invoke the refreshmethod follow the syntax given below.

Form1.Data1.Refresh

2.14.4 Adding Records

1. As in the previous case Set the DatabaseName property as “C:\ex.mdb”,Set the Record Source for the data control as Customer and Set the RecordType to 0.

2. Design a form with 5 text boxes and 2 command buttons new and update.

Page 44: Dmc 175745

DMC 1755

NOTES

44 ANNA UNIVERSITY CHENNAI

3. Set the DataSource to Data1 for all the text boxes.4. Set the DataField property for each text box to the different fields of the Customer

table.5. Handle Click event for the command button new and type the handler as given

belowdata1.RecordSource = “Customer”data1.Refreshdata1.Recordset.AddNewAdd New adds a buffer in memory for a new record.

6. Handle Click event for the command button update and type the handler asgiven below

data1.Recordset(“Id”) = CInt(text1.Text)data1.Recordset(“name”)= text2.Textdata1.Recordset(“address”)= text3.Textdata1.Recordset(“city”)= text4.Textdata1.Recordset(“state”)= text5.Textdata1.Recordset.Update

Update writes the record into the database.

2.14.5 Deleting Records

To delete a record use the Delete method. To delete a record from the customer tablefollow the coding given below.

data1.RecordSource = “Customer”

data1.Recordset.Delete

The above coding would delete the current record.

Short Questions

1. Name any 4 events associated with a command button.LostFocusKeyDownKeyUpMouseDown

2. Name any 4 events associated with a form.LoadMouseDownResizeClick

Page 45: Dmc 175745

VISUAL PROGRAMMING

NOTES

45 ANNA UNIVERSITY CHENNAI

3. Write the code for validating the input not to be 0.Handle validate event for the text box.Type the coding below.

Private Sub Text1_Validate(Cancel As Boolean)If (Val(Text1.Text) = 0) Then

Text1.Text = “ “End If

Result

If 0 is entered in Text1 it would be cleared when you click on the next control.

4. How will you ensure that the input is numeric?

Private Sub Text1_Validate(Cancel As Boolean)

If (IsNumeric(Text1.Text)) Then

MsgBox “number

End IfAnswer:

Handle validate event for the textbox.

IsNumeric checks whether the input is numeric.

MsgBox displays a message box (modal dialog)flashing number

5. Write the code to add 2 inputs only if both of them are numbers.Answer

1. Handle form double click event2. Use IsNumeric function to validate both the inputs3. The logical operator And ensures that only if both the conditions are true , addition

will be done.4. Even if one input is not a number the Text3 control would be cleared.

Private Sub Form_DblClick()It is Numeric (Text1.Text) And Is Numeric(Text2.Text)Then

Text 3.Text = Text1.Text +Text2.TextElse

Text3.Text = “ “End IfEnd Sub

5. Name any 3 buttons that can be associated with the second parameter of MsgBox.

Page 46: Dmc 175745

DMC 1755

NOTES

46 ANNA UNIVERSITY CHENNAI

Answer

vbCritical - displays a crossvbDefaultButton4 – displays no buttonvbExclamation – displays the exclaimation symbol “!”

6. What would be the check box state depending on thevalue of CHECKEDIf Check.Value is 0 means the check box will be uncheckedIf Check.Value is 1 means the check box will be checkedIf Check.Value is 2 means the check box will be grayed

7. What is read only property?

Read only property can be set at design time. It cannot be changedprogrammatically. The read only property can be set in the property window.

8. State the procedure for creating accelerators?In the caption of the control, place ‘&’ before any character. During execution,that character would be under lined. To invoke that control you can press CTRLand the under lined character at the same time.

9. What is default property?The default property need not be given value. For example the control combobox as Text as the default property.

Exercise

1. Develop a simple calculator to perform addition, subtraction, multiplication anddivision using VB.

Solution1. Select the text box control inside the tool box to the left of the work area.2. Place 3 text box controls on the form. Text1 and Text2 controls can be used for

supplying input. Text3 control will reflect the result.3. Place the 4 command buttons on the form.4. Associate the click event with the command buttons as given below.

Private Sub Command1_Click() Text3.Text = Val(Text1.Text) + Val(Text2.Text)End Sub

5. Private Sub Command2_Click()Text3.Text = Val(Text1.Text) - Val(Text2.Text)

End Sub

Page 47: Dmc 175745

VISUAL PROGRAMMING

NOTES

47 ANNA UNIVERSITY CHENNAI

6. Private Sub Command3_Click()Text3.Text = Val(Text1.Text) * Val(Text2.Text)

End Sub7. Private Sub Command4_Click()

Text3.Text = Val(Text1.Text) / Val(Text2.Text)End Sub

8. Run the program. 9. Enter the numbers in the input text box.

10. Click the command button and observe the result text box.

2. Create a project to illustrate a control array. Create a control array of ovals and assigndifferent fill styles.

Solution

1. Paste the Shape control on the form.2. Set the shape of the control by setting the shape property. Assign the value 2 to

denote oval shape.3. Copy and paste the object which enables control array creation.4. Paste the command button on the form.5. Handle click event for the command button.6. Incorporate the event handler as follows.

Private Sub Command1_Click()For k = 0 to 2Shape1(k).FillStyle = k+2Next kEnd Sub

3. Write a program to create a list box containing names of fruits.

a. Copy the selected item of the list box on to a second list box.b. Clear the contents of the first list box after copying to the second list box.c. Copy the second list box selected contents on to the first list box.d. Clear the contents of the second list box after copying to the first list box.

Solution

1. Create a new project by choosing file and then new options2. Let the project type be standard exe3. Paste 2 list box controls on the form.

Page 48: Dmc 175745

DMC 1755

NOTES

48 ANNA UNIVERSITY CHENNAI

4. Initialise the first list box by coding in form load eventPrivate Sub Form_Load()List1.AddItem “a”List1.AddItem “b”List1.AddItem “c”List1.AddItem “d”End Sub

5. Handle click event for the first list box and write the coding as givenPrivate Sub List1_Click()List2.AddItem List1.TextList1.RemoveItem List1.ListIndexEnd Sub

The Selected item is given by List1.Text. And it is inserted into the second list boxby List2.AddItem.List1.RemoveItem removes the contents from the list1 list box.The item to be deleted is given by the position indicator List1.ListIndex

6. Handle click event for the first list box and write the coding as givenPrivate Sub List2_Click()List1.AddItem List2.TextList2.RemoveItem List2.ListIndexEnd Sub

7. Click Run and Then Start with full compile.8. Click the contents of the first list box and observe the contents of the first list box

and the second list box .9. Repeat Step 8 until list box 1 becomes empty.10. Repeat Steps 8,9 with the second list box.

4. Write a program to create a list box containing numbers 1 to 10. Count the contentsof the list box and display the total items in a text box.

Solution1. Create a new project by choosing file and then new options2. Let the project type be standard exe3. Paste a list box control on the form.4. Initialise the first list box by coding in form load event

Private Sub Form_Load()List1.AddItem 1List1.AddItem 2

Page 49: Dmc 175745

VISUAL PROGRAMMING

NOTES

49 ANNA UNIVERSITY CHENNAI

List1.AddItem 3List1.AddItem 4List1.AddItem 5List1.AddItem 6List1.AddItem 7List1.AddItem 8List1.AddItem 9List1.AddItem 10End Sub

5. Handle click event for the first list box and write the coding as givenPrivate Sub List1_Click()Text1.Text = List1.ListCountEnd Sub

The total number of items in the list box is given by List1. ListCount.6. Click Run and Then Start with full compile.

7. Click the contents of the first list box and observe the contents of the text box.

5. Write a program to create a combo box containing fruits. Transfer the selectedcontents of the combo

Solution1. Create a new project by choosing file and then new options2. Let the project type be standard exe3. Paste a list box control and combo box control on the form.4. Initialise the combo box by coding in form load event

Private Sub Form_Load()Combo1.AddItem “apple”Combo1.AddItem “orange”Combo1.AddItem “grapes”

End Sub5. Handle click event for the combo box. Code the handler as given below.

Private Sub Combo1_Click()List1.AddItem Combo1.TextEnd Sub

6. Click Run and Then Start with full compile.7. Click the contents of the combo box and observe the contents of the list box

Page 50: Dmc 175745

DMC 1755

NOTES

50 ANNA UNIVERSITY CHENNAI

Summary

This Unit focuses on Visual Basic programming which is event driven programming. Aform is a layout on which objects called controls are placed. Properties and events associatedwith controls are discussed. The creation of projects in Visual Basic is explained. Thecommand button, text box, list box , combo box controls methods and some of theproperties were introduced. The different data types are introduced. The use of varianttype is explained. The working of the control statements are explained in detail. Theway in which menu titles and items are to be incorporated is explained. How to associatetoolbars with the menu titles and items was also covered. File system controls and controlarrays are discussed. MDI forms and accessing the database with the data control areexplained.

Page 51: Dmc 175745

VISUAL PROGRAMMING

NOTES

51 ANNA UNIVERSITY CHENNAI

UNIT III

VISUAL C++ PROGRAMMING AND CONTROLS

3.1 INTRODUCTION

This unit introduces you to develop applications using VC++. Single document interface(SDI), multiple document interface (MDI) and dialog based applications are covered inthis unit. The creation of these projects is explained. Every SDI or MDI project has 4classes incorporated in it. The view class is used for producing the drawing code. TheOnDraw() function in the view class implementation file is meant to house the drawingcode. The document class houses the data for the application. The framewnd class isresponsible for all the windows related coding such as the status bar, menu bar. Theobject of the application is contained in the Appclass. The appwizard tool’s role ofcreating a project is explained. The tool, class wizard’s role in adding member variablesis explained. Programs to illustrate event handling are incorporated. The CString, CRect,CPoint, CBrush, CClientDC, CColorDialog, CDC Microsoft Foundation Classes (MFC) used are covered in this unit. The need for device context is outlined. The documentview architecture is explained. Modal and Modeless dialogs are introduced. The conceptof serialization is covered. The MFC library is built on top of other Win 32 API. MFCis written in C++. MFC programs uses Win 32 APIs to interact with the OS.

3.2 LEARNING OBJECTIVES

To introduce the 3 different types of VC++ projects. To explain how to use class wizard and App wizard. To expose to the various files in a VC++ project. To introduce MFC classes. To introduce events and event handling. To introduce client area and invalid region. To introduce device context. To learn all GDI objects. To explain Serialisation. To explain document view architecture

Page 52: Dmc 175745

DMC 1755

NOTES

52 ANNA UNIVERSITY CHENNAI

To introduce the modal dialogs CColorDialog and CFileDialog To introduce MDI To introduce splitter window

3.3 TYPES OF PROJECTS USING VC++

A VC++ project can be a SDI application, MDI application or a dialog basedapplication.

3.3.1 SDI Application

A SDI application uses the main frame window to display a document. Only onedocument can be opened at a time.

3.3.2 MDI Application

A MDI application uses the main frame window as a work space in which the usercan open more document frame windows.

3.3.3 Files in a SDI and MDI Application

Both SDI and MDI projects has four implementation files (.cpp extension). They arethe files corresponding to the View Class, Document Class, MainFrame Class and theApp Class.

The App class contains the object of the project and it is inherited from CWinApp.If the project is named as first the App class would be named as CFirstApp and theimplementation file would be first.cpp. A corresponding header file first.h would also beavailable.

The View Class is mainly used for writing the drawing code. The OnDraw() functionin the View Class is the place where you will write the drawing code. Apart from theOnDraw() function, you can incorporate event handlers with drawing code. For the projectnamed first, the View Class would be CFirstView and the implementation file would befirstView.cpp. The corresponding header file would be firstView.h.

The Document class is the place where the data members are defined. Also it has theSerialise function which implements the file storage and retrieval. If the project is named asfirst the document class would be CFirstDoc and the implementation file would befirstDoc.cpp. The corresponding header file would be firstDoc.h.

The MainFrame class contains all the necessary coding for the display window of theproject. The status bar pane initialization is done in the MainFrame class. If the projectis named as first the MainFrame class would be CMainFrame and the implementationfile would be MainFrm.cpp. The corresponding header file would be MainFrm.h. Alsostdafx.h, the standard application frame work header file will also be part of every project.

Page 53: Dmc 175745

VISUAL PROGRAMMING

NOTES

53 ANNA UNIVERSITY CHENNAI

Apart from these implementation and header files , dsp, .ncb and .plg files are present;.dsp is the developer studio project file; .ncb contains the class information in binary; .plgcontains the settings of that project.

3.3.4 Dialog Based Application

The application that app wizard creates is based on a dialog templateresource.

3.4 THE IMPORTANT MFC CLASSES

The CWinApp, CDocument, CFrameWnd and CView are derived from CObjectand they provide most of the structure and functionality.

3.5 THE PRECOMPILED HEADER FILE

As soon as you create an empty project, before doing any coding you compile theproject to create .pch ( the pre compiled header) file and then you build. Because it isincremental compilation every time only the changes will be compiled.

3.6 APPWIZARD

Appwizard is a tool used for creating a project. It follows a sequence of steps tocreate a project.

3.6.1 Steps Involved in Creating A Project

Step 1From the menu bar , click File and then new options.

Step 2The new dialog box will appear with 4 tab pages. They are the1. Files2. Projects3. Workspaces4. Other Documents

Step 3Choose projects (2) in the above step. Then choose MFC Appwizard(.exe) option

Step 4Type the project name in the Edit box. A directory will be created using this name in

which all the files will be stored. Then click OK.Step 5

Choose any one of the options given below for the project type.1. Single Document

Page 54: Dmc 175745

DMC 1755

NOTES

54 ANNA UNIVERSITY CHENNAI

2. Multiple Document3. Dialog Based

The above sequences forms the Step1 of Appwizard.Step 6

Click nextIt will take you to the second step of the MFC appwizard. Select none and click next.

Step 7In the third step of MFC appwizard choose none and proceed with next button.

Step 8In the step 4 of MFC appwizard keep the settings as such and click the next button.

Step 9In step 5 of appwizard, you have the option of getting the comments on the coding.

Choose what you require and click next.Step 10

This is the last step of appwizard. The new classes to be created are displayed here.Click finish and then click create to complete the creation of application.

3.7 CLASS WIZARD

Class wizard given in Fig 3.1 is a tool to handle message handlers for objects, todefine member variables.

Fig ure 3.1 Class Wizard

Page 55: Dmc 175745

VISUAL PROGRAMMING

NOTES

55 ANNA UNIVERSITY CHENNAI

3.7.1 Adding Handlers With Class Wizard

When a handler is added, the class wizard places the prototype for the messagehandler in the header (.H) file. It provides a skeleton handler in the implementation file(.cpp) in the class which is placed in the base class combo box. It also adds the message-map entry that connects the message and the handler in the implementation file. For instance,for the message WM_LBUTTONDOWN, the prototype afx_msg void OnLButtonDown(UINT nFlags, CPoint point) is inserted in the header (.H) file by the class wizard. Theclass wizard inserts the skeleton handler in the implementation file (.cpp). The skeletonhandler would look as given below.

void CAppView :: OnLButtonDown( UINT nFlags, CPoint point)The class wizard also inserts an entry in the Message_Map macro.BEGIN_MESSAGE_MAP( CAppView, CView)

.

.ON_WM_LBUTTONDOWN()..

END_MESSAGE_MAP()

3.7.2 Deleting Handlers With Class Wizard

The handler can be deleted using the class wizard. The class wizard will delete theprototype and message map entry. The user must manually delete the handler.

3.7.3 Message Handling

1. The message is sent to a window. It is sent to the Window Procedure.2. The message map contains all the message handlers.3. The window procedure searches the message map for the handler for the

received message.4. The CWnd :: WindowProc calls the handler and passes the relevant message

parameters.5. If the message handler is not in the message map the default message handler,

that is, CWnd::DefWindowProc is called. The DefWindowProc handler providesdefault behavior such as moving, sizing for all the windows.

3.7.4 Use of WM_SIZE Message

When WM_SIZE message is handled the graphical objects on the output windowwill also change accordingly to the output window. The function Invalidate(TRUE) will

Page 56: Dmc 175745

DMC 1755

NOTES

56 ANNA UNIVERSITY CHENNAI

call the OnDraw() and the TRUE parameter will clear the screen. DeflateRect willshrink the rectangle

1. Create a SDI application wmsize.2. Handle WM_SIZE message for the CWmsizeView object id.3. Choose the class tabpage4. Right Click on CWmsizeView . A menu will pop up.5. Choose Add member variable.6. Specify the type as CRect and the variable name as m_rdRect.7. Type the coding in bold in OnDraw()void CWmsizeView::OnDraw(CDC* pDC){

pDC->SelectStockObject(GRAY_BRUSH);m_rdRect.DeflateRect(50,10);pDC->Rectangle(m_rdRect);

}8. Type the following coding in OnSize event handler.void CWmsizeView::OnSize(UINT nType, int cx, int cy){

GetClientRect(&m_rdRect);Invalidate(TRUE);

}9. Build and execute the project.10. A gray window will be displayed within a white window. The inner window is due

to deflate rectangle function.11. Change the brush as DKGRAY_BRUSH,HOLLOW_BRUSH and

GRAY_BRUSH and observe the output.12. Change m_rdRect.DeflateRect (2,2,2,2) and Build and execute the project.13. Delete the OnSize code.14. Remove the message WM_SIZE using the class wizard.15. Initialise the rectangular object as given16. CSizeView::CSizeView():m_rdRect (10,30,50,20) {}17. Build and execute the project.18. You will observe the impact of WM_SIZE message.

Page 57: Dmc 175745

VISUAL PROGRAMMING

NOTES

57 ANNA UNIVERSITY CHENNAI

3.8 WRITE A PROGRAM USING VC++ TO DISPLAY THE MOUSECOORDINATES

Step 1 Create a SDI application using Appwizard

Step 2 Press CTRL + W to invoke the class wizard

Step 3 Choose the View Class in the Combo box for the Class name

Step 4 Handle the WM_LBUTTONDOWN message for the View object id.

Step 5 Type the coding in bold in the event handler on OnLeftButtondown()

{

CString Str;

Str.Format(“%d %d”, CPoint.x,CPoint.y);

AfxMessageBox(Str);

}

Observe the Message map section. The prototype would be included in the header file.

Step 6 Build and execute the project.

Step 7 When the left mouse button down is pressed the coordinates of thatposition is displayed.

3.9 MFC CLASSES REQUIRED TO DRAW A RECTANGLE IN THE CLIENTAREA

A client area is where you can do drawing. The regions in which we cannot draw isknown as Invalid Regions.

To draw a rectangle in the client area we will use the following MFC classes, namely,CRect, CPoint and CBrush.

CRect is used for creating a rectangle. CRect includes member functions tomanipulate CRect objects and Windows RECT structures. A CRect object can be passedas a parameter in place of RECT structure, LPCRECT or LPRECT .

A CPoint object can be used wherever a POINT structure is used. Generally theevent handlers associated with the mouse have one of the parameters of type CPoint. Itrepresents the x and y coordinates of the mouse position.

CBrush Class encapsulates a Windows graphics device interface (GDI) brush.Brushes can be solid, hatched or patterned.

Page 58: Dmc 175745

DMC 1755

NOTES

58 ANNA UNIVERSITY CHENNAI

The hatch style of the brush can be any one of the following values and it is the firstparameter of the CBrush constructor represented by the parameter nIndex.

CBrush(int nIndex, COLORREF crColor)

The parameter nIndex can take any one of the values given below.

HS_BDIAGONAL   Downward hatch (left to right) at 45 degrees

HS_CROSS   Horizontal and vertical crosshatch

HS_DIAGCROSS   Crosshatch at 45 degrees

HS_FDIAGONAL   Upward hatch (left to right) at 45 degrees

HS_HORIZONTAL   Horizontal hatch

HS_VERTICAL   Vertical hatch

COLORREF is a macro which takes a RGB component to represent a color.

3.10 DEVICE CONTEXT

A device context provides the necessary drawing tools and the platform to draw. Ithelps to draw text, lines, shapes etc. To create a device context, the MFC provides variousclasses such as CDC and CClientDC.

CDC is the most fundamental class to draw in MFC. It provides all of the basicdrawing steps.

CClientDC class is used for drawing in the client area of a window.

Device context is a windows data structure that supports device independent output.The role of device context is best explained by Fig 1.

Win32 App Device Context Logical Display Device Driver ActualDisplay

Fig 1 The Role Of Device Context

The logical display is a virtual device and Actual display is the physical device. Theprogrammer need not worry about the medium in which he is writing the output. Thedevice context takes care of the output medium.

3.11 GDI OBJECTS

CDC provides five versions for GDI objects. They are pens, brushes, fonts, bitmapsand regions. The Select Object function replaces the current GDI object with the objectspecified as parameter. The GDI object CPen can use the following macro to specify thepen style.

Page 59: Dmc 175745

VISUAL PROGRAMMING

NOTES

59 ANNA UNIVERSITY CHENNAI

PS_SOILD

PS_DASH

PS_DOT

PS_DASHDOTDOT

3.11.1 Illustration of GDI object CPen1. Create a SDI application. Name it as gdipen.2. press ctrl(control key) and W together to invoke the class wizard.3. Choose the message maps tab in the class wizard.4. Choose CGdipenView object id and click WM_MOUSEMOVE message

and click ok.5. In response OnMouseMove handler will be inserted in the implementation file

gdipenView.cpp as given below.6. Type the coding in bold in the handler.void CGdipenView::OnMouseMove(UINT nFlags, CPoint point)

{CPen p(PS_SOLID, 2,RGB(255,205,255)),pe(PS_DASH,1,RGB(150,200,250));CClientDC dc(this);dc.SelectObject(&p);dc.Rectangle(10,20,50,100);dc.SelectObject(&pe);dc.Rectangle(100,20,50,100);}

7. The macro PS_SOLID in the CPen constructor tells the pen style. The secondparameter is the thickness of the pen, namely 2. The third argument specifies thecolor of the pen. Another pen object is created as pe. 2 Rectangles with thepens p and pe are drawn.

8. Change the style, thickness and color.9. Build the project and execute it to see the impact of the change incorporated.10. The rectangles would be displayed when the mouse is moved in the window

displayed.11. Change the color , thickness and style of the pen and observe the output after

building and executing the project.

Page 60: Dmc 175745

DMC 1755

NOTES

60 ANNA UNIVERSITY CHENNAI

Default Values for GDI Objects

The default color for pen is black , brush is white, default bitmap is null and the defaultfont is system.

3.12 STEPS TO BE FOLLOWED TO CREATE A RECTANGLE IN THE CLIENT AREA

1. Create a SDI application and name it as brush.2. Handle WM_LBUTTONDOWN message for the CBrushView object id.3. In response to Step 2 ON_WM_LBUTTONDOWN member function would

be inserted in the view implementation file as follows.void CBrushView::OnLButtonDown(UINT nFlags, CPoint point){ }

4. Type the following code in ON_WM_LBUTTONDOWN member functionCRect l;CBrush b(HS_BDIAGONAL,(point.x,point.y));CClientDC dc(this);dc.SelectObject(&b);//BOOL GetClientRect(LPRECT lpRect) constGetClientRect(&l);dc.Rectangle(l);

5. Build and execute the project.6. A window with lines would be displayed when the left button is pressed.7. Click the left button in different places and note the color change.8. Change the brush style as HS_DIAGONAL, HS_HORIZONTAL,

HS_VERTICAL and HS_CROSS for different executions and observe the output.

Get Client Rect function captures the rectangular window area and stores inm_rdRect object.

Select Stock Object makes a call to CGdi Object :: From Handle() to determinewhich CGdiObject to return.

Figure 3.2 Affect of Rectangle Function

Page 61: Dmc 175745

VISUAL PROGRAMMING

NOTES

61 ANNA UNIVERSITY CHENNAI

3.13 WRITE A PROGRAM TO DRAW A RECTANGLE GIVEN 2 POINTS

Step 1 Create a SDI application.

Step 2 Declare a global member variable in the View Class.

Step 3 To declare the global variable, click the Class tab page.

Step 4 Select the View Class

Step 5 Right Click on the View Class. A menu pops up.

Step 6 Choose Add member variable. (Create the given variable)

Declare the datatype as CPoint and the variable name as m_ptoldpt

Step 7 In response to Step 6 the variable is included in the header file.

Step 8 Initialise the data member in the constructor.

Step 9 At the end of the constructor initialize the member as given below.

CSample::CSample():m_ptoldpt(0,0)

{}

Step 10 Using class wizard handle WM_LBUTTONDOWN andWM_LBUTTONUP messages for the View object.

Step 11 Type the code in bold in LBdown handler.

void CDragView::OnLButtonDown(UINT nFlags, CPoint point)

{

m_ptoldpt=point;

}

The variable m_ptoldpt is initialized with the current mouse co-ordinates.

Step 12 Type the code in bold in LBup

void CDragView::OnLButtonUp(UINT nFlags, CPoint point)

{

CDC *pDC = GetDC();

pDC->Rectangle(m_ptoldpt.x, m_ptoldpt.y,point.x,point.y);

CView::OnLButtonUp(nFlags, point);

}

Page 62: Dmc 175745

DMC 1755

NOTES

62 ANNA UNIVERSITY CHENNAI

Step 13 Build and execute the project

Step 14 Click the left button down (first point is got) and move the mouse andrelease the left button (second point is got). The rectangle would be drawn using the 2points as given in Fig 3.2.

3.14 WRITE A PROGRAM TO ZOOM A RECTANGLE AS YOU DRAG1. Create a SDI application2. Declare 2 member variables clicked of Boolean type and m_ptoldpt of CPoint

type. Use class tab page and add member variables by right clicking on the ViewClass.

3. Using Class wizard add the messages left button down , left button up and mousemove.

4. Type the coding in bold in the left button down event handler.void CDragView::OnLButtonDown(UINT nFlags, CPoint point)

{clicked=true;

}The Boolean variable clicked is set to true.

5. Type the coding in bold in the left button up event handler.void CDragView::OnLButtonUp(UINT nFlags, CPoint point){

clicked=FALSE;Invalidate(TRUE);

}The Boolean variable clicked is set to FALSE and OnDraw() function is called using

Invalidate() function. The parameter TRUE clears the screen by calling WM_PAINT.6. Type the coding in bold in the Mouse Move event handler.

void CDragView::OnMouseMove(UINT nFlags, CPoint point){

if(clicked) {

CDC *dc = GetDC();dc->Rectangle(oldpt.x,oldpt.y,point.x,point.y);oldpt=point;

}}

Page 63: Dmc 175745

VISUAL PROGRAMMING

NOTES

63 ANNA UNIVERSITY CHENNAI

When the mouse button is released with the last point as first point and where themouse button was released a rectangle would be drawn.

3.15 WRITE A VC++ PROGRAM TO SCRIBBLE

Step 1 Create a SDI applicationStep 2 Create a CPoint object m_ptoldpt and Boolean variable clicked. Initialise in

the constructor. Use Class Tab page and select the View Class. Right click and chooseadd member variable option.

CMovelineView::CMovelineView():m_ptoldpt (5,5){}

Step 3 Handle Leftbutton down, mouse move and Leftbutton up handlers in theView Class for the View object.

Step 4 Leftbutton down handler. This step initiates the drawingvoid CMovelineView::OnLButtonDown(UINT nFlags, CPoint point)

{clicked=TRUE;

}Step 5 Leftbutton up handler This step terminates the drawing

void CMovelineView::OnLButtonUp(UINT nFlags, CPoint point){

clicked=FALSE;}

Step 6 void CMovelineView::OnMouseMove(UINT nFlags, CPoint point){

if(clicked){CPen p(PS_SOLID, 2, RGB(point.x,point.y,point.x+point.y));CClientDC dc(this);dc.SelectObject(&p);dc.MoveTo (m_pt old pt);dc.LineTo(point);(m_pt old pt) = point;}}

Step 7 Build and execute the project.

Page 64: Dmc 175745

DMC 1755

NOTES

64 ANNA UNIVERSITY CHENNAI

Step 8 Click the left button down and as you move the lines are drawn. The scribbleapplication will terminate when the left button is released. Colors keep on changing becausethe mouse coordinates is used for specifying color.

3.16 ILLUSTRATION OF CCOLORDIALOG

The constructor of CColorDialog takes the first parameter as the default color andthe second parameter indicates how much the dialog is displayed. It is a modal dailog.Modal dialogs are displayed using DoModal() function. Modal dialog need to be disposedby clicking ok or cancel button. To create a color dialog follow the steps given below.

1. Create a SDI application.2. Handle Right button double click message for the CcolordlgView object id.3. In response to Step 2 the event handler will be inserted in colordlgView.cpp.4. Create a device context with which you can draw using CClientDC class.5. Create a color dialog object using CColorDialog class. In this case dlg is the color

dialog object.6. The first parameter RGB(255,0,0) indicates that Red is the default color.7. The modal dialog is displayed using DoModal function as dlg.DoModal()8. We are going to select a color from the color dialog.9. Therefore create a variable color using COLORREF10. The variable color is assigned the color using GetColor() function.11. Create a Cbrush object (mybrush) with the choosen color to draw.12. Use the choosen color with SelectObject function.13. The SelectObject function will put into use the new GDI object and return the

current object.14. Using the new color namely red, the default color, an ellipse would be drawn when

the right button is double clicked.15. Execute the project, double click the right button, choose a color and click ok

button of the color dialog.16. An ellipse would be filled with the choosen color.void CColordlgView::OnRButtonDblClk(UINT nFlags, CPoint point){CClientDC dc(this);CColorDialog dlg(RGB(255,0,0),CC_FULLOPEN);/* RGB(255,0,0) red color, default also red color*/

dlg.DoModal();COLORREF color = dlg.GetColor();//color can be a var and assign value

Page 65: Dmc 175745

VISUAL PROGRAMMING

NOTES

65 ANNA UNIVERSITY CHENNAI

CBrush mybrush(color);dc.SelectObject(&mybrush);dc.Ellipse(20,40,100,150);}

3.17 A PROJECT TO ILLUSTRATE AFXMESSAGEBOX , DEVICE CONTEXT AND WMCHAR MESSAGE

Whenever a message is handled for an object the handler will be included in themacro MESSAGE_MAP delimited by BEGIN and END. The first parameter CDrawViewrepresents the name of the project. The name is actually DrawView and it is prefixed byC. The second parameter states the base class. That is CDrawView is inherited fromCView . When WMCHAR message is handled the corresponding event handlerON_WM_CHAR() will be inserted in CDrawView.cpp. Also it will be included in theMESSAGE_MAP by the class wizard.

BEGIN_MESSAGE_MAP(CDrawView, CView)

ON_WM_CHAR()

END_MESSAGE_MAP()

Message Map sends the window messages and commands to their appropriatehandlers. The Message Map offers many of the advantages of using C++ virtual functionswithout the high over head of polymorphism. The Message Map connects messages tomessage handler function. For instance a WM_CHAR message would be mapped toON_WM_CHAR handler function in a view object. When the message is received, themessage map calls the handler function.

The prototype of a function is of the form given below

afx_msg void OnLButtonDown( UINT nFlags, CPoint point)

OnDraw function is used for writing on the screen for producing output. By defaultthe OnDraw function will be called when ever the project is executed.

A character array named as str is constructed. The value ‘c’ is inserted in thearray. To convert str into a string ‘\0’ (null character) is appended along with ‘c’. TheAfxMessageBox takes a string namely str, as parameter and displays the string str.

void CDrawView::OnDraw(CDC* pDC){

char str[] = {‘c’,’\0'};AfxMessageBox(str);

}

Page 66: Dmc 175745

DMC 1755

NOTES

66 ANNA UNIVERSITY CHENNAI

1. Handle WM_CHAR message for the CDrawView object id. The firstparameter nChar will hold the Unicode equivalent of the character that has beenpressed. To display the character that is pressed a CString object is used. Theformat function gives the character equivalent of the pressed character.

2. GetDC retrieves a handle to a display device context (DC) for the client areaof a specified window or for the entire screen.

3. The TextOut function is used for displaying the character that is pressed.4. ReleaseDC releases a device context freeing it for use by other applications.

void CDrawView::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags) {CString str;str.Format(“%c”,nChar);CDC *pDC = GetDC();

static int i=50;static int j=50;

pDC->TextOut(i,j,str);ReleaseDC(pDC);

i=i+15;}

3.18 DOCUMENT VIEW ARCHITECTURE

The Document/View architecture is used to create applications based on the MicrosoftFoundation Classes library.

The Document/View architecture is composed by a frame, one or more documentsand the view.

The View

A view is used for visualising. For example, while performing word processing, theuser works on a series of words that compose the text. If a user is performing calculationson a spreadsheet application, the interface the user is viewing is made of small boxes calledcells. Another user may be in front of a graphic document while drawing lines and othergeometric figures. The thing the user is looking at and performing changes is called a view.The view also allows the user to print a document.

Page 67: Dmc 175745

VISUAL PROGRAMMING

NOTES

67 ANNA UNIVERSITY CHENNAI

To let the user do anything on an application, you must provide a view, which is anobject based on the CView class. You can either directly use one of the classes derivedfrom CView or you can derive your own custom class from CView or one of its childclasses.

The Document

A document holds the user’s data. For example, after working on a text processor,the user may want to save the file. Such an action creates a document and this documentmust reside somewhere. In the same way, to use an existing file, the user must locate it,open it, and make it available to the application. These two jobs and many others arehandled behind the scenes as a document. To create the document part of this architecture,you must derive an object from the CDocument class.

The Frame

As its name suggests, a frame is a combination of the building blocks, the structure (inthe English sense), and the borders of an item. A frame gives “physical” presence to awindow. A frame defines the location of an object with regards to the Windows desktop.A frame provides borders to a window, borders that the user can grab to move, size, andresize the object. The frame is also a type of desk that holds the tools needed on anapplication.

An application cannot exist without a frame. As we saw in previous lessons, to providea frame to an application, you can derive a class from CFrameWnd.

MFC provides a mechanism for notifying views of modifications to a documentthrough the UpdateAllViews member function of the CDocument class. TheUpdateAllViews function traverses the list of views attached to the document. The functioncalls the OnUpdate of CViewClass . Invalidate(TRUE) in OnUpdate clears the client areaof the view and calls the OnDraw()function of the view class. Document View architectureallows the variables in the document class to be displayed in the view class usingGetDocument() function in the view class.

3.18.1 A Project To Illustrate Document View Architecture

1. Choose MFC Appwizard EXE2. Create a SDI application3. Add a global variable in the document class4. To add the global variable expand class tab page.5. Click on the document class6. Right click and choose add member variable7. Let the variable be CString type and call it c.

Page 68: Dmc 175745

DMC 1755

NOTES

68 ANNA UNIVERSITY CHENNAI

8. CDoDoc::CDoDoc()

{c=”hello”;

}Initialise the variable in the document constructor.

9. Access the document variable in the view class using the pDoc which is a pointer tothe document class. From this we come to know that the variables in the document classcan be accessed only by document class members. The function GetDocument() returnsthe pointer to the document class.

{

CDoDoc* pDoc = GetDocument();

pDC->TextOut(20,30,pDoc->c);

}

3.19 USE OF THE SERIALIZE FUNCTION IN THE DOCUMENT CLASSIMPLEMENTATION FILE

void CStoreDoc::Serialize(CArchive& ar){if (ar.IsStoring())

{// TODO: add storing code here}

else{

// TODO: add loading code here}

}

The Serialize function is used for writing to a file or in the else part it retrieves thecontents of a file.

3.19.1 Displaying a file Without Scrolling.

To display a file follow the steps given below.

1. Create a SDI application.

Page 69: Dmc 175745

VISUAL PROGRAMMING

NOTES

69 ANNA UNIVERSITY CHENNAI

2. Type the coding given in bold in the Serialize else part.The CArchive object ar is used for writing or for retrieving a file.

3. Create a global string m_pdata in the document class.To create the global data click on the ClassView tabpage.Expand the tree control of classes.Select the CStoreDoc classRight click and choose add member variableSpecify the type as char and variable name as *m_pdataGetFile() function of CArchive is used for selcting the file to be displayed.GetLength() returns the size of the file.

4. Allocate memory to the string m_pdata using the new operator5. The Read function of CArchive stores the ncount characters of the file to

be displayed in the string m_pdata.6. The string m_pdata is displayed using AfxMessageBox7. The dynamically allocated memory is recovered using delete function.8. Build and execute the project.9. Choose file and open menu item.10. Choose a file.11. The contents will be displayed in a message box.void CStoreDoc::Serialize(CArchive& ar){

if (ar.IsStoring()){

}else

{unsigned int ncount = ar.GetFile()->GetLength();m_pdata= new char[ncount];ar.Read(m_pdata,ncount);AfxMessageBox(m_pdata);delete [] m_pdata;}

}

Page 70: Dmc 175745

DMC 1755

NOTES

70 ANNA UNIVERSITY CHENNAI

3.19.2 Displaying a file With Scrolling

To display a file with scrolling option enabled follow the steps given below.1. Create a SDI application.2. In the Step 6 of the Appwizard inherit CScrollView as the base class

scrolling code will be inserted by the Appwizard in on initialupdate () function in the View implementation file.

3. Type the coding given in bold in the Serialize else part.unsigned int n=ar.GetFile()->GetLength();str=new char[n];ar.Read(str,n);UpdateAllViews(NULL);

Create a global string char * str in the document class.To create the global data click on the ClassView tabpage.Expand the tree control of classes.Select the CStoreDoc classRight click and choose add member variableSpecify the type as char and variable name as *str

4. Type this code in OnDraw() in View.cpppDC->DrawText(pDoc->str,CRect(0,0,1000,1000),DT_LEFT);

CScrollDoc* pDoc = GetDocument();

The GetDocument() function returns a pointer to the document class using which weaccess the member str defined in the document class.

5. Override OnUpdate() function in the view class.

To Override OnUpdate() function invoke the class wizard using CTRL+W. Forthe view object id click OnUpdate() under messages and then say add function.

move scrolling code from on initial update() to OnUpdate(). YourOnUpdate()function must look as given below.

OnUpdate()

{

CClientDC dc(this);

CScrollDoc* pDoc = GetDocument();

int i=dc.DrawText(pDoc->str,CRect(0,0,1000,1000),DT_CALCRECT);

Page 71: Dmc 175745

VISUAL PROGRAMMING

NOTES

71 ANNA UNIVERSITY CHENNAI

DT_CALCRECT returns the height of the rectangle containing the text and itdoesn’t draw.

// scrolling code to CScrollView

CSize sizeTotal;

// TODO: calculate the total size of this view

sizeTotal.cx = sizeTotal.cy = i;

SetScrollSizes(MM_TEXT, sizeTotal);

Invalidate(TRUE);

}

The UpDateAllViews(NULL) in the Document implementation file calls OnUpdate()function in the view class.Control gets transferred to OnDraw() due to Invalidate(TRUE).

6. Build and execute the project

7. The File dialog which is a modal dialog would be displayed.

8. Choose File Open and select a file by clicking on the file and then say open.

9. Now you’ll observe that the scroll bar is introduced and you can scroll and see allthe pages.

3.20 A PROJECT TO ILLUSTRATE MDI APPLICATION

1. Choose MDI option while creating the project using Appwizard2. Add the message WM_LBUTTONDOWN for the view object id3. Type the following coding in left button down

CMDIChildWnd *pChild = (CMDIChildWnd *) GetParentFrame();

pChild->MDIMaximize ();

CMDIFrameWnd *pParent = pChild-> GetMDIFrame();pParent->MDINext ();

4. Build and execute the project5. While you click File and then New menu item another child window will open as

given in Fig 3.3.6. This output will switch between MDI 1 and 2 when you click the left button down

GetParentFrame() will return the handle of the parent window. The address is typecast to CMDIChildWnd. The function MDIMaximize () will display the window on fullscreen. The function GetMDIFrame() will return the handle of the MDI window. Thefunction MDINEXT() displays the next MDI window.

Page 72: Dmc 175745

DMC 1755

NOTES

72 ANNA UNIVERSITY CHENNAI

Figure 3.3 MDI

If you click New continuously multiple windows keeps opening. For MDI applicationsAppwizard derives the CMainFrame class from CMDIFrameWnd.

3.21 PROJECT TO CREATE SPLITTER WINDOW1. Create a SDI application

2. Expand the class tab page3. Select the view class4. Right click and a menu pops up5. Choose add member variable.6. Type the variable as cswnd and the type as CSplitterWnd7. Handle OnCreateClient in Frm.cpp

Create(this, 2, 2, CSize(10,10), pContext);pContext is the parameter of OnCreateClient

8. Build and executeThe display would be partitioned into 2 windows as in Fig 3.4

3.22 PROJECT TO CREATE SPLITTER WINDOW AND TO WRITE

1. Create a SDI application. Call it split2. In Mainfrm.cpp include the following header files

#include “CSplitDoc.h”

Page 73: Dmc 175745

VISUAL PROGRAMMING

NOTES

73 ANNA UNIVERSITY CHENNAI

#include “CSplitView.h” #include “AddView.h”

AddView is a new class inherited from CViewTo Create AddView follow the Steps given belowExpand the class tabpageSelect the root of the treecontrolRight click and select add className the class as AddView and the base class as CView

3.In MainFrm.cpp type the followingOnCreateClient()

{CsWnd.CreateStatic(this,2,1);

// the first parameter 0 is referring to the first splitter windowCsWnd.CreateView(0,0,RUNTIME_CLASS(CAddView),CSize(100,100), pContext);// the first parameter 1 is referring to the second splitter windowCsWnd.CreateView(1,0,RUNTIME_CLASS(CSplitView),CSize(100,100), pContext);}

4. In OnDraw of both views write the coding as given below. The respective outputwill be reflected in the respective window.

5. Type the following in CSplitViewpDC->Rectangle(10,10,100,100);

6. Type the following in CAddViewpDC->Ellipse(10,10,20,20);

Build and execute the project. In one window a rectangle would be drawn andin another window ellipse would be drawn.

Page 74: Dmc 175745

DMC 1755

NOTES

74 ANNA UNIVERSITY CHENNAI

Fig 3.4 Splitter Window

3.23 MODELESS DIALOG

Dialog boxes are either modal or modeless. A modal dialog box must be closed(hidden or unloaded) before you can continue working with the rest of the application. Forexample, a dialog box is modal if it requires you to click OK or Cancel before you canswitch to another form or dialog box.

The About dialog box in Visual Basic is modal.

Dialog boxes :That display important messages should always be modal — that is,the user should always be required to close the dialog box or respond to its messagebefore proceeding.

Modeless dialog: let you shift the focus between the dialog box and another formwithout having to close the dialog box. You can continue to work elsewhere in the currentapplication while the dialog box is displayed. Modeless dialog boxes are rare. From theEdit menu, the Find dialog box in Visual Basic is an example of a modeless dialog box. Usemodeless dialog boxes to display frequently used commands or information.

Follow the steps given below to create a modeless dialog.

1. Create a SDI application.2. Create a global variable m_dlg of CDialog type. To create a global variable

click the class tabpage. Choose the view class. Right click and choose addmember variable.

3. Create a dialog resource using the resource editor.

Page 75: Dmc 175745

VISUAL PROGRAMMING

NOTES

75 ANNA UNIVERSITY CHENNAI

To create the dialog resource click on the resource tabpage.Expand the dialog resources.Select the dialog optionRight Click and choose insert from the pop up menuChoose the resource type as dialogClick new to create a new dialog (IDD_DIALOG1) given in the constructor

4. Initialise the dialog resource in the view constructor as follows:CModalessView::CModalessView(){m_dlg.Create(IDD_DIALOG1,this);}The Create function in the constructor assigns the dialog to m_dlg CDialog object5. Handle WM_LBUTTONDBLCLK message for the CModalessView object idand type the coding in bold in the handler as given below.void CModalessView::OnLButtonDblClk(UINT nFlags, CPoint point){

m_dlg.ShowWindow(SW_SHOW);}

Show Window is used for displaying a modeless dialog.

6. Build and execute the project.7. When the left button is double clicked the window is displayed. (modeless dialog)8. You can continue working with other windows.9. The modeless dialog will minimize when you work with other windows.10.On pressing Alt + Tab key simultaneously the modeless dialog is displayed.

3.24 IMAGELIST

CImageList object is a collection of same sized imgs, each of which can be referredto by its index. ImageList are used to efficiently manage large sets of icon orbitmaps.ImageList is not a control since it is not a window. They are used with severaldifferent types of controls such as list control, tree control and tab control.

Steps to create a image list

1. Create an SDI application

2. Create a CImageList object as m_ImageList by choosing class tabpage andright clicking on the CimagelistView object. Choose add member variable.

Page 76: Dmc 175745

DMC 1755

NOTES

76 ANNA UNIVERSITY CHENNAI

3. Type the coding given in bold in the constructor.

CImagelistView::CImagelistView()

{

m_ImageList.Create(32,32,TRUE,4,1);

}

The first two parameters for Create are the dimensions of each image in pixels andit is denoted as cx of type int and cy of type int. Both cx and cy are 32 in this example.The fourth parameter is the initial number of images and it is four in this case . The lastparameter is by how much it can grow and it is 1 in this case.

4. Override a user defined function Addbitmaptoimagelist.5. To override user defined function Right Click on CImagelistView . A menu will

pop up.6. Choose Add member function.7. Specify the return type in the Function type text box. Type BOOL for this example.8. In the Function Declaration type the signature of the function. That is the function

name followed by the parameter list.9. For this example type Addbitmaptoimagelist(UINT resid) in the function declaration.10. Create 4 bitmaps namely IDB_BITMAP2, IDB_BITMAP3, IDB_BITMAP4,

IDB_BITMAP5 and pass it to the function Addbitmapimagelist as parameter.11. To create a bitmap follow the steps given below.

Click the resource tabpage.Expand the resources tree controlRight click on bitmap resource.Choose insert bitmap.The editor will be displayed.Create a bitmap with the drawing tools available and save.The name of the bitmap will be automatically created.Addbitmaptoimagelist(IDB_BITMAP2);Addbitmaptoimagelist(IDB_BITMAP3);Addbitmaptoimagelist(IDB_BITMAP4);Addbitmaptoimagelist(IDB_BITMAP5);

}12 Type the coding given below in Addbitmaptoimagelist function.

BOOL CImagelistView::Addbitmaptoimagelist(UINT resid)

Page 77: Dmc 175745

VISUAL PROGRAMMING

NOTES

77 ANNA UNIVERSITY CHENNAI

{BOOL b;CBitmap bmp;b=bmp.LoadBitmap(resid);if(b != FALSE)

{b=m_ImageList.Add(&bmp,RGB(255,255,255));bmp.DeleteObject();}return b; }

The LoadBitmap member function of CBitmap is used to initialize the bitmap objectbmp. The Add member function of the CImagelist associates the bitmap with the imagelist. DeleteObject recovers the memory occupied by the gdi object, namely bitmap in thiscase.

13. Type the following coding in bold in OnDraw.void CImagelistView::OnDraw(CDC* pDC){ The parameter pDC is a pointer to a device context. If it is null the function

creates a memory device context that is compatible with the system display.CPoint pt(0,0);for(int i=0; i<4; i++)

{m_ImageList.SetBkColor(RGB(123,111,222));m_ImageList.Draw(pDC,i,pt,ILD_NORMAL);

ILD_NORMAL is the style and the images are drawn using the background color.pt.x += 50;

}}

14. Build and execute the project.

15. 4 bitmaps will be displayed side by side.

Summary

This unit has focused on the various types of VC++ projects, namely the SDI, MDIand dialog based applications. The various files of a project were introduced. The MFCclasses, appwizard and class wizard usage and how to use them has been dealt in this unit.The device context and the MFC support for device context has been covered. The GDIobjects have been introduced. Event handling, Modal and modeless dialogs have been

Page 78: Dmc 175745

DMC 1755

NOTES

78 ANNA UNIVERSITY CHENNAI

explained. The creation of Multiple Document Interface (MDI) has been explained. Thecreation of splitter window is introduced.

SHORT QUESTIONS

1. How can you paint the window with vertical lines?

Answer: By specifying the style of the brush as HS_VERTICAL we can paint thewindow with vertical lines.

CBrush(HS_VERTICAL, RGB(20,70,90));

The first parameter of CBrush specifies the style and the second parameter specifiesthe color of the brush.

2. Give examples of Modal dialog.

CColorDialog and

CFileDialog are Modal dialogs

3. Differentiate Modal and Modeless dialogs

4. Which class deals with the data of a project in VC++?

The SDI and MDI applications has the Document class in which the data membersare defined.

5. Which MFC class supports file storage and retrieval?

CArchive class provides Isstoring() member function to write to a file. The objectused for providing persistent storage is ar.

6. How will you display a file of 10 pages?

The base class must be CScrollView for the SDI application. The MFC classCScrollView will provide the data members and member functions necessary forscrolling.

Modal Dialog Modeless Dialog They are displayed using DoModal function

They are displayed using ShowWindow function

Modal dialogs should be disposed by clicking OK or cancel. Only than you can work with any other window

Modeless Dialog allows you to work with other windows and it gets minimized.

Page 79: Dmc 175745

VISUAL PROGRAMMING

NOTES

79 ANNA UNIVERSITY CHENNAI

UNIT IV

DATABASE APPLICATIONS4.1 INTRODUCTION

In this chapter, we define a dialog and tab order which is the order in which thecontrols will be navigated during execution. The dialog data exchange (DDX) mechanismto transfer data from controls to variables and vice versa is explained. Projects involvingdialog based applications are presented. Various controls such as animate control, list boxcontrol, combo control, tree control, slider control are used. The inheritance ofCtreeCtrlView to create tree control is explained. The creation of dynamic control and theassociated messages are explained. The creation of dynamic link libraries and their usageis covered. Database access using Open Database Connectivity (ODBC) is explained.Cdatabase and CrecordSet MFC classes for accessing database are covered.

4.2 LEARNING OBJECTIVES

To introduce a dialog To display the tab order using CTRL+D To visualize the dialog during design time using CTRL+T To introduce the function to achieve data transfer (DDX mechanism) To introduce the modal dialog file dialog in the context of using Animate control. To introduce OnInitDialog () function of the dialog based projects. To introduce the ListBox control and its associated methods. To introduce the ComboBox control and its associated methods. To explain how to create a calculator using a dialog. To explain how to create a Tree control using the control from the tool box. To know how to create a Tree control by inheriting CtreeCtrlView To introduce creation of controls dynamically. To use WM_SIZE and WM_CREATE messages to support dynamic controls. To introduce slider control. To create dll and an exe to use the dll To explain how to access data base using MFC classes.

Page 80: Dmc 175745

DMC 1755

NOTES

80 ANNA UNIVERSITY CHENNAI

4.3 DIALOG

A dialog is a window that contains controls. Dialog boxes are the form of input andoutput. A control can be placed on a dialog box for communicating. If you inherit CViewonly at run time you can visualize the output. Where as, using CFormView or dialogbased application you can visualize the output at design time itself. To Maximise the dialogduring execution set the following:

ShowWindow(SW_SHOWMAXIMIZED); in OnInitDialog()

In the properties of dialog set maximize and Minimise button. Otherwise only X willbe present in the upper right corner of the dialog for closing the dialog.

For a dialog based application if you use CTRL+T at design time you will see thedialog as it would be at run time. Try this option after placing the controls.

For a dialog based application if you invoke CTRL+D the tab order of the controlswill be displayed at design time.

4.3.1 Tab Order

The tab order represents the order in which the controls receive focus when the userpresses the tab key. CTRL + D can be used to set the tab order of controls. If you clickthe controls in the sequence you want, in that order the controls will receive the focus. Thisis the way to set the tab order. If you press ESC or CTRl + D, the tab order setting willbe completed.

4.3.2 DDX - Dialog Data Exchange

Data members can be associated with specific controls in the dialog box. When thedialog box is displayed, DDX will transfer the values into the dialog box controls for you.When the user dismisses the dialog box, DDX stores the values from the dialog boxcontrols in the dialog class data members.

4.3.3 Dialog Based Application

4.3.3.1 A Dialog Based Application To Illustrate Animate Control

1. Create a dialog based application.2. Design the dialog as follows.3. Place four command buttons and the Animate Control on the dialog.4. Using class wizard create a control object m_AnimateCtrl of CAnimateCtrl type.5. Set the caption of the 4 command buttons as play, stop, close and open.6. Handle button clicked event for the 4 command buttons.7. Include the coding as handler for open command button

CFileDialog File(TRUE,NULL, ,”(*.AVI)|*.AVI”,NULL);

Page 81: Dmc 175745

VISUAL PROGRAMMING

NOTES

81 ANNA UNIVERSITY CHENNAI

if(File.DoModal() != idok)return;

m_AnimateCtrl.Open(File.GetPathName());

The handler for the open command button is responsible for opening the AVI file.The function GetPathName() returns the handle of the AVI file.

8. Type the coding as handler for the play command button

m_AnimateCtrl.play(0,-1,-1);

The first parameter of play(), namely 0, denotes the beginning of the file. The secondparameter -1, tells to play the file till the end. The third parameter -1, tells to play the fileinfinitely.

9. Type the coding as handler for the stop command button

m_AnimateCtrl.Stop();

10. Type the coding as handler for the close command button

m_AnimateCtrl.Close();

The Close() function removes the memory allocated to the CAnimateCtrl object.

11. Build and execute the project

12. Click the open command button

In response the Modal dialog, File dialog would be displayed. Only thefiles with AVI extension would be displayed. Choose a file name and

click OK in the file dialog box.

13. Click the play command button

The selected file contents would be displayed

14. Click the stop command button

The selected file contents display would be stopped

15. Click the close command button

The selected file contents would be removed from the memory.

4.3.3.2 A Dialog Based Application To Illustrate List Box control

1. Develop a dialog based application.2. Design the dialog as follows. Place a list box control and two command buttons on

the dialog.

Page 82: Dmc 175745

DMC 1755

NOTES

82 ANNA UNIVERSITY CHENNAI

3. Using class wizard add a control variable m_v1 of CListBox type.4. Type the following in OnInitDialog() to initialize the list box

m_v1.InsertString(-1,”abc”);-1 in the InsertString() function is used to indicate the tail of the list.

m_v1.AddString(“xyz”);The AddString() function sorts the contents of the list box automatically.

m_v1.AddDString(“def”);5. The function GetCurSel() will return an index of the item selected from the list box.6. Handle On SelChange() function for the list box object id

m_v1.DeleteString(m_v1.GetCurSel());The function GetCurSel() will return the handle of the selected item in the list box.

This is used by Delete String to dynamically delete the contents from the list box.7. Handle Button Clicked event. Type the coding given below.

AfxMessageBox(m_v1.GetText(CString&,m_v1.GetCurSel()));The function GetText() retrieves the selected item of the list box and the message

box displays the selected item.8. Handle button clicked event for the second command button. Type the coding

given below.if(m_v1.FindString(-1,”pat”) < 0)

m_v1.InsertString(-1,”pat”);

The function FindString() searches the contents in the list box for the presence of thestring “pat” given by the second argument. If it is not present the content is inserted as a tailelement in the list box.

4.3.3.3 A Dialog Based Application To Illustrate Combo Box control

Combo box is a drop list. We can edit the contents in the combo box. If it is dropdown, we cannot edit during execution. Another category is simple combo box. Using thecombo box you can give data at design time. Using CTRL ENTER you can complete thedata entry in the combo box.

1. Develop a dialog based application.

2. Design the dialog as follows.

3. Place a combo box control in the dialog.

4. Place a command button in the dialog.

5. Add a control variable of type CComboBox for the combo box control. Namethe variable as m_v1

Page 83: Dmc 175745

VISUAL PROGRAMMING

NOTES

83 ANNA UNIVERSITY CHENNAI

6. Handle button clicked event for the command button. Type the coding given below.

AfxMessageBox(m_v1.GetLBText());

The function GetLBText() will return the selected item in the combo box.

4.3.3.4 A Dialog Based Application To Implement A Calculator1. Develop a dialog based application2. Provide three edit boxes, one command button compute, 4 radio buttons and

group them as one control.3. Using class wizard include m_n1, m_n2 and m_result the 3 integer variables for

the 3 edit boxes.4. Include a control variable object for the radio button as m_nadd5. Handle BN_CLICKED for the compute command button.

UpdateData(TRUE);switch(m_nadd)

{ Case 0:

{m_result = m_n1 + m_n2;UpdateData(FALSE);

break; }Case 1:

{m_result = m_n1 - m_n2;UpdateData(FALSE);

break; }

Case 2:{

m_result = m_n1 * m_n2;UpdateData(FALSE);

break; }

Case 3:{ if (m_n2 == 0)

AfxMessageBox(“error”,MB_OK|MB_ICONSTOP);

Page 84: Dmc 175745

DMC 1755

NOTES

84 ANNA UNIVERSITY CHENNAI

m_result = m_n1 / m_n2;UpdateData(FALSE);Break;

}

The UpdateData flag indicates whether the dialog box is being initialized or datais being retrieved.

6. Build and execute the project7. The dialog will be displayed.8. Enter 2 numbers in the 2 edit boxes.9. Click a radio button.10. Click the command button11. Depending on the radio button you have clicked the result will be displayed in the

third edit box.

4.3.3.5 A Dialog Based Application To Implement The Tree Control

Fig 4.1 Tree Control1. Develop a dialog based application.2. Place the CTreeCtrl given in Fig 4.1on the dialog.3. Set the following properties of the tree control

has linesbuttons

4. Include in the dialog header file the following variables.5. Click the class tab page. Select the dialog class. Right click and choose add

member variable from the pop up menu.variable name typem_v1 CTreeCtrlm_v2 CStringm_v3 CImageList

6. Create the image list in OnInitDialog() functionm_v3.Create(16,16,TRUE,2,1);CBitmap bmp;

Page 85: Dmc 175745

VISUAL PROGRAMMING

NOTES

85 ANNA UNIVERSITY CHENNAI

m_v3.Add(&bmp, RGB(255,255,255));bmp.DeleteObject();m_v1.SetImageList(&m_v3,TVSIL_NORMAL);

HTREEITEM one = m_v1.InsertItem(“India”,0,1);HTREEITEM two = m_v1.InsertItem(“Tn”,0,1,one);

m_v1.InsertItem(“Chennai”,0,1,two);m_v1.InsertItem(“Trichy”,0, 2,two);

7. Handle SelChanged message (TVNSELCHANGE) for the tree control Objectand type the handler given below.

HTREEITEM hndl = m_v1.GetSelectedItem();UpdateData(TRUE);m_v2 = m_v1.GetItemText(hndl);UpdateData(FALSE);

The clicked item on the tree control will be displayed in the edit box.8. Place a command button and set its caption as delete. Handle button clicked

event and include the coding given below. DeleteItem() function will delete thecontents only during execution.

m_v1.DeleteItem(m_v1. GetSelectedItem());9. Build and execute the project.

The output would be as follows. India will be the root intended by Tn and Chennaiand trichy are nested under Tn.

4.3.3.6 A SDI Application To Implement The Tree Control By Inheriting CTreeCtrlView

1. Create a SDI application.2. In Step 6 of Appwizard inherit the CTreeCtrlView as base class3. Include the variable m_v1 of type CImageList in the view header file4. Type the coding in OnInitialUpdate() in View.cpp

{ // create an image list

CBitmap bmp;

bmp.LoadBitmap(HBITMAP1);

m_v1.Create(16,16,TRUE,2,1);

m_v1.Add(&bmp, RGB(0,0,240));

bmp.DeleteObject();

GetTreeCtrl().SetImageList(&m_v1,TVSIL_NORMAL);

Page 86: Dmc 175745

DMC 1755

NOTES

86 ANNA UNIVERSITY CHENNAI

HTREEITEM one = GetTreeCtrl().InsertItem(“India”,0,1);

HTREEITEM two = GetTreeCtrl().InsertItem(“Tn”,0,1,one);

GetTreeCtrl().InsertItem(“Chennai”,0,1,two);

GetTreeCtrl().InsertItem(“Trichy”,0, 2,two);

The function GetTreeCtrl() will return an handle to the tree control. Using that handlethe manipulations on the tree control are done. In the earlier case we used a tree controlin the dialog based application. Where as, in this case the tree control is displayed in theview class.

5. Handle WM_CREATE message. In the OnCreate() function initialize the style.OnCreate (){Create(dwStyle |= TVS_HASLINES | TVS_LINESATROOT |

TVS_HASBUTTONS}

6. Handle OnSelChanged() message for the view class.CString m_v2 = GetTreeCtrl().GetItemText(GetTreeCtrl().GetSelectedItem());

AfxMessageBox(m_v2);7. Build and execute the project. If an item of the tree control is clicked, a message

box displays the selected text.

4.3.3.7 Dynamic Controls

Any control created dynamically must be initialized in On_Create() function. For thisthe WM_CREATE message must be handled. The control must be displayed in On_Size()handler. The WM_SIZE message must be handled for the view object. Now, we will seehow to create the progress control dynamically.

1. Create a SDI application. Name it as tree.

2. Select class tab page. Right click on the view class. A menu will pop up. Chooseadd member variable of the following type.

CProgressCtrl pc

CRect r

These objects will be included in view.h

3. Initialise the object in the constructor at the end of the first line of the Constructoras follows.

Page 87: Dmc 175745

VISUAL PROGRAMMING

NOTES

87 ANNA UNIVERSITY CHENNAI

tree::tree():r(10,10,20,20)

4. Handle WM_CREATE message for the view object id. Type the initializationCode given below.

pc.Create(WS_BORDER,r,this,1);

pc.SetRange(0,100);

pc.SetStep(10);

5. Handle WM_SIZE message for the view object id.

On_Size()

{

pc.SetWindowPos(&wndTop,10,10,150,30,SWP_SHOWWINDOW);

6. Handle left button down event for the view object

for(int c=0; c<100; c+=10)

pc.StepIt();

7. Build and execute the project.

Press the left button down. You will see the progress indicator. At regular intervalspress the left button down and observe the output.

4.3.3.8 Slider Control

The slider control can be used for controlling the volume of speaker or any suchapplication.

1. Create a dialog based application.2. Place the slider control on the dialog.3. Place a edit box on the dialog.4. Set the following properties by selecting the corresponding check box control.

Tickmars, Autoticks, Border, Enable Selection, horizontal, bottom / right5. Create m_v1 as CSliderCtrl. To create the variable invoke the class wizard.6. Select the CSliderctrl object id7. Select add member variable

Page 88: Dmc 175745

DMC 1755

NOTES

88 ANNA UNIVERSITY CHENNAI

8. Name the variable as m_v1 and the type as CSliderCtrl. It becomes a controlvariable.

9. Create a variable for the Edit box10. Invoke the class wizard. Press CTRL+W11. Select IDC_EDIT1 object id12. Click Add variable13. Name it as m_v2 and type as int14. Initialise in OnInitDialog()

m_v1.SetRangeMin(5,FALSE);m_v1.SetRangeMax(100,FALSE);

15. Handle Horizontal Scroll message (WM_HSCROLL) for the dialog object idOnHScroll(){

UpdateData(TRUE);m_v2 = m_v1.GetPos();UpdateData(FALSE);

}16. Build and execute the project.17. The slider control would be displayed.18. Drag the pointer on the slider control using the mouse and observe the output.19. The Positional value will be displayed in the edit box.

4.3.3.9 Another Dialog Based Application1. Design a dialog with 2 command buttons. The default names would be

IDC_BUTTON1 and IDC_BUTTON2. Name the project as dlgbut.2. Handle BN_CLICKED message for the IDC_BUTTON1 and IDC_BUTTON23. Observe the MESSAGE_MAP in dlgbutDlg.cpp4. BEGIN_MESSAGE_MAP(CDlgbutDlg, CDialog)

{ON_BN_CLICKED(IDC_BUTTON1, OnButton1)

ON_BN_CLICKED(IDC_BUTTON2, OnButton2)}

END_MESSAGE_MAP()5. In response to Step 2 the skeleton given below would be inserted. Type the coding

given in bold in the handler.

Page 89: Dmc 175745

VISUAL PROGRAMMING

NOTES

89 ANNA UNIVERSITY CHENNAI

6. GetDlgItem will return the handle of the specified control. It is typecasted to CButtontype.

7. EnableWindow(FALSE) will gray the control and deactivate it.8. When the first button is clicked it will be disabled and the second button will be

enabled.9. When the second button is clicked it will be disabled and the first button will be

enabled.10. This application behaves as a toggle.

void CDlgbutDlg::OnButton1(){ CButton *pone = (CButton*) GetDlgItem(IDC_BUTTON1);

CButton *ptwo = (CButton*) GetDlgItem(IDC_BUTTON2);pone->EnableWindow(FALSE);ptwo->EnableWindow(TRUE);

}void CDlgbutDlg::OnButton2(){ CButton *pone = (CButton*) GetDlgItem(IDC_BUTTON1);

CButton *ptwo = (CButton*) GetDlgItem(IDC_BUTTON2);pone->EnableWindow(TRUE );ptwo->EnableWindow(FALSE);

}

4.4 DYNAMIC LINK LIBRARY

A dynamic link library (dll) allows one copy of a function to be shared among severalconcurrently executing programs. A dll is a file which contains a number of modules. Afunction in a dll is connected to a program that uses it when the application is run. Eachtime the program executes the dll is connected to the program.

A dynamic-link library (DLL) is a module that contain functions and data that can beused by another module (application or DLL).

A DLL can define two kinds of functions: Exported and internal.

Exported : The exported functions are intended to be called by other modules, aswell as from within the DLL where they are defined.

Internal : Functions are typically intended to be called only from within the DLLwhere they are defined. Although a DLL can export data, its data is generally used only byits functions. However, there is nothing to prevent another module from reading or writingthat address.

Page 90: Dmc 175745

DMC 1755

NOTES

90 ANNA UNIVERSITY CHENNAI

DLLs provide a way to modularize applications so that functionality can be updatedand reused more easily. They also help reduce memory overhead when several applicationsuse the same functionality at the same time, because although each application gets its owncopy of the data, they can share the code.

The Windows application programming interface (API) is implemented as a set of dynamic-link libraries, so any process that uses the Windows API uses dynamic linking.

About Dynamic-Link Libraries

Using Dynamic-Link Libraries

Dynamic-Link Library Reference

Even though DLLs and applications are both executable program modules, they differin several ways. To the end-user, the most obvious difference is that DLLs are not programsthat can be directly executed. From the system’s point of view, there are two fundamentaldifferences between applications and DLLs:

An application can have multiple instances of itself running in the system simultaneously,whereas a DLL can have only one instance.

An application can own things such as a stack, global memory, file handles, and amessage queue, but a DLL cannot.

Advantages of Using DLLs

Dynamic linking has the following advantages: It saves memory and reduces swapping. Many processes can use a single DLL

simultaneously, sharing a single copy of the DLL in memory. In contrast, Windowsmust load a copy of the library code into memory for each application that is builtwith a static link library.

DLL saves disk space. Many applications can share a single copy of the DLL ondisk. In contrast, each application built with a static link library has the library codelinked into its executable image as a separate copy.

Upgrades to the DLL are easier. When the functions in a DLL change, theapplications that use them do not need to be recompiled or relinked as long as thefunctions’ arguments and return values do not change. In contrast, statically linkedobject code requires that the application be relinked when the functions change.

Supports multilanguage programs. Programs written in different programminglanguages can call the same DLL function as long as the programs follow thefunction’s calling convention. The programs and the DLL function must becompatible in the following ways: the order in which the function expects itsarguments to be pushed onto the stack, whether the function or the application isresponsible for cleaning up the stack, and whether any arguments are passed inregisters.

Page 91: Dmc 175745

VISUAL PROGRAMMING

NOTES

91 ANNA UNIVERSITY CHENNAI

Provides a mechanism to extend the MFC library classes. You can derive classesfrom the existing MFC classes and place them in an MFC extension DLL for useby MFC applications.

Eases the creation of international versions. By placing resources in a DLL, it ismuch easier to create international versions of an application. You can place thestrings for each language version of your application in a separate resource DLL,and have the different language versions load the appropriate resources.

A potential disadvantage to using DLLs is that the application is not self-contained; itdepends on the existence of a separate DLL module.

4.4.1 Export

The items defined as export are visible to the outside world. Functions, resources,classes can be exported from a dll.

4.4.2 Extern

The key word extern C makes the function visible for C programs also. declspec isa key word.

4.4.3 A Project To Create Win32 DLL

1. Choose Win32 dynamic link library.2. Type a project name3. Choose empty DLL project4. Click New Text File icon and save as .cpp5. Add the .cpp file to the project

extern “C++” __declspec (dllexport) double mul (float a, float b){

return a * b;}extern “C++” __declspec (dllexport) double div (float a, float b){

return a / b;}

6. Build the projectA .dll and .lib file will be created.

7. Find the path of the lib fileTo find the path click on the file and press ALT + F, then press

R or ALT + ENTER

Page 92: Dmc 175745

DMC 1755

NOTES

92 ANNA UNIVERSITY CHENNAI

8. Select View and then optionsAll the files will be displayed. (This way you can see the dll file)

Follow the steps 1 to 7 to create the dll. Next you need to create an application touse the dll. Follow the Steps given below to create the application to use the dll.

1. Choose MFC appwizard (exe). Mention the project name (dlluse).2. Choose dialog based application3. Create two edit boxes for the two inputs4. Create an edit box for the result5. Place a Command Button on the form6. Add member variables7. To add member variables invoke class wizard using CTRL + W8. Attach a member variable m_v1 of type value float to the object IDC_EDIT19. Attach a member variable m_v2 of type value float to the object IDC_EDIT210. Attach a member variable m_v3 of type value float to the object IDC_EDIT311. Handle Button Clicked event for the Command Button12. Type the following before OnInitDialog() function in the .cpp file.

extern “C++” __declspec (dllimport) double mul (float a, float b)extern “C++” __declspec (dllimport) double div (float a, float b)

13. Type the code in bold as the handler for the Button Clicked eventOnButton1(){UpdateData(TRUE);m_v3 = (float) mul(m_v1,m_v2);UpdateData(FALSE);}

14. Change the button caption to mul and div15. Type the code in bold as the handler for the Button Clicked event

OnButton2(){UpdateData(TRUE);m_v3 = div(m_v1,m_v2);UpdateData(FALSE);}

Page 93: Dmc 175745

VISUAL PROGRAMMING

NOTES

93 ANNA UNIVERSITY CHENNAI

16. To link the dll Choose Project , then Settings and choose Link17. In the obj/lib modules edit box type the path of the lib file.18. A Sample path name is given below. The lib file will always be available in the

Debug directory of the project. dll in the path name corresponds to the projectname. The project is stored in C drive under the folder Visual Studio which againhas a sub folder MyProject. Enclose the path name in double quotes so as toavoid extra characters in the path name.

“C:\Visual Studio\MyProject\dll\Debug\*.lib”19. Now Choose Rebuild All20. Drag the .dll file and drop into the debug directory of ‘dlluse’ project and execute.

dlluse is the name of the exe which will use the dll. dlluse is a dialog basedapplication.

21. A dialog with two edit boxes for input and one edit box for output would bedisplayed.

22. Also two command buttons with captions mul and div would be present in thedialog.

23. Enter the two inputs which is to be multiplied.24. Click the mul command button25. Observe the third edit box which would contain the resultant26. Execute the project once again27. Enter the two inputs which is to be divided.28. Click the div command button29. Observe the third edit box which would contain the resultant30. Both multiplication and division are performed by using the dll

4.4.4 A Project To Create MFC Appwizard DLL

1. Choose MFC Appwizard (dll) option.2. Name the project as dll23. Choose default regular dll using shared MFC4. Go to the Source file dll2.cpp5. Type the following after the declaration of the App object

extern “C++” __declspec (dllexport) CString Getdata(){Return theApp.GetRuntimeClass()-> m-lpszClassName;}

9. In the header file dll2.h include the prototypeextern “C++” __declspec (dllexport) CString Getdata();

Page 94: Dmc 175745

DMC 1755

NOTES

94 ANNA UNIVERSITY CHENNAI

10. Now build the project.11. lib file will be created12. Expand the debug directory

dll2.dll and dll2.lib files will be available.10. Get the path of the lib file.

Follow the steps 1 to 7 to create the dll. Next you need to create an application touse the dll. Follow the Steps given below to create the application to use the dll.

1. Choose MFC Appwizard (exe)2. Create a dialog based application3. Specify a project name4. Select OK button5. Place a Command button on the dialog6. Invoke the Class Wizard (Press CTRL + W)7. Handle Button Clicked event for the Command button8. Type the following before OnInitDialog() in the .cpp file

extern “C++” __declspec (dllimport) CString Getdata();9. Type the code in bold as the handler for the Button Clicked event

OnButton1(){AfxMessageBox(Getdata());}

10. Set the path of the lib by selecting Project -> Settings11. Execute after copying the dll file to the debug directory12. Click the button in the dialog.

13. The class name would be displayed.

14. The class name is got by executing the dll

4.4.5 Another Project To Create MFC Appwizard DLL

1. Choose MFC appwizard (dll) option2. Name the project as dll3. In the implementation file dll.cpp type the following

extern “C++” __declspec (dllexport) void draw(CDC *pDC){pDC->Rectangle(10,10,20,20);

Page 95: Dmc 175745

VISUAL PROGRAMMING

NOTES

95 ANNA UNIVERSITY CHENNAI

}4. In the dll.h file include the prototype given below

extern “C++” __declspec (dllexport) void draw(CDC *pDC);5. Build the Project6. dll and .lib files would be created7. Find the path of .lib file.

Develop an exe to use the dll created by following the above steps.1. Develop a dialog based application.2. Place a Command Button on the dialog.3. Handle Button Clicked event for the Command Button4. Type the coding in bold as the handler

OnButton1(){CClientDC dc(this);Draw(&dc);}

5. Type the following before OnInitDialog() in the .cpp fileextern “C++” __declspec (dllimport) void draw(CDC *pDC);

6. Specify the path of the dll byChoosing Project, Settings and link tab page

7. Move the .dll file to the debug directory of the dialog based application.8. Build and execute the project.9. Click the button and observe that the rectangle would be drawn.10. The rectangle is the resultant of the dll.

4.5 ODBC

The ODBC provides an API that differentiates data base vendors implementationvia ODBC drivers specific to a DBMS. The program will use this API to call theODBC driver manager, which passes the calls to the respective driver. The driver interactswith the DBMS using Structured Query Language (SQL).

4.5.1 Record Set

The record set represents the records in a base table or the records retrieved due toa query. The record set falls into 3 categories. They are table type record sets, dyna settype record sets and snap shot type record sets.

Page 96: Dmc 175745

DMC 1755

NOTES

96 ANNA UNIVERSITY CHENNAI

4.5.1.1 Table Type Record Sets

Table type record sets represents a base table in a Microsoft Jet data base.

4.5.1.2 Dyna Set Type Record Sets

Dyna set type record sets are the resultant of a query.

4.5.1.3 Snap shot Type Record Sets

Snap shot type record sets represents a static copy of the records.

4.5.1.4 Data Source

Data source is a specific instance made up of the 4 components.

1. Database which contains the data2. A DBMS3. The Operating system and the environment where the data resides4. A network connection that allows access to the data source.

The database related projects are made up of MFC database classes. The ODBCdriver manager using the driver interacts with the database as given in Fig 4.1.

Figure 4.1 Working of a Database Application

APPLICATION

|

|

MFC Database Classes

|

|

ODBC Interface

|

|

ODBC Driver Manager

|

|

DRIVER

|

|

DATA SOURCE

|

|

DATBASE

Page 97: Dmc 175745

VISUAL PROGRAMMING

NOTES

97 ANNA UNIVERSITY CHENNAI

4.5.2 Cdatabase Class

The CDataBase class helps to connect to a data source. The Open member functionopens a connection to the data source. The CRecordset class is used for performingmanipulation on the connected data source. The Close member function destroys theCDatabase object. It also closes any record sets that have not been previously closed.

4.5.3 Executesql

The ExecuteSQL is used for executing query on the database. The CRecordset usesthe RFX mechanism to exchange data between field data members of the record setobject and corresponding table columns of the data source. Record sets enable scrollingfrom record to record, updating records (addition, edit, deletion).

4.5.4 Enabling ODBC1. Choose programs, setting, control panel and then ODBC322. Double click on ODBC323. Settings for the operating system will occur.4. Select user tab page5. Click ADD6. Select Microsoft ODBC driver for ORACLE7. Click finish8. Another dialog appears

It asks for DSN, Description, username, passwd and connect string.9. After giving the values in Step 8 click ok.

4.5.5 A Project To Manipulate The Contents Of The DataBase

1. Create a dialog based application.2. Expand the class tab page.3. Select the dialog class4. Right click and a menu pops up.5. Choose add member variable6. Type the variable type as CDatabase and the pointer variable name as *pDatabase7. Type

#include <Afxdb.h> in stdafx.h8. Type the following in OnInitDialog()

TRY{

pDatabase = new CDatabase;

Page 98: Dmc 175745

DMC 1755

NOTES

98 ANNA UNIVERSITY CHENNAI

pDatabase.Open(“ODBC; DSN= “ );}

CATCH(CMemoryException, e){e->ReportError();}

CATCH(CDBException, e){e->ReportError();}

END_CATCH

9. The DSN in Step 8 should be the same as the one you used for initializing ODBC.TRY and CATCH are used for exception handling.

10. Design the dialog as follows. Place an edit box and a command button on thedialog. Associate a CString object with the edit box (m_v1).

11. Handle button clicked event for the command button.OnButtonClicked()

{UpdateData(TRUE);TRY

{ pDatabase->ExecuteSQL(m_v1);}CATCH(CDBException, e){e->ReportError();}

END_CATCHUpdateData(FALSE);}

Type the SQL command in the edit box. You can use insert, delete , update data andapply create command only. No select operation is possible using CDatabase object. Itdoesn’t do any retrieval. The command is stored in m_v1, which is passed as parameter toExecuteSQL() function.

Page 99: Dmc 175745

VISUAL PROGRAMMING

NOTES

99 ANNA UNIVERSITY CHENNAI

4.5.6 A Project To Display The Contents Of The DataBase

1. Create an SDI application2. Choose the header files in second step of Appwizard3. Inherit CFormView or CSrollView in the 6th Step of Appwizard in creating the

project.4. Create a new class CDataSet with base class as CRecordSet

(before this you should create or decide the table to be used and create or choosethe DSN). For the selected table configure and create record set.

5. Add a data member in the Document class for the new class CDataSet asFollows

Choose the class tab page and expand it, select the document class, right clickand select add member variable from the pop up menu.

Name the variable as m_set and the type as CDataSet

6. Declare a pointer for CDataSet in view classChoose the class tab page and expand it, select the view class, right click andselect add member variable from the pop up menu.Name the variable as *m_pset and the type as CDataSet

7. Override OnInitialUpdate()OnInitialUpdate()

{m_pset = &(GetDocument()->m_set);if (m_pset -> ISOpen())

{if(m_pset->GetRecordCount() > 0 )m_pset->MoveFirst();

}else{m_pset->Open();}}

8. Override draw()

Type the coding given below

int x=0,y=0;

Page 100: Dmc 175745

DMC 1755

NOTES

100 ANNA UNIVERSITY CHENNAI

if(m_pset->GetRecordCount() > 0)m_pset->MoveFirst();

elsereturn;

while (!m_pset->IsEOF()){ // NAME, AGE, DESG are the fields of the tablex=0;

pDC->TextOut(x,y,m_pset->M_NAME);pDC->TextOut(x += 50,y,m_pset->M_AGE);pDC->TextOut(x += 50,y,m_pset->M_DESG);

m_pset->MoveNext();y += 20;}

9. build and Execute10. Place 4 command buttons on the dialog11. Name them as HOME, END, PREV and NEXT12. Handle button clicked for the PREV button. This will display the previous record.

On button(){CClientDC dc(this);int x=y=80;m_pset->MovePrev();

dc.TextOut(x,y,m_pset->M_NAME);dc.TextOut(x += 50,y,m_pset->M_AGE);dc.TextOut(x += 50,y,m_pset->M_DESG);

}13. Handle button clicked for the NEXT button. This will display the next record.

On button(){CClientDC dc(this);int x=y=80;m_pset->MoveNext();

dc.TextOut(x,y,m_pset->M_NAME);dc.TextOut(x += 50,y,m_pset->M_AGE);dc.TextOut(x += 50,y,m_pset->M_DESG);

Page 101: Dmc 175745

VISUAL PROGRAMMING

NOTES

101 ANNA UNIVERSITY CHENNAI

}14. Handle button clicked for the HOME button. This will display the firstrecord.

On button(){CClientDC dc(this);int x=y=80;m_pset->MoveFirst();

dc.TextOut(x,y,m_pset->M_NAME);dc.TextOut(x += 50,y,m_pset->M_AGE);dc.TextOut(x += 50,y,m_pset->M_DESG);

}15. Handle button clicked for the END button. This will display the last record.

On button(){CClientDC dc(this);int x=y=80;m_pset->MoveLast();

dc.TextOut(x,y,m_pset->M_NAME);dc.TextOut(x += 50,y,m_pset->M_AGE);dc.TextOut(x += 50,y,m_pset->M_DESG);

}16. Build and execute the project.17. Clicking the HOME button will display the first record contents.18. Clicking the END button will display the last record contents.19. Clicking the PREV button will display the previous record contents from the current

position.20. Clicking the NEXT button will display the next record contents from the current

position.

4.5.7 Container Class

1. Create a project using appwizard2. choose the container option3. Due to the container option CntrlItem class will be included in your project.4. Build and execute the project.5. Choose edit and insert object

Page 102: Dmc 175745

DMC 1755

NOTES

102 ANNA UNIVERSITY CHENNAI

6. You can choose bitmap or wordpad or any other option.

7. If it is a bitmap draw some picture and save.

8. It would be saved as part of the project

9. If you choose the file open option and select the newly saved bitmap it would bedisplayed.

4.5.8 Summary

A dialog is a window which houses controls. It has properties such as maximize,minimize buttons. A project has been covered to display AVI files using the CanimateCtrl.Open (), Stop (), Close () and Play () methods have been used for effectively displayingAVI files. InsertString (), AddString (), GetCurSel(), DeleteString () functions of the listbox control are explained. The message WM_SELCHANGED has been handled to reflectchanges in the list box control. A calculator has been developed using a dialog. The filemanager is displayed using a tree control in general. How to design the tree control byinheriting CtreeCtrlView is explained. The creation of dynamic controls and their associatedmessages are explained. The usage of slider control is explained. How to create a dll andhow to use it has been covered. Displaying, updating, deleting and inserting into a databasehave been explained.

Page 103: Dmc 175745

VISUAL PROGRAMMING

NOTES

103 ANNA UNIVERSITY CHENNAI

UNIT V

GUI DESIGN AND FILE HANDLING

5.1 INTRODUCTION

As you know the aim of the user interface design is to achieve the user’s goals. Whenthe user’s goals are met, the user is satisfied and the user interface design software will bea success. The user’s goals differs from what we would guess. For instance, from a clerk’spoint of view, he would not want to make mistakes and he would want volume of workto be done. These would be the goals from the clerk’s point of view. Whereas, theorganization’s goal may be efficient processing.

User interface design focuses on what the software will look like and how it willcommunicate with the user.

5.2 LEARNING OBJECTIVES

To introduce the features that should be avoided in the graphical user interface To know what is meant by software that is rude To know what makes a software obscure To know what is software with inappropriate behavior To study the three models for the user interface design To study about visual interface design To study about the file system To study the storage and retrieval system To study about simultaneous multi platform development

5.3 BASICS OF GUI DESIGN

Next we will see what features need to be avoided in the graphical user interface.The issues to be addressed are

Software that is rude Software that is obscure Software with inappropriate behavior Features of user interface design The three models of user interface design

Page 104: Dmc 175745

DMC 1755

NOTES

104 ANNA UNIVERSITY CHENNAI

5.3.1 Software That Is Rude

As we all know, software warns the user for making mistakes. Message boxespop up indicating the mistake and the user will have to click the OK or CANCEL buttonto dispose off the Message Box. This is because the developer of the software assumesthe user of the package will be a computer literate.

Yet another instance is after we edit a document and close it, the word processorwill ask whether it should be stored. Similarly, questions such as ‘Are you Sure’ ‘Did youreally want to delete’ are also irritating. The user may not be prepared to answer suchquestions. The user interface design should avoid such confirmation interface which leadsto concluding that the software is rude.

5.3.2 Software That Is Obscure

Software hides the meaning, intensions and actions from the user. For example, if auser is asked whether a full installation, custom installation or laptop installation is required,the user may not be able to decide the kind of installation. If the user is given informationin terms of the functionality of each installation or the disk space requirement, the user canchoose what kind of installation he needs. But generally the software hides these factors.

5.3.3 Software With Inappropriate Behavior

You would save a document, print it, then you’ll attempt to close it. The program willask you if you want to save. This is because, the software thinks the printing operationwould have made modifications.

The designer of the user interface should ensure, that the software is not rude, is notobscure and the inappropriate behavior should be avoided.

5.4 FEATURES OF USER INTERFACE DESIGN

The features such as how will the software be used? Who will be the users? What willbe the life of software? During its lifetime how frequently will the software be used? Theseare some of the issues to be addressed by the software developer. The help associatedwith the software on how to use it should be easy to learn and the software should achievethroughput. Good design will make the user more effective. The designer has to choosewith its ease or effectiveness that matter. For instance, a software meant to guide thevisitors in a campus should aim for ease of use. If it is easy to use only visitors will use thesoftware to locate spots in the campus. Where as, some software need to be only effective.For instance, if a software is developed to distinguish enemy flights and friendly flights, itmust be effective in identifying enemy flights. If it wrongly identifies friendly flights asenemy flights the software fails. So, the designer should choose depending on therequirement whether ease of use or effectiveness should be satisfied. The problems to betackled during design are as follows:

Page 105: Dmc 175745

VISUAL PROGRAMMING

NOTES

105 ANNA UNIVERSITY CHENNAI

What should be the form of the program? How will the user interact with the program? How can the program’s function be most effectively organized? How will the program introduce itself to first time users? How can the program put an understandable and controllable face on technology? How can the program deal with problems? How will the program help infrequent users become more expert? How can the program provide sufficient depth for expert users?

5.5 THE THREE MODELS FOR THE USER INTERFACE DESIGN

The three models for the user interface design are the implementation model, mentalmodel and the manifest model.

5.5.1 The Implementation Model

How the program is to be designed will be already given.

5.5.2 The Mental Model

This model resembles the user’s view. If reasoning and logic is incorporated in themanifest model it becomes an implementation model. But it would result in a bad interface.

As we know, in Adobe Photoshop, to adjust the color, a series of small sampleimages with a different color balance is displayed. The user can click on the specific imageto choose a specific color. Since the user is thinking in terms of colors, it resembles theuser’s view. So it follows the mental model. This is an example for the mental model.

5.5.3 The Manifest Model

The way the designer chooses to render the program is the manifest model. Thismodel can be changed. If the logic is abandoned in rendering, than the manifest model willcreate a good interface. This is because it follows user’s imagination.

5.5.4 Mathematical Thinking

The interface designer must shield the user from the implementation models used inconstructing the software. The data structures and algorithms for representing andmanipulating information are based on mathematical models. Recursion, hierarchical datastructures and multi-threading are used in designing user interface. Boolean Algebra isused in describing on or off conditions. To achieve this ‘AND’ and ‘OR’ operators areused. The users confuse the logical AND and OR with the AND and OR in the Englishlanguage. An instance of this confusion is encountered in the context of querying databases.For instance, if we want to find all the students of MCA of distance education mode and

Page 106: Dmc 175745

DMC 1755

NOTES

106 ANNA UNIVERSITY CHENNAI

regular mode, we would say, display the students in DMCA or RMCA. This is in thecontext of Boolean algebra because a student will not study both in DMCA and RMCA.In Boolean Algebra context if we say DMCA and RMCA, only null will be returned,because no record will match this condition.

Where as, Using English language to mean the same we would say, display studentsof DMCA and RMCA. This would mean display students studying in DMCA and RMCA.

Another example of the difference in usage of AND and OR in English and the logicalAND and OR is in the context of wanting students born in the month of March and May.In English we would say display the students born in March and May. Where as, usinglogical OR we will say display the students born in March OR May.

The user interface should avoid Boolean Algebra since they confuse the use oflogical AND and OR, with the use of AND and OR in English language.

5.6 VISUAL INTERFACE DESIGN

Rather than the graphic nature of the program, the visualness of the inter action only isimportant. The program should not focus on GUI. On the other hand it should concentrateon the visual user interface (VUI). The software that recognizes VUI is the visual interfacedesign.

5.6.1 Visual Processing

Our mind groups things into patterns and this enables us to process visual information.Understanding and applying how the human mind process visual information is the keyelement of visual interface design. The aim is to present the program’s components on thescreen as recognizable visual patterns with accompanying text as a descriptive supplement.

5.6.2 A Visual Interface Is Based On Visual Patterns

The visual user interface must create recognizable patterns and text will be used fordistinguishing objects with similar patterns. Patterns are created by simple recognizablegraphic symbols and value is given to them by association. Visual interface design createssymbols for the objects in the interface. If the program created manages a class room, youknow that, tables, chairs, fans, lights, boards, chalk are the fundamental elements. Theyform the building blocks for creating the interface. A recognizable visual symbol is neededfor these fundamental elements. For instance Chairs, Tables, Fans, Lights and Boardscould be represented as given in Fig 5.1.

Page 107: Dmc 175745

VISUAL PROGRAMMING

NOTES

107 ANNA UNIVERSITY CHENNAI

Figure 5.1 Symbols Representing The Elements of A Class Room

The symbols should be used to represent the objects on the screen in all places. If theobjects are represented as a list box, the symbols only should be present in the list box torepresent the objects. Whether it be a dialog box, text or a tool bar the symbol only shouldbe used to represent the object.

5.6.3 Restricting The Vocabulary

A properly formed vocabulary is like an inverted pyramid. All easy to learncommunication system obey this pattern.

|---------| Chairs

--------------------------------------- ||| ||| Tables || || Fans

X

|| lights || ******

|-----|------| Boards

Page 108: Dmc 175745

DMC 1755

NOTES

108 ANNA UNIVERSITY CHENNAI

Figure 5.2 The Canonical Vocabulary

The canonical vocabulary in Fig 5.2 is comprised of the idioms, compounds andprimitives. Idioms combine compounds with knowledge of the problem known as domainknowledge. Application specific commands and feed back forms the idioms. The input atthis level would be commands such as delete, create and draw. The expected outputwould be a scrolling effect, sorted output or dialogs.

The next level is the compounds. They represent the complex constructs created bycombining one or more of the primitives. It is comprised of generic input and outputactions and symbols. The input at this level in the GUI context would be actions such asdouble clicking, clicking the button and manipulating the objects such as push button andcheck box. The target controls would be edit fields and check box. Highlighting would bea possible output at this level.

The next level is the primitives. It is comprised of the smallest indivisible actions andfeed back mechanisms. They form the atomic elements of which every thing in the languageis comprised. The input at this level would be commands such as click, drag or key press.The expected output would be on the cursor and text. When the user interface designfollows the canonical vocabulary it will be a success.

5.7 FILE SYSTEM

The file system manages information that is not in main memory by maintaining asecondary copy on disk. The various functions of the file system are

Input ______________________________________________________ Output

Delete

Draw Idioms Scrolling

Create Application Specific Commands and Feedback Sorting

Dialogs

_____________________________________________

Double Compounds Edit Fields

Click Checkbox

Button click Generic Input and output Highlighting

Selection actions and symbols

_____________________________

Primitives

Smallest indivisible actions

Click and

Drag feed back mechanisms Cursor

Key Press Text

Page 109: Dmc 175745

VISUAL PROGRAMMING

NOTES

109 ANNA UNIVERSITY CHENNAI

Saving Archiving Document Management Creating a copy of the document Naming and renaming the document Placing and repositioning the document Specifying the stored format of the document Reversing some changes Abandoning all changes Creating a milestone copy of the document.

5.7.1 Saving

It is maintaining a secondary copy on disk. An important function of the file system ishow to save a file. This option will write the changes made to the in memory copy on to theon disk copy of the document. The program will automatically save the document. Whenthe user requests the close function, the program will write the changes to the disk. Theprogram must also save the document at intervals during the user session. This is because,due to power failure, changes will be lost before you have pressed CLOSE. The SAVEdialog is forced on all users when they close the document or QUIT or EXIT the program.

5.7.2 Archiving

For making a copy or archiving a document, Save As dialog is used.

5.7.3 Document Management

The following functions are required for document management. They are

Creating a copy of the document Creating a mile stone copy of the document Naming and renaming the document Placing and Repositioning the document Specifying the stored format of the document Reversing some changes Abandoning all changes

5.7.3.1 Creating a copy of the document

This function makes an identical copy of the original and the copy is not related to theoriginal in any aspect. Subsequent changes to the original will have no effect in the copy.

5.7.3.2 Naming and renaming the document

The name of the document should be shown on the application’s tool bar. If the userdecides to rename the document, the user can just click on it and edit it in place.

Page 110: Dmc 175745

DMC 1755

NOTES

110 ANNA UNIVERSITY CHENNAI

5.7.3.3 Placing and Repositioning the document

Most documents that are edited already exist. They are opened and not createdfrom scratch. The position in the file system is fixed. If the user wants to explicitly place thedocument some where in the file system hierarchy, a dialog similar to Save As dialogappears with the current document high lighted. The user can then move the file to anydesired location. This dialog is used for repositioning them.

5.7.3.4 Specifying the stored format of the document

The Save As dialog offers an additional function. It has a combo box using which theuser can specify the physical format of the file. The physical format could be rich text,ASCII or word format. The format is a characteristic of the document rather than of thedisk file. Therefore, format specification shouldn’t be associated with the act of saving thefile to disk. The physical format of the document should be specified by way of a smalldialog box callable from the main menu.

5.7.3.5 Reversing some changes

There should be a function to reverse the changes made to the document. Undo is thetool to reverse the changes made to the document. The file system should be the mechanismfor supporting the function, but it should not be rendered to the user in those terms.

5.7.3.6 Abandoning all changes

If the user wants to discard all of the changes he has made since opening or creatinga document, this action should be supported. A abandon function on the main menu wouldbe sufficient to achieve this. This function would involve significant data loss. Therefore, itshould have warning alert boxes like ‘Do You Really Want to Abandon All The Changes’.

5.7.3.7 Creating a milestone copy of the document.

Making a milestone is similar to the copy command. The difference between copyand mile stone is that the mile stone copy is managed by the application after it is made.The user can use the mile stone dialog box which will list each mile stone copy along withvarious statistics about it, such as the time it was recorded and its length. With a click, theuser can select a mile stone copy and use it as the active document.

5.8 STORAGE AND RETRIEVAL SYSTEMS

The storage system is a repository. It is a physical container and provides mechanismsto put in the repository and take them back. The retrieval system is a method for findingthings in a repository. It is a logical system that allows the goods to be located according tosome abstract value like the name, position or based on the features of the contents.

Page 111: Dmc 175745

VISUAL PROGRAMMING

NOTES

111 ANNA UNIVERSITY CHENNAI

5.8.1 Retrieval Methods

There are three ways to find a document. The first method is positional retrieval. Thisis achieved by remembering where you left it. The second method is identity retrieval. Youcan retrieve by remembering its identity name. The last method is associative retrieval. Thisis searching based on some features of the document.

For instance, if you want to find a book on Visual Programming, or a book containingphotographs of cricketers, the method should be associative retrieval.

The positional and identity retrieval also functions as storage systems. If the retrievalsystem is based on storage methods, then associative retrieval is not possible in this case.The user will have to know where the content is stored and also by what name it is stored.

5.8.2 Indexing

In libraries, the card catalog is the index. Three indices are used in the library. Author,Subject and title are the three indices. Each index is associative. The index allows the userto find the book according to a feature of the book. Apart from the feature the indices alsogive the number or the location of the book.

To search for a book, we look into any of the indices and find the number. With thisnumber, we can locate the shelves containing books in the range of the number we aresearching for. After the particular shelf is located, following the lexical order of the number,we locate the book.

Physically, the book is retrieved from the system of storage. Conceptually, the bookis found logically from the system of retrieval. The shelves and numbers are the storagesystem. The card indices are the retrieval system. The books are identified with one systemand retrieved with the help of another system. The customer identifies the book by usingthe retrieval system. The librarian retrieves the book by using the storage system. Theretrieval system are also based on associative search. If the associative retrieval systemremembers facts such as

The program that created the document The type of document – whether the document is word or graphics The program that last opened the document If the document is exceptionally large or small. If the document has been untouched for a long time For how long the document was last open The amount of information that was added or deleted during the last edit Whether the document has been edited by more than one type of program Whether the document contains embedded objects from other programs Whether the document was created from scratch or cloned from another

Page 112: Dmc 175745

DMC 1755

NOTES

112 ANNA UNIVERSITY CHENNAI

If the document is frequently edited If the document is frequently viewed but rarely edited Whether the document has been printed and where How often the document has been printed, and whether changes were made to it

each time immediately before printing Whether the document has been fixed and to whom Whether the document has been emailed and to whom

The retrieval system could find the documents using the above stated facts.

5.9 SIMULTANEOUS MULTI PLATFORM DEVELOPMENT

Develop the code for the primary market. Use the revenue from this product toport to the secondary platform. There are two ways for simultaneous multi platformdevelopment. The code can be made complicated or the interface can be homogenized.

5.9.1 Complicating The Code

Anything that increases the complexity of source code should be avoided. It willconsume time for writing the complicated code as well as for debugging. The softwaredeveloper manager should avoid uncertainty and delay. “If – Else” statements can beadded to the source code to support an extra hard ware platform. Software developmentbecomes harder and more complex. Every design decision must be made for two platforms.

Commercial libraries of code are available which supports development on multipleplatform simultaneously. To achieve multiple platform development, GUI is designedgenerically. This would be easy for the development team. The users would not preferthis. For instance, Macintosh users would prefer programs with a MAC sensibility.Windows users will want a Windows application. Windows user would like multiple,complex tool bars running horizontally across the top of the program just beneath themenu bar.

First, you develop for a single platform. Mostly, it will be Windows, which will be themain market. Avoid the complexities of multi platform development. Once you finish thefirst version with the maximum speed possible, ship it to the largest possible market. Nowyou would generate revenue while you start development for the second platform. Singleplatform development is the correct course of action. The needs of secondary marketsshouldn’t delay the needs of primary markets. Now a working model of the productrunning on Windows is available. This could serve as a prototype for the versions to run onother platforms. A team of programmers can be employed to clone the Windows product.Since the design is already available, the development time can be reduced. Even the costinvolved can be reduced by hiring less experience programmers because negligibledesign work would be involved. The functionality alone will be cloned, but not the dialect.The Windows proto type will demonstrate how the program should inter act with the user,

Page 113: Dmc 175745

VISUAL PROGRAMMING

NOTES

113 ANNA UNIVERSITY CHENNAI

where as the Macintosh version must behave like a Mac program at the detail level. Forachieving this, local expertise is needed.

5.9.2 The Myth of Interoperability

Generally, Windows programmers have to port DOS legacy programs. The programsin DOS would be character based and it would be in command line environment. TheWindows program should emulate the DOS program as closely as possible. When DOSprogram is converted to Windows, The DOS users would be disappointed if the programis different from what they already know. The corporate users work in heterogeneousenvironments and they want the Windows version to work the same way as their DOSsystem. This is interoperability. Followers of interoperability feel that DOS customers aresatisfied with the Windows equivalent because of the way the Windows equivalent programbehaves. The organization also would not like to invest in training on Windows platform asthey have already been trained on DOS. So, the organization need not invest on training,since the Windows product resembles the DOS product.

5.10 SUMMARY

This unit addresses GUI design and file handling. The characteristics that should beavoided in the software implementing user interface design were discussed. Obscurecharacteristics and inappropriate behavior should be avoided. The implementation model,mental model and the manifest model to implement user interface design are presented.The canonical vocabulary was introduced. The various file system functions such as saving,archiving and document management was covered. The associative, positional and identityretrieval systems were introduced.

Page 114: Dmc 175745

DMC 1755

NOTES

114 ANNA UNIVERSITY CHENNAI

NOTES