You are on page 1of 114

VISUAL PROGRAMMING

UNIT I

NOTES

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 Microsofts Visual Basic.

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

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 command button 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 naming convention. 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 hand notation 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 the screen, to memory and printers. So the programmer need not know anything about the video 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 Device Context). 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. The client 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 to enable transition from 16 bit to 32 bit system. Some of the new data types are HINSTANCE, 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 window MSG 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

ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

When Windows was 16 bit WPARAM was a WORD which was a 16 bit unsigned short integer and LPARAM was LONG which was a 32 bit signed long integer. So only the 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 the various resources The resources are compiled by a resource compiler. The linker will bind object (*.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 cursor is a blinking rectangle or an underline symbol. On Windows it could be an I-beam or an arrow. 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 icon causes 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. The bitmapped 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 symbol is a tool bar for saving. They will be associated with corresponding menu items. A toolbar is a window that contains a row of command buttons. Clicking the button will issue a predefined command. For selecting a menu item you can click a toolbar corresponding to the 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. They wait for the system to pass input to them. The system passes input to the various windows in the application. Each window has a function, the window procedure, which is called by the system whenever it has input for the window. The window procedure processes the
3

NOTES

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

input and returns control to the system. The system passes input to a window procedure in the form of messages. Messages are generated by both the system and applications. The system generates a message for each input event for example, when the user types, moves the mouse or clicks a control such as a list box. The system also generates messages in response to changes in the system brought about by an application, such as when an application resizes one of its windows. An application can generate messages to direct its own windows to perform tasks or to communicate with windows in other applications. When a window procedure receives a message, it uses a message identifier to determine how to process the message. The message identifier WM_PAINT tells the window procedure that the windows client area has changed and must be repainted. WM is for general window messages. 1.5.1 Message Routing The system posts messages to a first-in, first-out queue called a message queue or it sends messages directly to a window procedure. Messages posted to a message queue are called queued messages. They are the result of user input entered through the mouse or keyboard, such as WM_RBUTTONDOWN , WM_KEYUP. Messages, sent directly to the 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 sends nonqueued messages to notify a window of events that affect it. For example, when the user activates a new application window, the system sends the window WM_ACTIVATE, WM_SETFOCUS and WM_SETCURSOR messages. These messages notify the window that it has been activated, that keyboard input is being directed to the window, and that the mouse cursor has been moved within the borders of the window. Nonqueued messages occur when an application calls certain system functions. For example, the system sends the WM_WINDOWPOSCHANGED message after an application uses the SetWindowPos function to move a window. 1.6 DOCUMENT INTERFACES Single document interface (SDI) and Multiple document interface (MDI) are the document interfaces. MDI based applications can have several child windows under one parent 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 in the computer. DLL files that support specific device operation are known as device

ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

drivers.The advantage of DLL files is that, space is saved in RAM since they dont get loaded 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 to be loaded into RAM. When the user decides to print the document, then the Word application 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 them during 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 with that state.Context-sensitive help can be implemented using tooltips which display a complete topic from the help file. 1.9 WINDOWS 32 BIT (WIN 32) APPLICATIONS Win 32 based applications are the applications developed for the windows family of operating systems. Win 32 applications respond to events. They are composed of Win 32 Application Programming Interface (API) which are DLLs. The Win 32 API is a collection of function calls, data structures and messages. The Win 32 API are written in C. The Win 32 based program uses Win 32 API to interact with the windows based operating system. The Operating System responds to the programs using the 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

NOTES

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

1.10 ARCHITECTURE OF WIN 32 PROGRAM

Hardware Events | | | | System Queue | | | | -------------------------------------------------------------------------| | Application Message Queue | Message loop | | | Window Proc | | Default Wnd Proc
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 events are stored in the system queue and it is dispatched to the appropriate message queue of the application. Every program will have the message loop which will retrieve the events from the queue and call the window procedure which will contain the handler. If the handler is not incorporated in the application the default window procedure will be called. The default window procedure Default Wnd Proc in Fig 1.2 implements the behaviors such 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 which directly interact with the hardware. So the execution of SDK programs are fast. A sample SDK program for displaying a window is given. MSG is a structure. CreateWindow, ShowWindow, UpdateWindow are examples of SDK functions. HWND is a handle to the window. The created windows address is stored in hWnd. The first parameter button is the class name. The second parameter hello is the window name. BS_PUSHBUTTON
6 ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

is the style. BS stands for button style. The next 4 parameters indicate the size of the window. The 8th parameter indicates that the created window has no parent. The next parameter indicates that there is no menu. ShowWindow displays the window. #include <windows.h> int WINAPI Winmain(HANDLE hInstance, HANDLE hprevInstance, LPSTR lpszCmdLine, 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 messages from the applications message queue and passes these to the associated window procedure. The messages are retrieved in FIFO (First In, First Out order). The code snippet above illustrates the message loop. The message received for the window denoted by hWnd is read and stored in the structure msg. The functions TranslateMessage and DispatchMessage 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. The messages have been introduced and some messages have been explained. Dynamic link library has been covered. A program has been incorporated to illustrate window creation. The message loop is also explained.

NOTES

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

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 native Win32 application interface (API) or C++ and the class libraries such as Microsoft Foundation Classes (MFC) or Microsofts 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 clicking the command button. 4. Event-driven programming allows the program to respond to different inputs or events. 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 board events 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.

ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

10. Accelerators are short cut keys. It is a key combination such as Alt+F9 to activate a task. 11. The different kinds of messages are Queued messages and Non 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 dont get loaded into the 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.

NOTES

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

10

ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

UNIT II

NOTES

CONTROLS AND TOOLBARS


2.1 INTRODUCTION Visual Basic programming is event driven programming. In a form objects called controls are placed. We can set the properties of the controls and associate events with the control. Accelerators are short cut keys. Tooltips are messages that would be displayed when the mouse is positioned on the control. How to associate accelerators and tooltips with the controls are explained. A project comprising of command buttons and text box is presented. Some of the events associated with these controls are handled. The usage of controls such as list box and combo box are introduced. The inclusion of menus and tool bars in a project are explained. The various files, data types, control statements associated with a Visual Basic project are explained. You can add modules to your project and you can control the startup object which will be the starting point for execution. These features are incorporated in 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.
11 ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

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, Combo box, 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 the properties associated with controls. 2.3.1 Properties Every control has a default property associated with it. The default property need not be named when you are working. The control Check box as value has the default property. The control Combo box as text has the default property. The control image as picture 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 be changed programmatically. They can be set only at design time. For instance name of a control 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 property window. As a result in the drop down list of the property window the control will be listed as add Command Button. For changing the caption of a label control, set the caption property 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 to a user action such as a mouse click or a key press.

12

ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

2.3.3. Accelerators Accelerators are short cut keys. Accelerators are created by placing an ampersand before any of the characters of the Caption. As a result the letter following the ampersand will be underlined. The underlined letter along with the ALT key should be used to activate the Control. Pressing the ALT key and the corresponding letter key is equivalent to clicking the 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 as Command2. To activate the Command2 button you either click on the Command2 button or press ALT and C together. 2.3.4 ToolTip The ToolTip property is used to flash a message about a control object when the mouse pointer moves over that object for a couple of seconds. Select a control and click F4 key to navigate to the property window of that control. To set tooltip move down to ToolTips property and double click in the space to the right of ToolTips property. Then type the message without quotation marks. Execute your program by using F5(short cut method) or use the Run option in the menu. Place the mouse over the control for which you have set the tooltip and the tooltip message would be flashed. Tooltips are used to indicate for 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. 2. 3. 4. 5. 6. 7. Open Visual Basic 6.0. Choose a Standard .exe project. Maximize the form by clicking on the middle maximize button. Choose View option and click project explorer. Click on the project name to select it. Right click and choose properties. Type the project name you want.

NOTES

13

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

2.4.3 Placing the text box on the form 1. 2. 3. 4. 5. Select the text box control inside the tool box to the left of the work area. Double-clicking on the text box places the text box onto the form. Size the text box control using the resizing handles. Drag the control to place it on the form using the left mouse button. 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. 2. 3. 4. 5. 6. Place the 3 command buttons on the form. Set the caption for the first command button as &hello. Set the caption for the second command button as &clear. Set the caption for the third command button as &exit. Add events to the controls (command buttons). 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 be inserted. 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 With End Sub The With command associates the properties that follow with the control. (in this case Text1).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

14

ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

Double click on the command button with caption exit. Type the following code. Private Sub command3_Click() end End 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.

NOTES

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 the list box for data entry. No editing is possible in a list box. If you want to edit you should use a 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 Project Let the project type be Standard EXE Add a list box and text box to the form Double click on the form. Add the coding given below Private Sub Form_Load() List1.AddItem a List1.AddItem b List1.AddItem c

15

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

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 box Private Sub List1_Click() Text1.Text = List1.Text End Sub When you click on an item in the list box, the contents will be transferred to the text box.

Figure 2.2 A Form with List Box control 2.4.6.2 A Project To Illustrate The Use of Combo Box 1. Start a new Project by choosing File and then New Project Let the project type be Standard EXE Add a combo box and text box to the form as in Fig 2.3 Initialize the combo box as follows Private Sub Form_Load() Combo1.AddItem apple Combo1.AddItem orange Combo1.AddItem grapes End Sub

16

ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

Handle click event for the combo box Private Sub Combo1_Click() Text1.Text = Combo1.Text End Sub

NOTES

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 the resource file; .exe represents the executable file. If only one form is associated with a project 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 variables the DIM statement is used. For instance to say a variable sum is of integer type, either of the following statements can be used. Dim sum As Integer Dim sum% The general syntax for declaring a variable is Dim (keyword) followed by variable name (user defined) followed by As (keyword) followed by datatype which is again a keyword. Table 2.1 gives an idea of the other data types.
17 ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

Dim is Used for declaring variables in procedures. Each time the procedure is called, the data stored in the variables declared with this keyword are reset (eg. an Integer data type will be reset to zero). Static is used to declare variables in procedures. Each time the procedure is called, the data stored in static variables are retained. Public is Used to declare variables within a module. The variable is available to all procedures in the project Private is Used to declare variables within a module. The variable is only available to procedures 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 Byte Boolean Integer Example Dim tn As Byte Dim As Boolean Dim As Integer Description It stores an integer in the range 0 to 255 (8 bits). It stores a value that is either True or False. 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. 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. It stores a real number in the range 922,337,203,685,477.5808 to +922,337,203,685,477.5807. It stores a single-precision floating point number, accurate to 8 significant digits (32 bits). It stores a double-precision floating point number, accurate to 16 significant digits (64 bits). It stores a Date. It stores a sequence of up to 63,000 characters. 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.

Long

Diml As Integer Dim As Currency Dimg As Single DimA As Double Dim to As Date Dims As String Dimu As Variant

Currency

Single Double Date String Variant

18

ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

2.6.1 Option Explicit Declaration If option explicit is used necessarily all variables will have to be declared. Otherwise error will be reported saying that the variable is not declared. The option explicit declaration is found under Tools, options, editor option. Declaring variables gives readability and also the code executes faster. 2.6.2 Numeric data types Integer, long integer are used for whole numbers. Single and double are associated with floating point numbers. Currency is associated with numbers dealing with money. The code below illustrates the five different numeric data types and their effect. Integer can store 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 actual value stored would be 8.976555 only. When the data type is Single and the value stored is 100000000 it would be displayed as 1E+08 using Scientific notation. When the data type is 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 are 2 strings and they are assigned values using =. The value of msg string is displayed followed by space followed by msg1 contents. The output would be distance mca. Private Sub Command1_Click() Dim msg As String Dim 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 to give 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

NOTES

19

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

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 string m the output would be as chennai is the capit. Only 20 characters including the space in between is displayed. 2.6.4 Variant Type If no data type is associated with VB variables, it takes the default variant type. The variable x will be of variant type when the following two declarations are used. Dim x Dim 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 As Single) Dim i As Integer Dim j As Long Dim a As Single Dim b As Double Dim c As Single Dim c1 As Currency i = 32767 range is upto 32767 beyond that overflow occurs j = 97400 Form1.Print integer i is; i Form1.Print long j is; j a = 8.97655467787088 8.976555 b = 0.876554677870879 c = 100000000 1E+08 c1 = 100000000 Form1.Print single a is; a Form1.Print double b is; b Form1.Print single c is; c Form1.Print currency c1 is; c1 End Sub

20

ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

2.7 CONTROL STATEMENTS A conditional expression uses a comparison operator which results in true or false value. If the comparision is valid it results in true, other wise it results in false. Heres a simple conditional expression: Price < 100 If the Price variable contains a value that is less than 100, the expression evaluates to True. 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 statement and Do Until loop control statements are explained. 2.7.1 Select Case Select Case is used for handling multiple paths. Select Case evaluates the expression and depending on the value the corresponding Case statement executes. Select Case expression Casevalue1 BlockofoneormoreVBstatements Casevalue2 BlockofoneormoreVBStatements Casevalue3 BlockofoneormoreVBstatements Casevalue4. CaseElse
21

NOTES

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

BlockofoneormoreVBStatements End Select A function WeekDay(Now) is used which reads the day, date and time from the computer 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 clear the screen when the first command button is clicked. The working of this program is given in 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.Cls End 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 vbFriday Form2.Print Friday Case vbSaturday Form2.Print Saturday

22

ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

End Select End Sub

NOTES

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 vbSunday would be returned. Therefore the corresponding block would execute. So Sunday would be 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 action based on the condition. If the condition is true the then part will execute otherwise the else block will execute. If .. ThenElse IfconditionThen Block of VB Statements Else

23

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

Block of VB Statements End If To use If then Else construct you can place a button and text box on the form as given in Fig 2.5. Run the project and enter value in the text box. Then click the button. The event handler given below executes and if the value entered exceeds 50 it displays pass, otherwise it 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 and a label control on the form. Handle click event for the command button. Type the coding given below as the event handler.
24 ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

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, the order in which the controls will be visited will be highlighted for every tab press. This is known as the tab order. Label control will not have a tab order. Mainly Label control is used for displaying heading. You set the caption property of the label control. During execution the caption will be displayed on the form where the label control is placed. The general syntax of for loop is as follows. For index = start value to end value (Step value) OneormoreVBstatements Next The for loop uses a index, namely i, in this illustration. The index is assigned the starting value, namely 1 as given. The keyword To tells the range of values the index can take. The integer following to is the final value, which is 10 in this example. So, i, will start with 1 and increase by 1 till it reaches 10. For each value of i, the statements between for and next would be executed. When the button is clicked for loop illustration will be displayed in the place where label control was placed. Also the following output would be displayed on the screen 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

NOTES

25

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

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 explicitly stated it is taken as 1 by default. In the above statement Step is specified as 1. So the value will be decremented by 1 for every iteration. The index starts with 10 and is decremented 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 dowhile loop block executes till the condition given in while is true. The working of doloop is explained with the event Form_MouseDown in Fig 2.7. When you click the mouse on the form, the event handler executes and produces the output as given in fig 2.7. Private Sub Form_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) Dim i As Integer i=5 Do While i > 0 Form1.Print i is & i i=i-1 Loop End Sub
26 ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

NOTES

Figure 2.7 Working of do while loop 2.7.6 Do Until Loop Statement The statements within the dountil loop block executes till the condition given in until becomes true. The working of dountil loop is explained with the event Form_ Mouse Down. DoUntilcondition BlockofoneormoreVBstatements Loop When you click the mouse on the form, the event handler executes and produces the output as given in Fig 2.8. Private Sub Form_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) Dim i As Integer i=5 Do Until i = 0 Form1.Print i is & i i=i-1 Loop End Sub

27

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

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 and only an event. It has no methods. A menu has titles (such as Project). Each title contains menu items ( for eg Add Form). A separator can be used to group related items within one menu. 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 editor will 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. Only then, 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 items name. The text we type as caption becomes the title or item under the title. You can place an & before any character of the caption. That character will be the accelerator for that item.

28

ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

2.8.2.2 The Checked Property The Checked Property will place a check mark next to the menu item. Titles cannot be checked. The check mark can be toggled. The checked property can be set to on or off 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 can enable the property. 2.8.3 A Project To Illustrate Creation of The Menu 1. Start a new project by choosing file and then new project 2. Choose Standard EXE as the Project type 3. 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 editor 8. 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 G keys together. 11. Set the checked property of the menu item square by clicking on the check box for 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 If End Sub 14. When you click on square menu item for the first time, the property Checked is set to TRUE. So the else part executes and sets the property Checked to FALSE. The control behaves as a toggle.

NOTES

29

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

15. To address the controls on the form use the form name (Form1 in this case). The menu item we want to manipulate is mnusquare (mnusquare is the name we associated with the menu item during design time). So to access the control we say Form1.mnusquare. Next we want to manipulate Checked property. So we are qualifying it as Form1.mnusquare.Checked 16. Choose Run option 17. Choose Start With Full Compile 18. The form will be displayed 19. Click on disp menu title 20. The sub menu pops up. You have square as the menu item. Notice the check mark as given in Fig 2.10 21. If you click on the menu item square the check mark will disappear during next execution 22. Clicking again will bring the check mark

Figure 2.9 The Menu Editor

30

ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

NOTES

Figure 2.10 Menu Item Square 2.8.4 Associating Toolbars for the menu 1. Add the tool bar control to your form 2. Follow the steps to add the tool bar control to your form 3. Right Click on the tool box 4. 4.A pop up menu will be displayed 5. Choose Components menu item 6. The Components Dialog Box will appear 7. Check Microsoft Windows Common Controls 5.0 (SP2) 8. Click ok 9. Steps 3 to 8 includes the tool bar control in the tool box 10. Add the tool bar control to your form by clicking on it. 11. The default name of the tool bar control would be Toolbar1 12. Set the align property. 13. By default it would be 1- vbAlignTop 14. Select the Custom properties of the toolbar object by Clicking 15. The Property Pages Dialog box would appear. 16. Choose the Buttons tab page 17. Click Insert Button. This would place the first button on the tool bar.
31 ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

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 box 2. Choose the custom property of the image list 3. Click the images tab 4. Choose Insert Picture 5. Select an image and say ok 6. Associate images with all the buttons 7. Select the tool bar object 8. Select the customs property 9. Choose the general tab page. 10. Set the image list with what you have created. It would be ImageList1 if you didnt 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 bar 16. The following handler will be inserted Private Sub Toolbar1_ButtonClick(ByVal Button As ComctlLib.Button) Select Case Button.Key Case Is = square MsgBox sqhello Case Is = disp MsgBox disphello End Select End Sub

32

ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

NOTES

Figure 2.10 Toolbars When you run the project you can click the tool bar in Fig 2.10 or the menu item or title to get the result. When using the menu editor if all the items are on the same indentation they will be the 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 neither on or off. The user can change the setting of the grayed check box.

33

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

2.8.4.3 Develop a Project to illustrate the use of check Box 1. Select General in the objects drop down list box and Declarations in the events drop down list box. 2. Declare 2 Boolean variables Public a As Boolean Public j As Boolean 3. Design the form with 3 check boxes 4. Handle Mouse Up event for the check1 control and type the handler as given below Private Sub Check1_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) If a And j Then Check1.Value = 1 Exit Sub End If If a Or j Then Check1.Value = 2 Exit Sub End If If Not a And Not j Then Check1.Value = 0 Exit Sub End If End Sub 5. Handle click event for check2 control Private Sub Check2_Click() If Check2.Value = 1 Then Form1.a = True Else Form1.a = False End If End Sub 6. Handle click event for check3 control Private Sub Check3_Click()

34

ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

If Check3.Value = 1 Then Form1.j = True Else Form1.j = False End If End Sub Initialize as follows Private Sub Form_Load() If Form1.a Then Check2.Value = 1 Else Check2.Value = 0 End If If Form1.j Then Check3.Value = 1 Else Check3.Value = 0 End If End Sub 7. Execute the project 8. If check2 or check3 is checked by clicking on it and then check1 is clicked it would 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 clicked and then check1 is clicked it would become empty. In this case the public variables a 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 would become checked. In this case the public variables a and j would become 1. This snippet in MouseUp will execute If a And j Then Check1.Value = 1

NOTES

35

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

2.9 DIALOG BOXES Two dialog boxes, namely, the message box and the input box are used in Visual Basic. A message box is used for displaying messages to users and input box is used by the user 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 message box 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 contents as i is 80 and OK and Cancel buttons are displayed. The message box is displayed with 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 msgbox and 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, Y As Single) MsgBox demo of msgbox, vbYesNo, sample End Sub

Figure 2.12 Message box


36 ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

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 project 2. Choose standard exe 3. Add a command button to the form 4. handle double click for the command button and code the handler as given below. Private Sub Command1_Click() Dim r As String r = InputBox(name) MsgBox hello & r End Sub 5. Execute 6. The input box asks for an input 7. Once the input is entered(say mca) hello mca would be displayed using the message box; & is used for string concatentation.

NOTES

Figure 2.13 Input Box 2.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 window will open to type your coding. Type the following coding. Sub Main() Dim sum1 As Integer sum1 = 80 sum1 = sum1 + 10 MsgBox sum1 Main1

37

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

End Sub Add one more module as Main1. Type the following coding in module Main1. Sub Main1() Dim sum1 As Integer sum1 = 80 sum1 = sum1 - 10 MsgBox sum1 End Sub You can choose the Startup object for the project. Select project tabpage, then right click and choose properties. Then choose the startup object from the Startup object list box control. In this case choose Main(). When you execute, Main() will be the starting point of execution. It displays sum1, and then a call to function Main1 is encountered. So control gets transferred to the module containing Main1. In Main1 the subtraction is done and 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 list box and the file list box. The drive list box control is used to display the disk drives on the system such as A drive ,C drive ,D drive etc. The down arrow in the control helps you to visualize all the available drives in the system. The directory list box is used to display the directories available in the selected drive. The file list box displays all the files in the selected 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 default 6. Handle click event for the file list box object. The object would be File1 by default 7. 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()
38 ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

Drive1.Drive = CurDir$ Dir1.Path = CurDir$ File1.Path = CurDir$ File1.Pattern = *.* End Sub The CurDir$ keyword stores the selected drives path in the Drive1 object. The data member Drive contains the selected drives path. The CurDir$ keyword stores the selected drives path in the Drive1 object in the above code snippet. The data member Drive contains the selected drives path . The CurDir$ keyword stores the path of the selected directory in the Dir1 object. The data member Path contains the selected directorys path. The CurDir$ keyword stores the selected files path name in the File1 object. The data member Path contains the selected files path name. 9. Handle change event for the Drive1 object. Code the handler as given below. Private Sub Drive1_Change() Dir1.Path = Drive1.Drive End Sub Dir1.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.Path End 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.FileName End Sub File1.FileName returns the selected files name and that is stored in the text box Text1.

NOTES

39

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

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. Microsofts notepad and paint are examples of single document interface. As we know SDI applications have limited capabilities. They have limited image and text- editing features. Multiple document interface allows users to edit multiple documents at the same time as given in Fig 2.15. Adobe Photoshop allows to edit multiple images at the same time.

Figure 2.15 MDI Window

40

ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

The main window in a MDI program is the parent window. All the other windows of the application are child windows. A MDI program will have only one parent window and many child windows. Only one child window will be open at one time. Uses of child windows can vary. A child window could be used for editing images, the second child window could be used for editing text. Closing or minimizing the parent window automatically 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 explorer 4. Select Add and then select Windows Form 5. Create a new child form object and set the MdiParent property to the parent form. 6. Invoke the child forms Show method. 7. Write the coding below to create the child form in a event handler. Dim childForm As New ChildFormClass() childForm.MdiParent = parentForm childForm.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 multiple controls of the same type to a form at design time. Control arrays are also useful if you want several controls to share code. For example, if three option buttons are created as a control 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 a member of a control array. With a control array, each new element inherits the common event procedures of the array. Using the control array mechanism, each new control inherits the common event procedures already written for the array. For example, if your form has several text boxes that each receive a date value, a control array can be set up so that all of the text boxes share the same validation code. For example you can have several Text Boxes with the same name and differentiate them with the help of a subscript. We will see how to create a control array. We are going to create an array of textboxes. Follow the following steps to create a control array of textbox.
41

NOTES

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

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 displayed 7. 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 Integer For an = 0 To 2 Text1(an).Text = Val(Text1(an).Text) + 5 Next an End Sub The Val function converts the content of Text1 to numeric. The subscript, an, is used to access the various text boxes; an(0) would refer to the first text box, an(1) would refer to 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 to connect to a database. The first property is the database name. You can set this in the data control property. The syntax is Form.datacontrol.DatabaseName = pathname pathname is the location of the database file name. If the database is ex.mdb, and the data 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 the drop down list box youll observe that you can connect to Paradox, Dbase, Excel, Lotus and ODBC. You need to set the Connect property. The third property is the Recordset property. 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.
42 ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

2.14.1 Displaying The Database Text box, check box, image box, labels, picture box can be bounded to the data control for displaying the data base contents. Two properties are essential for binding to the data control. The DataSource and the DataField are the essential properties for binding to the data control. The DataSource refers to the database and the DataField refers to the specific field of the record. If a text box is used for displaying the names of the customer then the DataField property 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 and state. 2. Place 5 text boxes on the form to display the records. 3. Place a data control on the form 4. 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 refresh method 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 Record Type to 0. 2. Design a form with 5 text boxes and 2 command buttons new and update.
43

NOTES

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

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 below data1.RecordSource = Customer data1.Refresh data1.Recordset.AddNew Add New adds a buffer in memory for a new record. 6. Handle Click event for the command button update and type the handler as given below data1.Recordset(Id) = CInt(text1.Text) data1.Recordset(name)= text2.Text data1.Recordset(address)= text3.Text data1.Recordset(city)= text4.Text data1.Recordset(state)= text5.Text data1.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 table follow 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. LostFocus KeyDown KeyUp MouseDown 2. Name any 4 events associated with a form. Load MouseDown Resize Click
44 ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

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

NOTES

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 If Answer: 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. 1. Handle form double click event 2. Use IsNumeric function to validate both the inputs 3. 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.Text Else Text3.Text = End If End Sub 5. Name any 3 buttons that can be associated with the second parameter of MsgBox.
45 ANNA UNIVERSITY CHENNAI

Answer

DMC 1755

NOTES

Answer vbCritical - displays a cross vbDefaultButton4 displays no button vbExclamation displays the exclaimation symbol ! 6. What would be the check box state depending on the value of CHECKED If Check.Value is 0 means the check box will be unchecked If Check.Value is 1 means the check box will be checked If 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 changed programmatically. 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 CTRL and 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 combo box as Text as the default property. Exercise 1. Develop a simple calculator to perform addition, subtraction, multiplication and division using VB. Solution 1. 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
46 ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

6. Private Sub Command3_Click() Text3.Text = Val(Text1.Text) * Val(Text2.Text) End Sub 7. 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 assign different 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 2 Shape1(k).FillStyle = k+2 Next k End Sub 3. Write a program to create a list box containing names of fruits. a. b. c. d. Copy the selected item of the list box on to a second list box. Clear the contents of the first list box after copying to the second list box. Copy the second list box selected contents on to the first list box. Clear the contents of the second list box after copying to the first list box.

NOTES

Solution 1. Create a new project by choosing file and then new options 2. Let the project type be standard exe 3. Paste 2 list box controls on the form.

47

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

4. Initialise the first list box by coding in form load event Private 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 given Private Sub List1_Click() List2.AddItem List1.Text List1.RemoveItem List1.ListIndex End Sub The Selected item is given by List1.Text. And it is inserted into the second list box by 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 given Private Sub List2_Click() List1.AddItem List2.Text List2.RemoveItem List2.ListIndex End 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 contents of the list box and display the total items in a text box. Solution 1. Create a new project by choosing file and then new options 2. Let the project type be standard exe 3. 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 1 List1.AddItem 2
48 ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

List1.AddItem 3 List1.AddItem 4 List1.AddItem 5 List1.AddItem 6 List1.AddItem 7 List1.AddItem 8 List1.AddItem 9 List1.AddItem 10 End Sub 5. Handle click event for the first list box and write the coding as given Private Sub List1_Click() Text1.Text = List1.ListCount End 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 selected contents of the combo Solution 1. Create a new project by choosing file and then new options 2. Let the project type be standard exe 3. 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 Sub 5. Handle click event for the combo box. Code the handler as given below. Private Sub Combo1_Click() List1.AddItem Combo1.Text End 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
49

NOTES

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

Summary This Unit focuses on Visual Basic programming which is event driven programming. A form is a layout on which objects called controls are placed. Properties and events associated with controls are discussed. The creation of projects in Visual Basic is explained. The command button, text box, list box , combo box controls methods and some of the properties were introduced. The different data types are introduced. The use of variant type is explained. The working of the control statements are explained in detail. The way in which menu titles and items are to be incorporated is explained. How to associate toolbars with the menu titles and items was also covered. File system controls and control arrays are discussed. MDI forms and accessing the database with the data control are explained.

50

ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

UNIT III

NOTES

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 in this unit. The creation of these projects is explained. Every SDI or MDI project has 4 classes incorporated in it. The view class is used for producing the drawing code. The OnDraw() function in the view class implementation file is meant to house the drawing code. The document class houses the data for the application. The framewnd class is responsible for all the windows related coding such as the status bar, menu bar. The object of the application is contained in the Appclass. The appwizard tools role of creating a project is explained. The tool, class wizards role in adding member variables is 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 document view architecture is explained. Modal and Modeless dialogs are introduced. The concept of serialization is covered. The MFC library is built on top of other Win 32 API. MFC is 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

51

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

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 based application. 3.3.1 SDI Application A SDI application uses the main frame window to display a document. Only one document 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 user can 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 are the files corresponding to the View Class, Document Class, MainFrame Class and the App 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 the implementation file would be first.cpp. A corresponding header file first.h would also be available. The View Class is mainly used for writing the drawing code. The OnDraw() function in the View Class is the place where you will write the drawing code. Apart from the OnDraw() function, you can incorporate event handlers with drawing code. For the project named first, the View Class would be CFirstView and the implementation file would be firstView.cpp. The corresponding header file would be firstView.h. The Document class is the place where the data members are defined. Also it has the Serialise function which implements the file storage and retrieval. If the project is named as first the document class would be CFirstDoc and the implementation file would be firstDoc.cpp. The corresponding header file would be firstDoc.h. The MainFrame class contains all the necessary coding for the display window of the project. The status bar pane initialization is done in the MainFrame class. If the project is named as first the MainFrame class would be CMainFrame and the implementation file would be MainFrm.cpp. The corresponding header file would be MainFrm.h. Also stdafx.h, the standard application frame work header file will also be part of every project.
52 ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

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; .plg contains the settings of that project. 3.3.4 Dialog Based Application The application that app wizard creates is based on a dialog template resource. 3.4 THE IMPORTANT MFC CLASSES The CWinApp, CDocument, CFrameWnd and CView are derived from CObject and 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 the project to create .pch ( the pre compiled header) file and then you build. Because it is incremental 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 to create a project. 3.6.1 Steps Involved in Creating A Project Step 1 From the menu bar , click File and then new options. Step 2 The new dialog box will appear with 4 tab pages. They are the 1. Files 2. Projects 3. Workspaces 4. Other Documents Step 3 Choose projects (2) in the above step. Then choose MFC Appwizard(.exe) option Step 4 Type 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
53

NOTES

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

2. Multiple Document 3. Dialog Based The above sequences forms the Step1 of Appwizard. Step 6 Click next It will take you to the second step of the MFC appwizard. Select none and click next. Step 7 In the third step of MFC appwizard choose none and proceed with next button. Step 8 In the step 4 of MFC appwizard keep the settings as such and click the next button. Step 9 In 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, to define member variables.

Fig ure 3.1 Class Wizard


54 ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

3.7.1 Adding Handlers With Class Wizard When a handler is added, the class wizard places the prototype for the message handler 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 messagemap 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. The class wizard inserts the skeleton handler in the implementation file (.cpp). The skeleton handler 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 the prototype 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 provides default 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 window will also change accordingly to the output window. The function Invalidate(TRUE) will

NOTES

55

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

call the OnDraw() and the TRUE parameter will clear the screen. DeflateRect will shrink the rectangle 1. Create a SDI application wmsize. 2. Handle WM_SIZE message for the CWmsizeView object id. 3. Choose the class tabpage 4. 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 given 16. CSizeView::CSizeView():m_rdRect (10,30,50,20) {} 17. Build and execute the project. 18. You will observe the impact of WM_SIZE message.

56

ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

3.8 WRITE A PROGRAM USING VC++ TO DISPLAY THE MOUSE COORDINATES 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 that position is displayed. 3.9 MFC CLASSES REQUIRED TO DRAW A RECTANGLE IN THE CLIENT AREA A client area is where you can do drawing. The regions in which we cannot draw is known 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 to manipulate CRect objects and Windows RECT structures. A CRect object can be passed as a parameter in place of RECT structure, LPCRECT or LPRECT . A CPoint object can be used wherever a POINT structure is used. Generally the event handlers associated with the mouse have one of the parameters of type CPoint. It represents 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.
57

NOTES

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

The hatch style of the brush can be any one of the following values and it is the first parameter 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_BDIAGONALDownwardhatch(lefttoright)at45degrees HS_CROSSHorizontalandverticalcrosshatch HS_DIAGCROSSCrosshatchat45degrees HS_FDIAGONALUpwardhatch(lefttoright)at45degrees HS_HORIZONTALHorizontalhatch HS_VERTICALVertical 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. It helps to draw text, lines, shapes etc. To create a device context, the MFC provides various classes such as CDC and CClientDC. CDC is the most fundamental class to draw in MFC. It provides all of the basic drawing 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 Actual Display Fig 1 The Role Of Device Context The logical display is a virtual device and Actual display is the physical device. The programmer need not worry about the medium in which he is writing the output. The device context takes care of the output medium. 3.11 GDI OBJECTS CDC provides five versions for GDI objects. They are pens, brushes, fonts, bitmaps and regions. The Select Object function replaces the current GDI object with the object specified as parameter. The GDI object CPen can use the following macro to specify the pen style.
58 ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

PS_SOILD PS_DASH PS_DOT PS_DASHDOTDOT 3.11.1 Illustration of GDI object CPen 1. 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 second parameter is the thickness of the pen, namely 2. The third argument specifies the color of the pen. Another pen object is created as pe. 2 Rectangles with the pens 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.

NOTES

59

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

Default Values for GDI Objects The default color for pen is black , brush is white, default bitmap is null and the default font 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 CRect l; CBrush b(HS_BDIAGONAL,(point.x,point.y)); CClientDC dc(this); dc.SelectObject(&b); //BOOL GetClientRect(LPRECT lpRect) const GetClientRect(&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 in m_rdRect object. Select Stock Object makes a call to CGdi Object :: From Handle() to determine which CGdiObject to return. function

Figure 3.2 Affect of Rectangle Function


60 ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

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 and WM_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); }
61

NOTES

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

Step 13 Build and execute the project Step 14 Click the left button down (first point is got) and move the mouse and release the left button (second point is got). The rectangle would be drawn using the 2 points as given in Fig 3.2. 3.14 WRITE A PROGRAM TO ZOOM A RECTANGLE AS YOU DRAG 1. Create a SDI application 2. 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 View Class. 3. Using Class wizard add the messages left button down , left button up and mouse move. 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; } }
62 ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

When the mouse button is released with the last point as first point and where the mouse button was released a rectangle would be drawn. 3.15 WRITE A VC++ PROGRAM TO SCRIBBLE Step 1 Create a SDI application Step 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 choose add member variable option. CMovelineView::CMovelineView():m_ptoldpt (5,5) { } Step 3 Handle Leftbutton down, mouse move and Leftbutton up handlers in the View Class for the View object. Step 4 Leftbutton down handler. This step initiates the drawing void 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.
63

NOTES

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

Step 8 Click the left button down and as you move the lines are drawn. The scribble application will terminate when the left button is released. Colors keep on changing because the mouse coordinates is used for specifying color. 3.16 ILLUSTRATION OF CCOLORDIALOG The constructor of CColorDialog takes the first parameter as the default color and the 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 disposed by 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 COLORREF 10. 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
64 ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

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 the macro MESSAGE_MAP delimited by BEGIN and END. The first parameter CDrawView represents the name of the project. The name is actually DrawView and it is prefixed by C. The second parameter states the base class. That is CDrawView is inherited from CView . When WMCHAR message is handled the corresponding event handler ON_WM_CHAR() will be inserted in CDrawView.cpp. Also it will be included in the MESSAGE_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 appropriate handlers. The Message Map offers many of the advantages of using C++ virtual functions without the high over head of polymorphism. The Message Map connects messages to message handler function. For instance a WM_CHAR message would be mapped to ON_WM_CHAR handler function in a view object. When the message is received, the message 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 default the 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 the array. To convert str into a string \0 (null character) is appended along with c. The AfxMessageBox takes a string namely str, as parameter and displays the string str. void CDrawView::OnDraw(CDC* pDC) { char str[] = {c,\0'}; AfxMessageBox(str); }
65

NOTES

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

1. Handle WM_CHAR message for the CDrawView object id. The first parameter nChar will hold the Unicode equivalent of the character that has been pressed. To display the character that is pressed a CString object is used. The format function gives the character equivalent of the pressed character. 2. GetDC retrieves a handle to a display device context (DC) for the client area of 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 Microsoft Foundation Classes library. The Document/View architecture is composed by a frame, one or more documents and the view. The View A view is used for visualising. For example, while performing word processing, the user works on a series of words that compose the text. If a user is performing calculations on a spreadsheet application, the interface the user is viewing is made of small boxes called cells. Another user may be in front of a graphic document while drawing lines and other geometric 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.

66

ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

To let the user do anything on an application, you must provide a view, which is an object based on the CView class. You can either directly use one of the classes derived from CView or you can derive your own custom class from CView or one of its child classes. The Document A document holds the users 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 document must 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 are handled 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 (in the English sense), and the borders of an item. A frame gives physical presence to a window. 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, and resize the object. The frame is also a type of desk that holds the tools needed on an application. An application cannot exist without a frame. As we saw in previous lessons, to provide a frame to an application, you can derive a class from CFrameWnd. MFC provides a mechanism for notifying views of modifications to a document through the UpdateAllViews member function of the CDocument class. The UpdateAllViews function traverses the list of views attached to the document. The function calls the OnUpdate of CViewClass . Invalidate(TRUE) in OnUpdate clears the client area of the view and calls the OnDraw()function of the view class. Document View architecture allows the variables in the document class to be displayed in the view class using GetDocument() function in the view class. 3.18.1 A Project To Illustrate Document View Architecture 1. Choose MFC Appwizard EXE 2. Create a SDI application 3. Add a global variable in the document class 4. To add the global variable expand class tab page. 5. Click on the document class 6. Right click and choose add member variable 7. Let the variable be CString type and call it c.
67

NOTES

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

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 to the document class. From this we come to know that the variables in the document class can be accessed only by document class members. The function GetDocument() returns the pointer to the document class. { CDoDoc* pDoc = GetDocument(); pDC->TextOut(20,30,pDoc->c); } 3.19 USE OF THE SERIALIZE FUNCTION IN THE DOCUMENT CLASS IMPLEMENTATION 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 the contents 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.
68 ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

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 class Right click and choose add member variable Specify the type as char and variable name as *m_pdata GetFile() 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 operator 5. 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 AfxMessageBox 7. 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; } }

NOTES

69

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

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 initial update () 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 class Right click and choose add member variable Specify the type as char and variable name as *str 4. Type this code in OnDraw() in View.cpp pDC->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 we access 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. For the 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);
70 ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

DT_CALCRECT returns the height of the rectangle containing the text and it doesnt 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 youll observe that the scroll bar is introduced and you can scroll and see all the pages. 3.20 A PROJECT TO ILLUSTRATE MDI APPLICATION 1. Choose MDI option while creating the project using Appwizard 2. Add the message WM_LBUTTONDOWN for the view object id 3. 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 project 5. 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 type cast to CMDIChildWnd. The function MDIMaximize () will display the window on full screen. The function GetMDIFrame() will return the handle of the MDI window. The function MDINEXT() displays the next MDI window.

NOTES

71

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

Figure 3.3 MDI If you click New continuously multiple windows keeps opening. For MDI applications Appwizard derives the CMainFrame class from CMDIFrameWnd. 3.21 PROJECT TO CREATE SPLITTER WINDOW 1. Create a SDI application 2. Expand the class tab page 3. Select the view class 4. Right click and a menu pops up 5. Choose add member variable. 6. Type the variable as cswnd and the type as CSplitterWnd 7. Handle OnCreateClient in Frm.cpp Create(this, 2, 2, CSize(10,10), pContext); pContext is the parameter of OnCreateClient 8. Build and execute The 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 split 2. In Mainfrm.cpp include the following header files #include CSplitDoc.h
72 ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

#include CSplitView.h #include AddView.h AddView is a new class inherited from CView To Create AddView follow the Steps given below Expand the class tabpage Select the root of the treecontrol Right click and select add class Name the class as AddView and the base class as CView 3.In MainFrm.cpp type the following OnCreateClient() { CsWnd.CreateStatic(this,2,1); // the first parameter 0 is referring to the first splitter window CsWnd.CreateView(0,0,RUNTIME_CLASS(CAddView),CSize(100,100), pContext); // the first parameter 1 is referring to the second splitter window CsWnd.CreateView(1,0,RUNTIME_CLASS(CSplitView),CSize(100,100), pContext); } 4. In OnDraw of both views write the coding as given below. The respective output will be reflected in the respective window. 5. Type the following in CSplitView pDC->Rectangle(10,10,100,100); 6. Type the following in CAddView pDC->Ellipse(10,10,20,20); Build and execute the project. In one window a rectangle would be drawn and in another window ellipse would be drawn.

NOTES

73

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

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. For example, a dialog box is modal if it requires you to click OK or Cancel before you can switch 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 message before proceeding. Modeless dialog: let you shift the focus between the dialog box and another form without having to close the dialog box. You can continue to work elsewhere in the current application while the dialog box is displayed. Modeless dialog boxes are rare. From the Edit menu, the Find dialog box in Visual Basic is an example of a modeless dialog box. Use modeless 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 add member variable. 3. Create a dialog resource using the resource editor.
74 ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

To create the dialog resource click on the resource tabpage. Expand the dialog resources. Select the dialog option Right Click and choose insert from the pop up menu Choose the resource type as dialog Click 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 object 5. Handle WM_LBUTTONDBLCLK message for the CModalessView object id and 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 referred to by its index. ImageList are used to efficiently manage large sets of icon or bitmaps.ImageList is not a control since it is not a window. They are used with several different 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 and right clicking on the CimagelistView object. Choose add member variable.

NOTES

75

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

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 and it 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 last parameter 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 control Right 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)
76 ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

{ 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 object bmp. The Add member function of the CImagelist associates the bitmap with the image list. DeleteObject recovers the memory occupied by the gdi object, namely bitmap in this case. 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, MDI and dialog based applications. The various files of a project were introduced. The MFC classes, 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 GDI objects have been introduced. Event handling, Modal and modeless dialogs have been
77

NOTES

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

explained. The creation of Multiple Document Interface (MDI) has been explained. The creation 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 the window with vertical lines. CBrush(HS_VERTICAL, RGB(20,70,90)); The first parameter of CBrush specifies the style and the second parameter specifies the color of the brush. 2. Give examples of Modal dialog. CColorDialog and CFileDialog are Modal dialogs 3. Differentiate Modal and Modeless dialogs

Modal Dialog They are displayed using DoModal function Modal dialogs should be disposed by clicking OK or cancel. Only than you can work with any other window
4.

Modeless Dialog They are displayed using ShowWindow function Modeless Dialog allows you to work with other windows and it gets minimized.

Which class deals with the data of a project in VC++? The SDI and MDI applications has the Document class in which the data members are defined.

5.

Which MFC class supports file storage and retrieval? CArchive class provides Isstoring() member function to write to a file. The object used 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 class CScrollView will provide the data members and member functions necessary for scrolling.

78

ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

UNIT IV

NOTES

DATABASE APPLICATIONS
4.1 INTRODUCTION In this chapter, we define a dialog and tab order which is the order in which the controls will be navigated during execution. The dialog data exchange (DDX) mechanism to transfer data from controls to variables and vice versa is explained. Projects involving dialog based applications are presented. Various controls such as animate control, list box control, combo control, tree control, slider control are used. The inheritance of CtreeCtrlView to create tree control is explained. The creation of dynamic control and the associated messages are explained. The creation of dynamic link libraries and their usage is 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.

79

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

4.3 DIALOG A dialog is a window that contains controls. Dialog boxes are the form of input and output. A control can be placed on a dialog box for communicating. If you inherit CView only at run time you can visualize the output. Where as, using CFormView or dialog based application you can visualize the output at design time itself. To Maximise the dialog during execution set the following: ShowWindow(SW_SHOWMAXIMIZED); in OnInitDialog() In the properties of dialog set maximize and Minimise button. Otherwise only X will be 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 the dialog 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 controls will be displayed at design time. 4.3.1 Tab Order The tab order represents the order in which the controls receive focus when the user presses the tab key. CTRL + D can be used to set the tab order of controls. If you click the controls in the sequence you want, in that order the controls will receive the focus. This is the way to set the tab order. If you press ESC or CTRl + D, the tab order setting will be completed. 4.3.2 DDX - Dialog Data Exchange Data members can be associated with specific controls in the dialog box. When the dialog 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 box controls 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. 2. 3. 4. 5. 6. 7. Create a dialog based application. Design the dialog as follows. Place four command buttons and the Animate Control on the dialog. Using class wizard create a control object m_AnimateCtrl of CAnimateCtrl type. Set the caption of the 4 command buttons as play, stop, close and open. Handle button clicked event for the 4 command buttons. Include the coding as handler for open command button CFileDialog File(TRUE,NULL, ,(*.AVI)|*.AVI,NULL);
80 ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

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 second parameter -1, tells to play the file till the end. The third parameter -1, tells to play the file infinitely. 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 the files 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.
81

NOTES

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

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 the string pat given by the second argument. If it is not present the content is inserted as a tail element 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 drop down, we cannot edit during execution. Another category is simple combo box. Using the combo box you can give data at design time. Using CTRL ENTER you can complete the data 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. Name the variable as m_v1

82

ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

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 Calculator 1. Develop a dialog based application 2. 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_nadd 5. 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);
83

NOTES

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES
}

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

The UpdateData flag indicates whether the dialog box is being initialized or data is being retrieved. 6. Build and execute the project 7. The dialog will be displayed. 8. Enter 2 numbers in the 2 edit boxes. 9. Click a radio button. 10. Click the command button 11. 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 Control 1. 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 lines buttons 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 m_v1 m_v2 m_v3 type CTreeCtrl CString CImageList

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


84 ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

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 Object and 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 the contents 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 Chennai and 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 class 3. Include the variable m_v1 of type CImageList in the view header file 4. 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);
85

NOTES

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

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 handle the manipulations on the tree control are done. In the earlier case we used a tree control in the dialog based application. Where as, in this case the tree control is displayed in the view 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 this the 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 see how 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. Choose add 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 Constructor as follows.

86

ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

tree::tree():r(10,10,20,20) 4. Handle WM_CREATE message for the view object id. Type the initialization Code 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 intervals press the left button down and observe the output. 4.3.3.8 Slider Control

NOTES

The slider control can be used for controlling the volume of speaker or any such application. 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 / right 5. Create m_v1 as CSliderCtrl. To create the variable invoke the class wizard. 6. Select the CSliderctrl object id 7. Select add member variable

87

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

8. Name the variable as m_v1 and the type as CSliderCtrl. It becomes a control variable. 9. Create a variable for the Edit box 10. Invoke the class wizard. Press CTRL+W 11. Select IDC_EDIT1 object id 12. Click Add variable 13. Name it as m_v2 and type as int 14. Initialise in OnInitDialog() m_v1.SetRangeMin(5,FALSE); m_v1.SetRangeMax(100,FALSE); 15. Handle Horizontal Scroll message (WM_HSCROLL) for the dialog object id OnHScroll() { 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 Application 1. 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_BUTTON2 3. Observe the MESSAGE_MAP in dlgbutDlg.cpp 4. 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.

88

ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

6. GetDlgItem will return the handle of the specified control. It is typecasted to CButton type. 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 several concurrently executing programs. A dll is a file which contains a number of modules. A function in a dll is connected to a program that uses it when the application is run. Each time 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 be used 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, as well as from within the DLL where they are defined. Internal : Functions are typically intended to be called only from within the DLL where they are defined. Although a DLL can export data, its data is generally used only by its functions. However, there is nothing to prevent another module from reading or writing that address.

NOTES

89

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

DLLs provide a way to modularize applications so that functionality can be updated and reused more easily. They also help reduce memory overhead when several applications use the same functionality at the same time, because although each application gets its own copy of the data, they can share the code. The Windows application programming interface (API) is implemented as a set of dynamiclink 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 differ in several ways. To the end-user, the most obvious difference is that DLLs are not programs that can be directly executed. From the systems point of view, there are two fundamental differences 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 a message 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, Windows must load a copy of the library code into memory for each application that is built with a static link library. DLL saves disk space. Many applications can share a single copy of the DLL on disk. In contrast, each application built with a static link library has the library code linked into its executable image as a separate copy. Upgrades to the DLL are easier. When the functions in a DLL change, the applications that use them do not need to be recompiled or relinked as long as the functions arguments and return values do not change. In contrast, statically linked object code requires that the application be relinked when the functions change. Supports multilanguage programs. Programs written in different programming languages can call the same DLL function as long as the programs follow the functions calling convention. The programs and the DLL function must be compatible in the following ways: the order in which the function expects its arguments to be pushed onto the stack, whether the function or the application is responsible for cleaning up the stack, and whether any arguments are passed in registers.
90 ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

Provides a mechanism to extend the MFC library classes. You can derive classes from the existing MFC classes and place them in an MFC extension DLL for use by MFC applications. Eases the creation of international versions. By placing resources in a DLL, it is much easier to create international versions of an application. You can place the strings for each language version of your application in a separate resource DLL, and have the different language versions load the appropriate resources.

NOTES

A potential disadvantage to using DLLs is that the application is not self-contained; it depends 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 is a key word. 4.4.3 A Project To Create Win32 DLL 1. Choose Win32 dynamic link library. 2. Type a project name 3. Choose empty DLL project 4. Click New Text File icon and save as .cpp 5. 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 project A .dll and .lib file will be created. 7. Find the path of the lib file To find the path click on the file and press ALT + F, then press R or ALT + ENTER

91

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

8. Select View and then options All 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 to use 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 application 3. Create two edit boxes for the two inputs 4. Create an edit box for the result 5. Place a Command Button on the form 6. Add member variables 7. To add member variables invoke class wizard using CTRL + W 8. Attach a member variable m_v1 of type value float to the object IDC_EDIT1 9. Attach a member variable m_v2 of type value float to the object IDC_EDIT2 10. Attach a member variable m_v3 of type value float to the object IDC_EDIT3 11. Handle Button Clicked event for the Command Button 12. 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 event OnButton1() { UpdateData(TRUE); m_v3 = (float) mul(m_v1,m_v2); UpdateData(FALSE); } 14. Change the button caption to mul and div 15. 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); }

92

ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

16. To link the dll Choose Project , then Settings and choose Link 17. 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 project name. The project is stored in C drive under the folder Visual Studio which again has a sub folder MyProject. Enclose the path name in double quotes so as to avoid extra characters in the path name. C:\Visual Studio\MyProject\dll\Debug\*.lib 19. Now Choose Rebuild All 20. 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 based application. 21. A dialog with two edit boxes for input and one edit box for output would be displayed. 22. Also two command buttons with captions mul and div would be present in the dialog. 23. Enter the two inputs which is to be multiplied. 24. Click the mul command button 25. Observe the third edit box which would contain the resultant 26. Execute the project once again 27. Enter the two inputs which is to be divided. 28. Click the div command button 29. Observe the third edit box which would contain the resultant 30. 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 dll2 3. Choose default regular dll using shared MFC 4. Go to the Source file dll2.cpp 5. 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 prototype extern C++ __declspec (dllexport) CString Getdata();
93

NOTES

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

10. Now build the project. 11. lib file will be created 12. 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 to use 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 application 3. Specify a project name 4. Select OK button 5. Place a Command button on the dialog 6. Invoke the Class Wizard (Press CTRL + W) 7. Handle Button Clicked event for the Command button 8. 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 -> Settings 11. Execute after copying the dll file to the debug directory 12. 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) option 2. Name the project as dll 3. In the implementation file dll.cpp type the following extern C++ __declspec (dllexport) void draw(CDC *pDC) { pDC->Rectangle(10,10,20,20);
94 ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

} 4. In the dll.h file include the prototype given below extern C++ __declspec (dllexport) void draw(CDC *pDC); 5. Build the Project 6. dll and .lib files would be created 7. 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 Button 4. Type the coding in bold as the handler OnButton1() { CClientDC dc(this); Draw(&dc); } 5. Type the following before OnInitDialog() in the .cpp file extern C++ __declspec (dllimport) void draw(CDC *pDC); 6. Specify the path of the dll by Choosing 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 implementation via ODBC drivers specific to a DBMS. The program will use this API to call the ODBC driver manager, which passes the calls to the respective driver. The driver interacts with 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 to a query. The record set falls into 3 categories. They are table type record sets, dyna set type record sets and snap shot type record sets.

NOTES

95

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

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 data 2. A DBMS 3. The Operating system and the environment where the data resides 4. A network connection that allows access to the data source. The database related projects are made up of MFC database classes. The ODBC driver manager using the driver interacts with the database as given in Fig 4.1.
APPLICATION | | MFC Database Classes | | ODBC Interface | | ODBC Driver Manager | | DRIVER | | DATA SOURCE | | DATBASE

Figure 4.1 Working of a Database Application


96 ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

4.5.2 Cdatabase Class The CDataBase class helps to connect to a data source. The Open member function opens a connection to the data source. The CRecordset class is used for performing manipulation on the connected data source. The Close member function destroys the CDatabase 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 uses the RFX mechanism to exchange data between field data members of the record set object and corresponding table columns of the data source. Record sets enable scrolling from record to record, updating records (addition, edit, deletion). 4.5.4 Enabling ODBC 1. Choose programs, setting, control panel and then ODBC32 2. Double click on ODBC32 3. Settings for the operating system will occur. 4. Select user tab page 5. Click ADD 6. Select Microsoft ODBC driver for ORACLE 7. Click finish 8. 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 class 4. Right click and a menu pops up. 5. Choose add member variable 6. Type the variable type as CDatabase and the pointer variable name as *pDatabase 7. Type #include <Afxdb.h> in stdafx.h 8. Type the following in OnInitDialog() TRY { pDatabase = new CDatabase;
97

NOTES

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

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 the dialog. 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_CATCH UpdateData(FALSE); } Type the SQL command in the edit box. You can use insert, delete , update data and apply create command only. No select operation is possible using CDatabase object. It doesnt do any retrieval. The command is stored in m_v1, which is passed as parameter to ExecuteSQL() function.

98

ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

4.5.6 A Project To Display The Contents Of The DataBase 1. Create an SDI application 2. Choose the header files in second step of Appwizard 3. 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 choose the DSN). For the selected table configure and create record set. 5. Add a data member in the Document class for the new class CDataSet as Follows Choose the class tab page and expand it, select the document class, right click and 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 class Choose the class tab page and expand it, select the view class, right click and select 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;
99

NOTES

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

if(m_pset->GetRecordCount() > 0) m_pset->MoveFirst(); else return; while (!m_pset->IsEOF()) { // NAME, AGE, DESG are the fields of the table x=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 Execute 10. Place 4 command buttons on the dialog 11. Name them as HOME, END, PREV and NEXT 12. 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);
100 ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

} 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 appwizard 2. choose the container option 3. 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

NOTES

101

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

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 be displayed. 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 displaying AVI files. InsertString (), AddString (), GetCurSel(), DeleteString () functions of the list box control are explained. The message WM_SELCHANGED has been handled to reflect changes in the list box control. A calculator has been developed using a dialog. The file manager is displayed using a tree control in general. How to design the tree control by inheriting CtreeCtrlView is explained. The creation of dynamic controls and their associated messages are explained. The usage of slider control is explained. How to create a dll and how to use it has been covered. Displaying, updating, deleting and inserting into a database have been explained.

102

ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

UNIT V

NOTES

GUI DESIGN AND FILE HANDLING


5.1 INTRODUCTION As you know the aim of the user interface design is to achieve the users goals. When the users goals are met, the user is satisfied and the user interface design software will be a success. The users goals differs from what we would guess. For instance, from a clerks point of view, he would not want to make mistakes and he would want volume of work to be done. These would be the goals from the clerks point of view. Whereas, the organizations goal may be efficient processing. User interface design focuses on what the software will look like and how it will communicate 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

103

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

5.3.1

Software That Is Rude

As we all know, software warns the user for making mistakes. Message boxes pop up indicating the mistake and the user will have to click the OK or CANCEL button to dispose off the Message Box. This is because the developer of the software assumes the user of the package will be a computer literate. Yet another instance is after we edit a document and close it, the word processor will ask whether it should be stored. Similarly, questions such as Are you Sure Did you really want to delete are also irritating. The user may not be prepared to answer such questions. The user interface design should avoid such confirmation interface which leads to 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 a user 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 information in terms of the functionality of each installation or the disk space requirement, the user can choose 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 youll attempt to close it. The program will ask you if you want to save. This is because, the software thinks the printing operation would have made modifications. The designer of the user interface should ensure, that the software is not rude, is not obscure 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 will be the life of software? During its lifetime how frequently will the software be used? These are some of the issues to be addressed by the software developer. The help associated with the software on how to use it should be easy to learn and the software should achieve throughput. Good design will make the user more effective. The designer has to choose with its ease or effectiveness that matter. For instance, a software meant to guide the visitors in a campus should aim for ease of use. If it is easy to use only visitors will use the software 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, it must be effective in identifying enemy flights. If it wrongly identifies friendly flights as enemy flights the software fails. So, the designer should choose depending on the requirement whether ease of use or effectiveness should be satisfied. The problems to be tackled during design are as follows:
104 ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

What should be the form of the program? How will the user interact with the program? How can the programs 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?

NOTES

5.5 THE THREE MODELS FOR THE USER INTERFACE DESIGN The three models for the user interface design are the implementation model, mental model 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 users view. If reasoning and logic is incorporated in the manifest 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 sample images with a different color balance is displayed. The user can click on the specific image to choose a specific color. Since the user is thinking in terms of colors, it resembles the users 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. This model can be changed. If the logic is abandoned in rendering, than the manifest model will create a good interface. This is because it follows users imagination. 5.5.4 Mathematical Thinking

The interface designer must shield the user from the implementation models used in constructing the software. The data structures and algorithms for representing and manipulating information are based on mathematical models. Recursion, hierarchical data structures and multi-threading are used in designing user interface. Boolean Algebra is used in describing on or off conditions. To achieve this AND and OR operators are used. The users confuse the logical AND and OR with the AND and OR in the English language. 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
105 ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

regular mode, we would say, display the students in DMCA or RMCA. This is in the context 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 students of 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 logical AND 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, using logical OR we will say display the students born in March OR May. The user interface should avoid Boolean Algebra since they confuse the use of logical 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 is important. The program should not focus on GUI. On the other hand it should concentrate on the visual user interface (VUI). The software that recognizes VUI is the visual interface design. 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 key element of visual interface design. The aim is to present the programs components on the screen 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 for distinguishing objects with similar patterns. Patterns are created by simple recognizable graphic symbols and value is given to them by association. Visual interface design creates symbols for the objects in the interface. If the program created manages a class room, you know that, tables, chairs, fans, lights, boards, chalk are the fundamental elements. They form the building blocks for creating the interface. A recognizable visual symbol is needed for these fundamental elements. For instance Chairs, Tables, Fans, Lights and Boards could be represented as given in Fig 5.1.

106

ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

|---------|

Chairs

NOTES

------------|| ||
|| || X

Tables

Fans

|| || ******

lights

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

Boards

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 the objects are represented as a list box, the symbols only should be present in the list box to represent the objects. Whether it be a dialog box, text or a tool bar the symbol only should be used to represent the object. 5.6.3 Restricting The Vocabulary

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

107

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

Input Delete Draw Create

______________________________________________________

Output

Idioms Application Specific Commands and Feedback

Scrolling Sorting Dialogs

_____________________________________________

Double
Click Button click Selection

Compounds

Edit Fields Checkbox

Generic Input and output actions and symbols _____________________________ Primitives Smallest indivisible actions

Highlighting

Click Drag Key Press

and feed back mechanisms Cursor Text

Figure 5.2 The Canonical Vocabulary The canonical vocabulary in Fig 5.2 is comprised of the idioms, compounds and primitives. Idioms combine compounds with knowledge of the problem known as domain knowledge. Application specific commands and feed back forms the idioms. The input at this level would be commands such as delete, create and draw. The expected output would be a scrolling effect, sorted output or dialogs. The next level is the compounds. They represent the complex constructs created by combining one or more of the primitives. It is comprised of generic input and output actions and symbols. The input at this level in the GUI context would be actions such as double clicking, clicking the button and manipulating the objects such as push button and check box. The target controls would be edit fields and check box. Highlighting would be a possible output at this level. The next level is the primitives. It is comprised of the smallest indivisible actions and feed back mechanisms. They form the atomic elements of which every thing in the language is 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 design follows 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 a secondary copy on disk. The various functions of the file system are
108 ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

5.7.1

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. Saving

NOTES

It is maintaining a secondary copy on disk. An important function of the file system is how to save a file. This option will write the changes made to the in memory copy on to the on disk copy of the document. The program will automatically save the document. When the user requests the close function, the program will write the changes to the disk. The program 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 SAVE dialog 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 the original 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 applications tool bar. If the user decides to rename the document, the user can just click on it and edit it in place.
109 ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

5.7.3.3 Placing and Repositioning the document Most documents that are edited already exist. They are opened and not created from scratch. The position in the file system is fixed. If the user wants to explicitly place the document some where in the file system hierarchy, a dialog similar to Save As dialog appears with the current document high lighted. The user can then move the file to any desired 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 the user 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 the disk file. Therefore, format specification shouldnt be associated with the act of saving the file to disk. The physical format of the document should be specified by way of a small dialog 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 the tool to reverse the changes made to the document. The file system should be the mechanism for 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 creating a document, this action should be supported. A abandon function on the main menu would be sufficient to achieve this. This function would involve significant data loss. Therefore, it should 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 copy and 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 with various statistics about it, such as the time it was recorded and its length. With a click, the user 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 mechanisms to put in the repository and take them back. The retrieval system is a method for finding things in a repository. It is a logical system that allows the goods to be located according to some abstract value like the name, position or based on the features of the contents.

110

ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

5.8.1 Retrieval Methods There are three ways to find a document. The first method is positional retrieval. This is achieved by remembering where you left it. The second method is identity retrieval. You can retrieve by remembering its identity name. The last method is associative retrieval. This is searching based on some features of the document. For instance, if you want to find a book on Visual Programming, or a book containing photographs of cricketers, the method should be associative retrieval. The positional and identity retrieval also functions as storage systems. If the retrieval system 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 user to find the book according to a feature of the book. Apart from the feature the indices also give 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 this number, we can locate the shelves containing books in the range of the number we are searching 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 book is found logically from the system of retrieval. The shelves and numbers are the storage system. The card indices are the retrieval system. The books are identified with one system and retrieved with the help of another system. The customer identifies the book by using the retrieval system. The librarian retrieves the book by using the storage system. The retrieval system are also based on associative search. If the associative retrieval system remembers 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
111

NOTES

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

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 to port to the secondary platform. There are two ways for simultaneous multi platform development. 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 will consume time for writing the complicated code as well as for debugging. The software developer manager should avoid uncertainty and delay. If Else statements can be added to the source code to support an extra hard ware platform. Software development becomes harder and more complex. Every design decision must be made for two platforms. Commercial libraries of code are available which supports development on multiple platform simultaneously. To achieve multiple platform development, GUI is designed generically. This would be easy for the development team. The users would not prefer this. 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 the menu bar. First, you develop for a single platform. Mostly, it will be Windows, which will be the main market. Avoid the complexities of multi platform development. Once you finish the first version with the maximum speed possible, ship it to the largest possible market. Now you would generate revenue while you start development for the second platform. Single platform development is the correct course of action. The needs of secondary markets shouldnt delay the needs of primary markets. Now a working model of the product running on Windows is available. This could serve as a prototype for the versions to run on other 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 cost involved can be reduced by hiring less experience programmers because negligible design 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,
112 ANNA UNIVERSITY CHENNAI

VISUAL PROGRAMMING

where as the Macintosh version must behave like a Mac program at the detail level. For achieving this, local expertise is needed. 5.9.2 The Myth of Interoperability Generally, Windows programmers have to port DOS legacy programs. The programs in DOS would be character based and it would be in command line environment. The Windows program should emulate the DOS program as closely as possible. When DOS program is converted to Windows, The DOS users would be disappointed if the program is different from what they already know. The corporate users work in heterogeneous environments and they want the Windows version to work the same way as their DOS system. This is interoperability. Followers of interoperability feel that DOS customers are satisfied with the Windows equivalent because of the way the Windows equivalent program behaves. The organization also would not like to invest in training on Windows platform as they 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 be avoided in the software implementing user interface design were discussed. Obscure characteristics 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 identity retrieval systems were introduced.

NOTES

113

ANNA UNIVERSITY CHENNAI

DMC 1755

NOTES

NOTES

114

ANNA UNIVERSITY CHENNAI