I ns t i t ut eo fMa na g e me nt & Te c hni c a lSt udi e s
VI SUALPROGRAMMI NG 500
Di p l o mai nc o mp u t e rAp p l i c a t i o n www. i mt s i ns t i t ut e . c om
IMTS (ISO 9001-2008 Internationally Certified) VISUAL PROGRAMMING
VISUAL PROGRAMMING
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING CONTENTS UNIT – I 01-25 Windows Programming: GUI concept – Hungarian Notation – data types – Handles – Message driven architecture – Message Processing & Loop , GDI – Brush – Pen, font, cursor, menu, Keyboard & mouse handling – Displaying text and graphics – Dialog boxes controls – Winmain procedure – Files – Clipboard – printer handling – DDE – DLL’s – OLE – COM - ODBC – Window registry – New executable [NE] and Portable Executable Files (PE). UNIT – II 26-50 Introduction to Visual Basic – Variables – constants – strings – Data types – Tools and Techniques. UNIT – III 51-66 Organizing information via code – Arrays – Organizing information via controls – Control arrays – List and Combo boxes – Flex grid control Building Large Projects – Navigating among forms. UNIT – IV 67-90 Working with interface – Microsoft windows common controls 6.0 – Menus – MDI forms – DDE properties – DDE events – DDE methods – OLE properties – ActiveX Controls creation & image – Database access – Data Control – Field Control – Data grid – Record set using SQL to manipulate data. UNIT – V 91-98 Introduction to graphics – Fundamentals of graphics – Screen Scales – Line and Shape controls – Graphics via code – Lines and Boxes – Circles – Ellipse and Charts. Basic File Handling – Building your own ActivxX Controls.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING
1
UNIT-1 WINDOWS PROGRAMMING 1.1 GRAPHIC USER INTERFACE (GUI) DEFINITION A GUI interface allows the users to navigate and interact with information on their computer screen by using a mouse to ‘point’, ‘click’ and ‘drag’ the icons and other data on the screen instead of typing in words and phrases. Example of GUI is Windows operating system. Advantages of GUI
very user friendly
Requires less human intervention and more machine work.
Cost effective
Background printing
Multiple programs running
Advanced built-in utilities
Text Based System Vs GUI Text Based System
Graphical User Interface
Based only on characters
Includes both characters and graphics
User strain is more
User strain is less
User can use only keyboard
Can use both keyboard and mouse
Occupies less space
Occupies more space
Reliability and efficiency is more
More efficiency and Less reliability
Terms Used in GUI: Icon: A small image, usually symbol, used to graphically represent a software program file or function on a computer screen. Icon makes it easier to recognise and locate these things. Click or (Single click): Click or single click is operating the left side of the mouse button once. Double Click: Double click is the operation of clicking the left side button of the mouse two times. Right Click: Right Click is the operation of clicking the right side button of the mouse.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING
2
Drag and Drop: Using Mouse, the user can make a single click on the object, moves it to the preferred location by pulling it and putting it. Mouse Pointers: Pointers used to point and make a click on the icons. 1.2 HUNGARIAN NOTATION: Microsoft’s Chief Architect Dr.Charles Simonyi introduced an identifier naming convention that adds a prefix to the identifier name to indicate the functional type of the identifier. This system is widely used in Microsoft. This method is known as Hungarian Notation. Advantages of the conventions: The following naming conventions provide a very convenient framework for generating names that satisfy the above criteria. The basic idea is to name all quantities by their types. i)
The names are mnemonic.
ii)
The names will be suggestive. We will be able to map any name into the type of the quantity hence obtaining information about the shape and the use of the quantity.
iii)
The names will be consistent because they have produced by the same rules.
iv)
The decision on the name will be mechanical, thus speedy.
v)
Expressions in the program can be subjected to consistency checks. pX
Pointer to X
dX
Difference between two instances of type X, X+dx is of type X.
cX
Count of instances of type X
1.3 DATA TYPES Data types define the type of value. BOOL
-
A Boolean value
BSTR
-
A 32 bit character pointer
BYTE
-
An 8 bit integer that is not signed
COLORREF
-
A 32 bit value used as a colour value
DWORD
-
A 32 bit unsigned integer or the address of a segment and it’s associated offset
LONG
-
A 32-bit signed integer
LPARAM
-
A 32 bit value passed as a parameter to a window procedure or callback function
LPCSTR
-
A 32 bit pointer to a constant character string
LPSTR -
A 32 bit pointer to a character string
LPCTSTR
-
A 32 bit pointer to a constant character string that is
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING
3 portable for Unicode and DBCS
LPTSTR
-
A 32 bit pointer to a character string that is portable for Unicode and DBCS
LPVOID
-
A 32 bit pointer to an unspecified type.
LRESULT
-
A 32 bit value returned from a window procedure or call back function
UINT
-
A 16 bit unsigned integer on windows versions 3.0 and 3.1; a 32 bit unsigned integer on Win32
WNDPROC
-
A 32 bit pointer to a window procedure
WORD -
A 16 bit unsigned integer
WPARAM
-
A value passed as a parameter to a window procedure or callback function
1.4 HANDLE 1. A pointer to a pointer is a variable that contains the address of another variable, which in turn contains the address of the desired object. In certain operating systems, the handle points to a pointer stored in a fixed location in memory, whereas that pointer points to a movable block. If applications start form the handle whenever they access the block the operating system can perform memory management tasks such as garbage collection without affecting the applications. 2. Any token that an application can use to identify and access an object such as device, a file, a window or a dialog box. User defined handles permit developers to design handles that are meaningful to the application. A user defined handle can be defined in a type declaration not in a function declaratory. When the remote procedure has a user defined handle as a parameter or as an implicit handle the client stubs call the binding routine after the remote call. 1.5 MESSAGE DRIVEN ARCHITECTURE MESSAGE A structure or set of parameters used for communicating information or a request. Messages can be passed between the operating system and an application, different applications, threads within an application, and windows within an application. Applications written for MicroSoft Windows are “message driven�. In response to events such as mouse clicks, keystrokes, window movements and so on, window sends messages to the proper window framework. Applications process windows messages like any other applications for windows. The framework also provides some enhancements that make processing messages easier, more maintainable and better encapsulated.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING
4
The message loop in the Run member function of class CWinApp retrieves queued messages generated by various events. For example when the user clicks the mouse, Windows sends several mouse-related messages, such as WM_LBUTTONDOWN when the left mouse button is pressed and WM_LBUTTONUP when the left mouse button is released. The framework’s implementation of the application message loop dispatches the message to the appropriate window. There are three main categories: 1. Windows messages This includes primarily those messages beginning with the WM-prefix, except for WM_COMMAND. Windows and views handle Windows messages. These messages often have parameters that is be used in determining how to handle the message. 2. Control notifications This includes WM_COMMAND notification messages form controls and other child windows to their parent windows. For Example, an edit control sends its parent
WM_COMMAND
message
containing
the
EN_CHANGE
control
notification code when the user has taken an action that may have altered text in the edit control. The windows handler for the message responds to the notification message in some appropriate way such as retrieving the text in the control. The framework routes control notification messages like other WM_ messages. One exception is the BN_CLICKED control notification message; this message is treated specially as a command message and routed like other commands. 3. Command Messages This includes WM_COMMAND notification messages from user interface objects: menus, tool bar buttons and accelerator keys. The framework processes commands differently from other messages and they can be handled by more kinds of objects. 1.6 MESSAGE LOOP When no windows messages are being processed the framework calls CWinApp member function OnIdle. Override OnIdle to perform background tasks. The default version updates the states of user interface objects such as tool bar buttons and performs clean up of temporary objects created by the framework in the course of its operations. A program loop is one that retrieves messages from a thread’s message queue and dispatches them to the appropriate window procedures. MESSAGE MAP: Message Map is a mechanism to route Window messages and commands to the windows, documents, views and other objects in MFC application. Each framework class that
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING
5
can receive messages or commands has its own “message map�. The framework uses message maps to connect messages and commands to their handler functions
yes Available message
Get/translate/Dispatch
no
Idle Processing yes Available message no yes More idle tasks no Sleep Until Message
Message Loop When windows messages are being processed, the framework calls the CWinApp member function Run member function. A framework application spends most of its time in the rum member function of class CWinApp. After initialization, WinMain calls Run to process the message loop.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING
Edit Clear All menu item selected
ID_EDIT_CLEAR_ALL
Document Object
OnEditClearAll()
Clears all document data
A simple message loop consists of one function call to each of the three functions, GetMessage, TranslateMessage and DispatchMessage. MSG msg; While(GetMessage(&msg,NULL,0,0)) { TranslateMessage(&msg); DispatchMessage(&msg); } The GetMessage function retrieves a message form the queue and copies it to a structure of type MSG. It returns a nonzero value unless it encounters the WM_QUIT message, in which case it returns FALSE and ends the loop. In a single threaded application, ending the message loop is often the first step in closing the application. An application can end its own loop by using the PostQuitMessage function, typically in response to the WM_DESTROY message in the window procedure of the application’s main window. A thread’s message loop must include translateMessage if the thread is to receive character input from the keyboard. The system generates virtual key messages ( WM_KEYDOWN and WM_KEYUP) each time the user presses a key. A virtual key message
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
6
VISUAL PROGRAMMING
7
contains a virtual key code that identifies which key was pressed, but not its character value. To retrieve this value the message loop must contain TranslateMessage, which translates the virtual key message into a character message (WM_CHAR) and places it back into the application message queue. The character message can then be removed upon a subsequent iteration of the message loop and displayed to a window procedure. The DispatchMessage function sends a message to the window procedure associated with the window handle specified in the MSG structure. If the window handle is NULL, DispatchMessage does nothing with the message. An application’s main thread starts its message loop after initializing the applications and creating at least one window. Once started the message loop continues to retrieve messages from the thread’s message queue and to dispatch them to the appropriate windows. The message loop ends when the GetMessage function removes the WM_QUIT message from the message queue. When no window messages are being processed, the framework calls the member function OnIdle. 1.7 GRAPHIC DEVICE INTERFACE (GDI): Applications draw to an output device by calling Graphic Device Interface (GDI) functions. The GDI library gdi.dll calls device drivers. The device drivers perform specific operations on the actual physical hardware.
The graphical component of the Microsoft
Windows graphical environment is the graphic device interface. It communicates between the application and the device driver. In the GDI environment there are two working spaces, logical and physical. Logical space is inhibited by applications whereas physical space is the real world of devices with limited colour, different output formats and drawing capabilities. The objects in the GDI are pen, brushes, fonts, palettes and bitmaps. Objects are converted from logical objects to physical objects using the realization process.
Graphic object Bitmap
Associated Attributes size in bytes, dimensions, in pixels, colour format, compression schemes and so on.
Brush
style, colour, pattern and origin
Palette
Colours and size
Font
Typeface name, width, height, weight, character set and so on
Path
shape
Pen
style, width and colour
Region
Location and dimensions
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING
8
Brush: Brushes are used to fill the interior of drawing objects.
A brush is created by
CreateBrushIndirect function. This function accepts a pointer to LOGBRUSH structure which specifies the brush style, colour and pattern. A brush pattern can be based on bitmap. In order to provide a smooth appearance it is necessary to align the origin of a brush bitmap. Applications can explicitly specify the origin through SetBrushOrgEx. The brush origin is a pair of coordinates with respect to the upper left corner of the window’s client area. Additional functions assisting in the creation of brushes are CreateSolidBrush, CreatePatternBrush and CreateHatchBrush. Pen: Pens are used to draw lines, curves and the contours of other shapes. A pen is created using the CreatePen function. When calling CreatePen applications specify the pen’s width, style and colour. The LOGPEN structure defines the pen’s width, colour and style. Font: Before displaying an output text, select a logical font for text output. Logical fonts are created by calling the CreateFont function. This function takes a LOGFONT structure as a parameter. Icon: Icons and cursors are like images but have attributes that distinguish them from images. When we create a new icon or cursor, the graphics editor first creates an image for VGA. The image is initially filled with the screen colour. If the image is a cursor, the hot spot is initially the upper left corner. Menu: A menu is a list of available options. A menu is probably the most important part of the consistent user interface that windows programs offer and adding a menu in the program. A list of options from which a user can make a selection in order to perform a selected action such as choosing a command or applying particular format or part of a document. A windows menu bar is displayed immediately below the caption bar. This menu bar is sometimes called as a main menu. Items listed in the top level menu, usually invokes drop down menu which are also called as “popup menu”. 1.8 KEYBOARD HANDLING All Win-32 based applications should accept user input from the keyboard as well as from the mouse. A Win-32 based application receives keyboard input in the form of messages posted to its windows. Keyboard Input Model: The system provides device-independent keyboard support for applications by installing a keyboard device driver appropriate for the current keyboard. The system provides language independent keyboard support by using the language specific keyboard layout currently selected by the user or the application. The keyboard device driver receives scan
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING
9
codes from the keyboard which are sent to the keyboard layout where they are translated into messages and posted to the appropriate windows in our application. Assigned to each key on a keyboard is a unique value called a scan code, a device independent identifier for the key on the key board. A Keyboard generates two scan codes when the user types a key, one when the user presses the key and another when the user releases a key. The keyboard device driver interprets a scan code and translates it to a virtual key code, a device independent value defined by the system that identifies the purpose of a key. After translating a scan code the keyboard layout creates a message that includes the scan code the virtual key code and other information about the keystroke and then places the message in the system message queue. The system removes the message from the system message queue and posts it to the message queue of the appropriate thread. Eventually the thread’s message loop removes the message and passes it to the appropriate window procedure for processing. The pictorial representation of keyboard input model is given below.
keyboard Scan code Keyboard device driver
System Message Queue
messages
Thread Message Queue
Thread message loop
Window procedure
messages
KeyStroke messages: Pressing key results in a WM_KEYDOWN or WM_SYSKEYDOWN message being place in the thread message queue associated with the window that has the keyboard focus. Releasing key results in a WM_KEYUP or WM_SYSKEYUP messages being placed in the queue. Keyup and keydown messages occur in pairs but if the user holds down a key long enough to start the keyboard’s automatic repeat feature, the system generates a number of WM_KEYDOWN or WM_SYSKEYDOWN messages in a row. It then generates a single WM_KEYUP or WM_SYSKEYUP message when the user releases the key. 1.9 MOUSE HANDLING The mouse is an important but optional user input device for win-32 applications. A win-32 application receives mouse input in the form of messages that are sent and posted to its windows.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING
10
Mouse Cursor: When the user moves the mouse, the system moves a bitmap on the screen called the mouse cursor. The mouse cursor contains a single point called the hot spot, appoints that the system tracks and recognizes the position of the cursor. When a mouse event occurs, the window that contains the hot spot typically receives the mouse message resulting from the event. Mouse Messages: The mouse generates an input event whenever the user moves the mouse or presses or releases a mouse button. The system converts mouse input events into messages and posts them to the appropriate thread’s message queue. When mouse messages are posted faster than a thread can process them, the system discards all but the most recent mouse message. A window receives a mouse message when a mouse event occurs while the cursor is within the borders of the window or window captured the mouse. Mouse messages are divided into two groups, client area messages and non-client area messages. Client area mouse messages: A window receives a client area mouse message when a mouse event occurs within the window’s client area. The system posts one of the following messages when the user presses or releases a mouse button while the cursor is within the client area. Message
meaning
WM_LBUTTONCLICK
The left mouse button was double clicked
WM_LBUTTONDOWN
The left mouse button was pressed
WM_LBUTTONUP
The left mouse button was released
WM_MBUTTONDBLCLK
The middle mouse button was double clicked
WM_MBUTTONDOWN
The middle mouse button was pressed
WM_MBUTTONUP
The middle mouse button was released
WM_RBUTTONDBLCLK
The right mouse button was double clicked
WM_RBUTTONDOWN
The right mouse button was pressed
WM_RBUTTONUP
The right mouse button was released
Non-client area mouse messages: A window receives a non client area mouse message when a mouse event occurs in any part of a window except the client area. A window’s non client area consists of its border, menu bar, title bar, scroll bar, window menu, minimize button and maximize button. For example moving the cursor in the non client area generates a WM_NCMOUSEMOVE message.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING 1.10 DISPLAYING TEXT AND GRAPHICS TEXT OUTPUT Text output is the most common type of graphics output found within the client area of win-32 based application. The Win-32 API provides a complete set of functions to format and draw text in an application’s client area and on a page of printer paper. The text functions falls in two categories: format the text and to draw the text. The formatting functions align text, set the inter character spacing, set the text and text background colours and justify text. The drawing functions draw individual characters or entire strings of text. Formatting text The formatting functions can be divided in to three categories:
Those that retrieve or set the text formatting attributes for a device context
Those that retrieve character widths
Those that retrieve string widths and heights
Text formatting Attributes The text formatting functions are *SetBkColor * SetBkMode * SetTextAlign *SetTextCharacterExtra *SetTextColor *SetTextJustification. The functions to retrieve the current text formatting attributes for any device context are * GetBkColor * GetBkMode * GetTextAlign *GetTextCharacterExtra *GetTextColor *GetTextExtentPoint32 Applications need to retrieve character width of the data when they perform tasks such as fitting strings of text to page or column widths. In addition to this, applications need to retrieve the width and height of the entire strings. The functions used to retrieve string’s width and height is GetExtentPoint32 and GetTabbedTextExtent. Drawing Text After setting the required formatting options the user can draw the characters and symbols using the text-output functions. The text output functions DrawText and TabbedtextOut are part of window manager and found in the library USER.DLL, and the ExtTextOut and TextOut functions are in the library GDI.DLL. When an application calls one of these functions, the operating system passes the call to the graphics engine, which in turn passes the call to the appropriate device driver.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
11
VISUAL PROGRAMMING
12
At the device driver level all of these calls are supported by one or more calls to the driver’s own ExtTextOut or TextOut function. An application will receive the fastest execution by calling the ExtTextOut call for the device. But for some instance it is necessary to call the other three functions directly, for example, to draw multiple lines of text within the borders of a specified rectangular region, it is more efficient to call the DrawTxt
function. To create
multicolumn table with justified columns of text it is more effective to call the TabbedTextOut function. DrawText Function: int DrawText{ HDC hDC,
// handle to device context
LPCTSTR lpString,
//pointer to string to draw
int nCount,
//string length in characters
LPRECT lpRect,
//pointer to struct with formatting dimensions
UINT uFormat
//text formatting flags
}; TabbedText function: Long TabbedTextOut{ HDC hDC,
// handle to device context
int X,
// X- coordinate of staring position
int Y,
// Y-coordinate of staring position
LPCTSTR lpString
//pointer to string
int nCount
// number of characters in string
int nTabPositions
//number of table in array
LPINT lpnTabStopPositions // pointer to array for tab positions int nTaborigin
// x-coordinate for tab position
}; ExtTextOut Function: BOOL ExtTextOut{ HDC hDC,
// handle to device context
int X,
// X- coordinate of reference point
int Y,
// Y-coordinate of reference point
UINT fuOptions
// text output options
CONST RECT *lprc
//optional clipping and/or opaquing rectangle.
LPCTSTR lpString
//pointer to string
UINT cbCount CONST INT *lpdx
// number of characters in string //pointer to array of intercharacter spacing
};
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING
13
TextOut Function: BOOL TextOut{ HDC hDC,
// handle to device context
int X,
// X- coordinate of starting position
int Y,
// Y-coordinate of starting position
LPCTSTR lpString
//pointer to string
int cbString
//number of characters in string
}; DRAWING GRAPHICS Device Contexts A device context is a structure that defines a set of graphic objects and their associated attribute and the graphic modes that affect output. The graphic objects include a pen for line drawing, a brush for printing and printing, a bitmap for copying or scrolling parts of the screen, a palette for defining the set of available colors, a region for clipping and other operations and path for painting and drawing operations. Device Context Types: There are four types of device contexts: display, printer, memory and information. Each type serves a specific purpose as described in the following table. Device Context Display Printer
Description Supports drawing operations on a video display Supports drawing operations on a printer or plotter
Memory
Supports drawing operations on a bitmap
Information
Supports the retrieval of device data
Displaying Bitmaps: A bitmap is a graphical object used to create, manipulate and store images as files on a disk. A bitmap is a structure that contains the following elements *A header that describes the relation of the device on which the rectangle of pixels was created, the dimensions of the rectangle, the size of the array of bits and so on. * A logical palette *An array of bits that defines the relationship between pixels in the bitmapped image and entries in the logical palette. A bitmap size is related to the type of image it contains. Bitmap images can be either monochrome or color. In an image, each pixel corresponds to one or more bits in a bitmap. Monochrome images have a ratio of one bit per pixel. Color imaging is more complex. The
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING number of colors that can be displayed by a bitmap is equal to 2 times the number of bits per pixel. A 256 color bitmap requires 8 bits per pixel. There are two classes of bitmaps: Device independent bitmaps and device dependent bitmap. The bitmap structure defines the type, width, height, color format and bit values of a bitmap. Typedef struct tagBITMAP{ LONG bmType; LONG bmWidth; LONG bmHeight; LONG bmWidthBytes; WORD bmPlanes; WORD bmBitsPixel; LPVOID bmBits; }BITMAP; Drawing Filled Shapes: Filled Shapes are geometric shapes that are outlined by using the current pen and filled by using the current brush. There are five filled shapes; ellipse, chord, pie, polygon and rectangle. Ellipse: The Ellipse function draws an ellipse. The center of the ellipse is the center of the bounded rectangle. BOOL Ellipse(HDC hdc, int nLeftRect, int nTopRect, int nRightRect, int nBottomRect); Drawing Chord: The chord function draws a chord. BOOL Chord( HDC hdc, int nLeftRect, int nTopRect, int nRightRect, int nBottomRect int nXRadial1, int nYRadial1, int nXRadial2, int nYRadial2);
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
14
VISUAL PROGRAMMING
15
Drawing Pie: The Pie function draws a pie shaped wedge bounded by the intersection of an ellipse and two radials. The pie is outlined by using the current pen and filled by using the current brush. BOOL Pie( HDC hdc, int nLeftRect, int nTopRect, int nRightRect, int nBottomRect int nXRadial1, int nYRadial1, int nXRadial2, int nYRadial2); Drawing a Polygon: The Polygon function draws a polygon consisting of two or more vertices connected by straight lines. The polygon is outlined by using the current pen and filled by current brush and polygon fill mode. BOOL Polygon( HDC hdc, CONST POINT *lpPoints, int nCount); 1.11 DIALOG BOX CONTROLS A dialog box is a temporary window an application creates to retrieve user input. An application typically uses dialog boxes to prompt the user for additional information for commands. A dialog box usually contains one or more controls (child windows) with which the user enters text, chooses options, or directs the action of the command. Win32 API provides many functions, messages and controls to create and manage the dialog box and thus makes it easy to develop the user interface for an application. Dialog box is one of the way to get the input from the user. For example, File open Command requires the name of the file to open so an application should use a dialog box to prompt the user for the name of the file. In general there are two types of dialog boxes, such as 1. Model
and
2. Modeless A Modal dialog box requires the user to supply information or cancel the dialog box before allowing the application to continue. A modeless dialog box allows the user to supply the information and return to the previous task without closing the dialog box.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING
16
The dialog box can be created using either the DialogBox or CreateDialog function. DialogBox creates a modal dialog box. CreateDialog creates a modeless dialog box. DialogBox Function: The DialogBox macro creates a modal dialog box from a dialog box template resource. Dialog box does not return control until the specified callback function terminates the modal dialog box by calling the EndDialog function. The DialogBox macro uses the DialogBoxParam function. int DialogBox( HINSTANCE hinstance, LPCTSTR lpTemplate, HWND hwndParent, DLGPROC lpDialogFunc); CreateDialog Function: The CreateDialog macro creates a modeless dialog box from a dialog box template resource. This uses the CreateDialogParam Function HWND CreateDialpg( HINSTANCE hinstance, LPCTSTR lpTemplate, HWND hwndParent, DLGPROC lpDialogFunc); MESSAGE BOX A message box is a special dialog box that an application can use to display messages and prompt for simple input. A message box typically contains a text message and one or more buttons. An application creates the message box by using the MessageBox or MessageBoxEx function. The MessageBoxEx function allows the user to specify the language. MessageBox Function: This function creates displays and operates a Message Box.
The message box
contains an application defined message and title, combination of predefined icons and push buttons. int MessageBox( HWND
hwnd,
LPCTSTR
lpText,
LPCTSTR lpCaption, UINT uType);
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING
17
MessageBoxEx Function: In addition to the above specification this function has wLanguageid parameter specifies the set of language resources. int MessageBoxEx( HWND
hwnd,
LPCTSTR
lpText,
LPCTSTR lpCaption, UINT uType, WORD wLanguageid); 1.12 WINMAIN PROCEDURE The WinMain function is called by the system as the initial entry point for Win32 based application. int WINAPI WinMain ( HINSTANCE hInstance, HINSTANCE hprevInstance, LPCTSTR lpCmdLine, int nCmdShow); Parameters: hInstance Handle to the current instance of an application. hPrevInstance Handle to the previous instance of the application. For a win32 based application this parameter is NULL. lpCmdLine Pointer to a null terminated string specifies the command line for the application, excluding the program name. To retrieve the entire command line use GetCommandLine function. nCmdShow Specifies how the window is to be shown. Values of this parameter are given below: Value SW_HIDE SW_MINIMIZE
Meaning Hides the window and activates another window Minimizes the specified window and activates the top-level window in the system’s list
SW_RESTORE
Activates and displays a window. The window is restored to its original size
SW_SHOW
Activates a window and displays it in its current
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING
18 size and position
SW_SHOWMAXIMIZED
Activates a window and displays it as maximized window
SW_SHOWMINIMIZED
Activates a window and displays it as minimized window
SW_SHOWMINNOACTIVE
Displays a window as an icon. The active Window remains active.
SW_SHOWNORMAL
Activates and displays a window. If the window is maximized or minimized restored to its original size and position.
Return values: If the function succeeds, terminating when it receives a WM_QUIT message it should return the exit value contained in that message’s wparam parameter. If the function terminates before entering the message loop it should return zero.
1.13 FILES The traditional concept of file is a block of data on a storage device identified by a file name. A file is the basic unit of storage that enables a computer to distinguish one set of information from another. Files are stored on storage media, such as disk, tapes and can be organized into groups called directories. The file I/O functions enable applications to create, open, modify and delete file. Creating and Opening file: The Create File function can create a new file or open an existing file. HANDLE CreateFile( LPCTSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisPoint, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile ); When an application creates a file, it must specify the operations on file such as whether it will read from the file or write into the file or both, and also it must specify the action to be taken when the file does not exist. In general when the create file function is used if the
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING
19
specified file does not exist it will create a new one or if the file exists it overwrites the contents of it. CreateFile also enables the user to specify whether it wants to share the file for reading, writing, both or neither. A file that is not shared can not be opened more than once by the first application or by another application until the first application has closed the file. The operating system assigns a unique identifier called a file handle to each file that is opened or created. Application can use the file handle in all file operations. It is valid until the file is closed using CloseHandle function, which closes the file and flushes the buffer. Reading and Writing: Every opened file has a file pointer that specifies the next byte to be read or the location of the next byte to be written. When a file is opened for the first time, the file pointer is positioned at the beginning of the file. For each read or write operation the file pointer is advanced. The filepointer can be moved to certain position by using SetFilePointer function. The Read and Write operation is carried out by using ReadFile and WriteFile functions respectively. These functions read and write a specified number of bytes at the location indicated by the file pointer. The data is read and written exactly as specified but do not format the data. An application can truncate or extend the file using SetEndOfFile function. If two applications write to the same location in the file at the same time, to prevent this the application should lock the area of the file by using the LockFile() function. When application completes the write operation, it unlocks the region of the file using UnlockFile() function. All locked regions of a file should be unlocked before closing a file. FILE I/O functions Function
meaning
CreateFile
Creates or opens a file
CreateFileMapping
Create a named or unnamed file mapping object for a file
CreateDirectory
Creates a new directory
CopyFile
Copies an existing file to a new file
DeleteFile
Deletes a file
GetFileSize
retrieves the size of the file
LockFile
Locks a region of a file
MoveFile
Moves a file or a directory and its contents
ReadFile
Read data from a file
UnlockFile
Unlock a region in an open file
WriteFile
Writes data to a file.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING
1.14 CLIPBOARD The clipboard
is a set of functions and messages that enable Win32 based
applications to transfer data. Because all applications have access to the clipboard, data can be easily transferred between applications or within an application. The ClipBoard is a standard windows method of transferring data between a source and a destination. It is very useful in OLE operations. It is a system device shared by the entire windows session, so it does not have a handle or class of its own. A window procedure transfers information to or from the clipboard in response to the WM_COMMAND message. The clipboard is user driven. A window must not use the clipboard to transfer data without the user’s knowledge. Creating ClipBoard Viewer Window: A clipboard viewer window displays the current content of the clipboard and receives messages when the clipboard content changes. To create a clipboard viewer do the following
Add the window to the clip board viewer chain
Process the WM_CHANGECBCHAIN message
Process the WM_DRAWCLIPBOARD message
Remove the window from the clip board viewer chain before it is displayed. The OpenClipboard function opens the clipboard for examination and prevents other
applications from modifying the clipboard content. The CloseClipboard function closes the clipboard. The GetClipboardData function retrieves data from the clipboard in a specified format. The clipboards must have been opened previously. The SetClipboardData function places data on the clipboard in a specified format. 1.15 PRINTERS Printing is one of the most complex tasks in window based application. Printing from our application involves these three components:
The code in our application, which starts the printing process.
The printer drivers installed on both our system and the systems of users of our application.
The capabilities of the printers available to users of our application. The code in our application determines the type and quality of print output available
from our application. One of the chief features of Microsoft Win32 printing functions is their support of device independence. Instead of issuing device-specific commands to draw output on a particular printer or plotter an application calls high level functions from the graphics device interface (GDI). Retrieving a Printer Device Context
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
20
VISUAL PROGRAMMING When the user selects the print option in the file menu, we can call the printDlgEx function to display the print property sheet. The property sheet enables the user to provide information about the print job. For example, the user can specify a range of pages to print, the number of copies and so on. printDlgEx can retrieve a handle to a device context for a selected printer. The PrintDlgEx function is available on Windows 2000 or later. 1.16 DYNAMIC DATA EXCHANGE (DDE) The Win32 API provides several methods for transferring data between applications. One method is to use the DDE protocol. The DDE protocol is a set of messages and guidelines. It sends messages between applications that share data and uses shared memory to exchange data between applications. The DDEML is a dynamic Link Library that win32 based applications can use to share data. Instead of sending, posting and processing DDE messages directly, an application uses the DDEML functions to manage DDE conversations. A DDE conversation is the interaction between client and server applications. The DDEML also provides a facility for managing the strings and data that DDE applications share. To initiate a DDE conversation the client sends a WM_DDE_INITIATE message. Usually the client broadcasts this message by sending the SendMessage with -1 as the first parameter. Once a DDE conversation has been established the client can either retrieve the value of a data item from the server by issuing the WM_DDE_REQUEST message or submit a data item value to the server by issuing WM_DDE_POKE. WM_DDE_EXECUTE message allows the application to execute a certain command or series of commands.
To terminate a conversation either client or server uses a
WM_DDE_TERMINATE command. 1.17 DYNAMIC LINK LIBRARIES (DLL) A dynamic link library (DLL) is an executable file that acts as a shared library of functions. Dynamic linking provides a way for a process to call a function that is not part of its executable code. The executable code for the function is located in DLL, which contains one or more functions that are compiled, linked and stored separately from the processes that use them. DLL also facilitate the sharing of data and resources. Multiple applications cam simultaneously accesses the contents of a single copy of a DLL in memory. In static linking, the linker gets all the referenced functions from the static link library and places it in the code itself, whereas the dynamic linking links the referenced file only during the run. Thus it reduces the size of the executable file. Several applications share the same DLL and this saves the disk space in memory. Advantages of DLL: 
Saves memory and reduce swapping

Saves disk space
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
21
VISUAL PROGRAMMING
Upgrades to the DLL are easier
Supports Multilanguage programs
Provides mechanism to extend the MFC library classes A potential disadvantage of using DLL is that the application is not self contained; it
depends on the existence of a separate DLL module. 1.18 OBJECT LINKING AND EMBEDDING (OLE) Object Linking and Embedding, a technology for transferring and sharing information among applications. When an object such as an image file created with paint application is linked to a compound document, such as spread sheet or a document created with a word processing application the document contains only a reference to the object; any changes made to the contents of a linked object are seen in the compound document. When an object is embedded in a compound document, the document contains the copy of the object; any changes made to the contents of the original object are not seen in the compound document unless the embedded object is updated. OLE is a mechanism that allows the users to create and edit documents containing items or objects created by multiple applications. OLE incorporates many different concepts such as Linking and Embedding: Linking and Embedding are the two methods for storing items created inside an OLE document that were created in another application. In-Place Activation: Activating an embedded item in the context of the container document is called inplace activation or visual editing. Automation: Automation allows one application to drive another application. The driving application is an automation client or automation controller, and the application being driven is known as an automation server or automation component. Compound Files: Compound files provide a standard file format that simplifies structured storing of compound documents for OLE applications. Uniform Data transfer: Uniform Data transfer (UDT) is a set of interfaces that allow data to be sent and received in a standard fashion, regardless of the actual method chosen to transfer the data. Drag and Drop: This is an easy to use, direct manipulation technique to transfer data between applications, between windows within an application or even within a single window in an application.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
22
VISUAL PROGRAMMING Component Object Model: Component Object Model provides the infrastructure used when OLE objects communicate with each other. 1.19 COMPONENT OBJECT MODEL (COM) The Component Object Model (COM) is a platform independent, distributed, object oriented system for creating binary software components that can be interact. The Component Object Model(COM) is a component software architecture that allows applications and systems to be built from components supplied by different software vendors. These services provide distinctly different functionality to the user, however they share a fundamental requirement for a mechanism that allows binary software components supplied by different software vendors, to connect to and communicate with each other in a well defined manner. COM a component software architecture that
Defines a binary standard for component interoperability
Is programming language independent
Is provided on multiple platforms
Provides for robust evolution of component based applications and systems
Is extensible
In addition COM provides mechanisms for the following
Communications between components even across process and network boundaries
Shared memory management between components
Error and status reporting
Dynamic loading of components
COM fundamentals: The Component Object Model defines several fundamental concepts that provide the model’s structural underpinnings. These include:
A binary standard for function calling between components
A provision for strongly typed groupings of functions into interfaces
A base interface providing i)
A way for components to dynamically discover the interfaces implemented by other components.
ii)
Reference counting to allow components to track their own life time and delete themselves when appropriate
A mechanism to uniquely identify components and their interfaces.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
23
VISUAL PROGRAMMING
24
A “component loader” to set up component interactions and additionally in the cross process and cross-network cases to help manage component interactions.
1.20 ODBC : INTRODUCTION Open Database Connectivity (ODBC) is a widely accepted application programming interface for database access. ODBC is designed for maximum interoperability that is, the ability of a single application to access different database management systems with the same source code. Database applications call functions in the ODBC interface, which are implemented in database specific modules called drivers. The use of drivers isolates applications from database specific calls. The ODBC architecture has four components Application: performs processing and calls ODBC functions to submit SQL statements and retrieve results. Driver Manager: Loads and unloads drivers on behalf of an application. Processes ODBC function calls or passes them to driver. Driver: processes ODBC function calls, submits SQL requests to a specific data source, and returns results to the application. If necessary, the driver modifies an application’s request so that the request conforms to syntax supported by the associated DBMS. Data Source: Consists of the data the user wants to access and its associated operating system, DBMS, and network platform used to access the DBMS. 1.21 WINDOWS REGISTRY The registry is a hierarchical database used to centrally store application-specific and system-specific information. The registry provides a single means of locating, editing, and administering this data for both users and machines. Each location in the registry is called as a key. Each key contain both sub keys and data entries called values. User settings should be stored separately from computer settings. The respective keys are HKEY_CURRENT_USER and HKEY_LOCAL_MACHINE. Windows registry API’s can be used to get information into and out of the registry and examine system, application and user information stored in the registry. A set of registry API’s make information available through remote procedure calls (RPC) to windows management tools.
Registry is logically one data store; physically it
consists of three different files to allow maximum network configuration flexibility. Windows uses the registry to store information in three major categories user.dat – user specific information, in the form of user profiles are stored in user.dat. It contains log on names, desktop settings, start menu settings and so on.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING System.dat – Hardware or computer specific settings are contained in the system.dat. It contains all hardware configurations, Plug and Play settings and application settings. Policy.pol- System policies are designed to provide an override for any settings contained in the other two registry components. System policies can contain additional data specific to the network or corporate environment as established by the network administrator. 1.22 PORTABLE EXECUTABLE (PE) The structure of executable (image) files and object files under Microsoft Windows NT are referred to as Portable Executable (PE) and Common Object File Format (COFF) files.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
25
VISUAL PROGRAMMING
26
UNIT –II WELCOME TO VISUAL BASIC (VB) Welcome to Microsoft Visual Basic. It is considered “the fastest and easiest way to create application for Microsoft windows(r)”. Whether you are an experienced professional or brand new to windows programming, Visual Basic (VB) provides you with a complete set of tools to simplify rapid application development (RAD). Windows based applications have a consistent user interface that helps the user to simply ‘Point and Click’. Like a kid in a candy store who does not know the name of the toffee. He merely points it and the parent will buy it for him. This means that all windows application provides a picture (or an ‘icon’ as the jargon goes) or a button for a function. The user will point at that picture with a mouse and click. The computer simply jumps up to perform (or sometimes declines) the task. Visual Basic is an ideal medium for developing windows based application. Before the advent of visual Basic, programmers grappled with “C” code and tons of documentation to come up with a good interface. 2.1 WHAT IS VISUAL BASIC Visual Basic is an event driven programming language. The “Visual” part refers method used to create the graphical user interface (GUI). Rather than writing numerous lines of code to describe the appearance and location of interface elements, simply drag and drop the prebuilt objects into place on the screen. The “Basic” part refers to the BASIC language. A language used by more programmers than any other language in the history of computing. The Visual Basic programming language is not unique to Visual Basic. The Visual Basic programming system, Applications Edition included in Microsoft Excel, Microsoft Access, and many other windows applications user the same language. The Visual Basic programming system, Scripting Edition (VBScript) for internet programming is a subset of the Visual Basic language. Where Visual Basic can be used? 1. To create a small utility for yourself, 2. An application for a department, work group, a large enterprise-wide system, 3. Distributed applications spanning the globe via the internet. 2.2 FEATURES OF VISUAL BASIC
Data access features allows the user to create databases and front–end application for most popular database formats.
ActiveX technologies allow using the functionality provided by other applications, such as Microsoft Word, Microsoft Excel spreadsheet, and other windows applications.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING Internet capabilities make it easy to provide access to documents and applications

across the internet from your application. (ActiveX Documents) 2.3. CONTROLS Text Box Control In order to display or accept user input in the form of text like name, age, etc. It is used to display and edit the text in the box. A Text Box control is also called an edit field. The Picture Box A picture Box control can display a graphic from a bitmap, icon, or metafile, as well as enhanced metafile, JPEG, or GIF files. If the image is larger than the control, the image will be clipped. Label Box It allows the user to display the text. And the user can not change the text at run time. This box is used to display the titles, prompts etc. Option Button This button allows the user to display multiple choices from which the user can choose only option. Frame Visual Basic 6 can have only one set of option buttons to a form. In order to overcome this limitation, frame control can be used. Each group of control can be placed on a different frame. The frame control allows you to create graphical or functional grouping controls. To group controls, draw the frame first, and then draw controls inside the frame. List Box Visual Basic 6 provides the list Box control to display a list of items from which the user can choose one. The list can be scrolled if it has more items than it can be displayed at one time. Combo Box The user can either choose an item from the list or enter a value in the text box. The new value entered can be added to the existing data. The list Box and the combo Box can be used to display the data from a database. The data control is used in order to access data and to manipulate data in the list box and combo box. Data Data control provides access to databases through controls in the form. It makes the job of the developer easy when data has to be manipulated in a database. The data bound controls are used to display and access the data in the database. HScrollBar (horizontal scroll bar) Provides a graphical tool for quickly navigating through a long list of items or a large amount of information. This is used for indicating the current position on a scale, or as an input device or indicator of speed or quantity.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
27
VISUAL PROGRAMMING
28
VScrollBar (vertical scroll bar) Provides a graphical tool quickly navigating through a long list of items or a large amount of information. This is used for indicating the current position on a scale, or as an input device or indicator of speed or quantity. Timer control This control is used to activate the automatic alert by fixing the time interval. Command Button Creates a button, which the user can choose to carry out a command. The computer performs the task associated with the button by clicking it. Check Box Creates a box, which the user can easily choose to indicate if something is true or false, or to display multiple choices when the user can choose more than one. The Drive, Directory and File List Controls These controls are used to display available Drives, Directories and Files.
By
selecting a valid drive in the system, the user can see a hierarchical structure of directories and files in the system. The Line and Shape Controls These controls are used to draw lines, squares, circles, etc. The Image Control This is very similar to the Picture Box Control. If the stretch property in this control is set the image will be modified to the size of the control, Whereas in picture control the image is clipped or truncated. OLE(Object Linking and Embedding) This control allows linking the program to another object or program. For example, it is possible to place a Word Pad file in the program directly and edit it thorough the application. Using OLE it is possible to link Micosoft Excel, word, Ms Paint. The Visual Basic Integrated Development Environment (IDE) consists of the following elements. Menu Bar Context menus Tool bars Tool Box Project explorer window Properties window Object browser Form designer Code editor window Form layout window Immediate locals and watch windows
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING Menu Bar Displays the commands you use to work with Visual Basic. Besides the standard File, Edit, View, Window and Help menus, menus are provided to access functions specific to programming such as Project, format or Debug. Context Menus Contain shortcuts to frequently performed actions. To open a context menu, click the right mouse button on the object you are using. The specific list of shortcuts available from context menus depends on the part of the environment where you click the right mouse button. For example, the context menu displayed when you right click on the Tool Box lets you display the Components dialog box, hide the Tool Box, dock or undock the Tool Box, or add a custom tab to the Tool Box. Tool Bars Provide quick access to commonly used commands in the programming environment. You can click a button on the toolbar once to carry out the action represented by that button. But default, the Standard Toolbar is displayed when you start Visual Basic. Additional Toolbars for editing from design and debugging can be docked beneath the menu bar or can “float� if you select the vertical bar on the left edge and drag it away from the menu bar. Tool Box Provides a set of tools that you can use at design time to place controls on a form. In additions to the default toolbox, layouts by selecting Add Tab from the context menu and adding controls to the resulting tab. Project Explorer Window Lists the forms and modules in your current project. A project is the collection of files you use to build an application. Properties Window Lists the property settings for the selected form or control. A property is a characteristic of an object, such as size, caption, or colour. Object Browser Lists objects available for use in your project and gives you a quick way to navigate through your code. You can use the Object Browser to explore objects in Visual Basic and other applications, see what methods and properties are available for those objects, and paste code procedures into your application. Form Designer Serves as a window that you customize to design the interface of your application. You add controls, graphics, and pictures to a form to create the look you want. Each form in your application has its own form designer window.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
29
VISUAL PROGRAMMING Code Editor Window Serves as an editor for entering application code. A separate code editor window is created for each form or code module in your application. The programmer can change the font size of the code. Form Layout Window The Form Layout Windows allow you to position the forms in your application using a small graphical representation of the screen. Immediate, Locals, and Watch Windows These additional windows are provided for debugging your application. They are only available when you are running your application within the IDE. You will use a number of the tools that we just saw as you build more and more applications. For the time being just follow along. If the details and concepts discussed here are clear to you, there is no harm in experimenting. Font Properties The Font properties for a Form include the following: Font Name: Name of the font. Font Bold: If set to True, the text will be displayed in bold. Font Size : You can set the size of the text in points. To access the Font property, you can scroll up or down till you reach that property or you can press Ctrl+Shift+First letter of property. In this case pressing Ctrl+Shift+f will take you directly to the Font property. Position Properties Properties like Left, Top, Height and Width can be set at design time as well as runtime to locate the form at a place of your choice. StartUp Position This property is set at design time, specifies the position of the form at runtime. Form Method Let us now take a look at the Methods that are associated with the Form. Forms have methods that are used in code to control their behaviour. Visual Basic supports many methods to change the appearance and behaviour of the form at runtime. Move The Move method for example, allows the programmer to position the form at a desired location on the screen. The syntax of the move method is as follows; FormName.Move Left, [Top],[Width],[Height]
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
30
VISUAL PROGRAMMING Graphics Methods There are other properties for drawing lines, circle, clearing the form for any drawing object. There are methods like getting the colour of point at a particular location. Circle : to draw a circle(s). Line
: to draw a line(s).
Pset
: to draw a point with a given colour at a given location.
Point
: returns the colour of screen at the given location.
2.4 WORKING WITH A CONTROL After you have placed the control on the Form, you may want to change the location or the dimension. All the Windows application has a uniform size for their buttons. Also the location of various buttons follows certain rules. To re-size the control you are given total of eight sizing handles that look like small solid squares. Take a look at the figure above, during design time the appearance of these sizing handles indicate that the control has now got the focus, any activity you do will affect that control. You can select a control by simply moving the mouse pointer inside the control and clicking the left mouse button. The sizing handles will appear. The four handles on the four corners are to increase or decrease the length and breadth of the control proportionately. The two sizing handles on the horizontal edges are used to increase or decrease the height control. The two sizing handles on the vertical edges are used to increase or decrease the width of the control. To move a control to another location, click on the control, hold down the left mouse button and drag the control to a location of your choice. It is like re-sizing a window in Windows 95. The following figure shows the IDE of Visual basic , menu bar, tool bar, toolbox, form design, properties window and project explorer.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
31
VISUAL PROGRAMMING
32
FIG-1 INTEGRATED DEVELOPMENT ENVIRONMENT The figure-2 shows the label box, text box, command button, picture control (image size can not be stretched), Image control with stretch property, frames with check buttons and radio buttons. 2.5. VARIABLES The various values used during computation are stored in variables. Variables in Visual Basic hold information. Rules to form variables are i)
it can be up to 255 characters long
ii)
first character is a letter
iii)
can have any combination of letters, numerals and underscores and
The case of the letters in the variable name is irrelevant. Valid
Invalid
Baseball
1Baseball - starts with numerals
Net_pay
net&pay – Using the special char &
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING
33
FIG-2 – CONTROLS 2.5.1 Declaring Variables In order to write a program we need variables. Before the variable is used it has to be informed that the program that this particular word is a variable. The process or method of providing this information is called declaring a variable. Variables in Visual Basic are declared using the DIM statement. The syntax of DIM statement is Dim variablename [As type] Eg. Dim Total [As integer] 2.5.2 Variable Assignment Statements: Assignment statements are what you use to give a Visual Basic variable a (new) value. Visual Basic uses an equal sign for this operation; for example InterestRate
= .05
assigns the value 0.05 to the variable named InterestRate to 0.05. The variable name always appears on the left of the equality sign, and the value always appears on the right. Visual Basic must be able to obtain a value from the right side of an assignment statement, and it will do any processing needed to make this happen. For example: NewRate = .05+.1
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING would make the variable NewRate have the value 0.15. This is because VB would do the addition first, and then store the result in the variable. 2.6. DATA TYPES Variables have a name and a data type. The data type of a variable determines the internal representation in the memory, i.e how the bits/bytes representing those values are stored in the computer’s memory. The data type of a variable is specified during the declaration itself. One needs to use different types of variables for different requirements in order to optimize speed and memory requirements. If you know that a variable will always store data of a particular type, Visual Basic can handle that data more efficiently if you declare a variable of that type. The following table lists the various data types available in visual basic. Let us look at the various data types one by one. Integer This data type is used to store whole numbers, and cannot be used in calculations where decimals or fractions are involved. They can store reasonably large numbers. The integer data type occupies only two bytes of memory and is quite fast when used in calculations. Long It can hold much larger values than integer. It occupies twice as much space as the Integer. It must be used only where the calculations involve very large numbers, and is much slower than the Integer. Single This is the equivalent of the Floating-Point number. It can store fractions. It occupies 4 bytes of memory space and should be used where very high precision is not a must. Double This is used where higher precision values are used. It occupies 8 bytes of memory space. Currency This data type is used for holding values related to money. Byte This data type can hold values from 0 to 255. I cannot hold negative numbers or numbers larger than 255. Boolean This data type accepts only True or False values. Since the default value for all numeric data types is zero, the default value for a Boolean data type is also zero. Zero value is interpreted as False and a non–zero value is interpreted as True.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
34
VISUAL PROGRAMMING
35
Date This variable holds date and time data. It can hold time from January 1 100 to December 31, 9999, and time from 00.00.00(midnight) to 23.59.59 (one second before midnight) in one second increments. It occupies 8 bytes of memory. The date is displayed as per the settings in your computer. String Probably the most commonly used data type is the string. The string data type holds characters. You can have a single character in a string or many. A variable holding a string is called a string variable. One method of identifying variables of this type is to place a dollar sign($) at the end of the variable name: You can declare the variable as a ‘variable-length string or a fixed-length string’. By default, a string variable or argument is a variable-length string; the string grows or shrinks as you assign new data to it. Dim ItemName As string * Dim
ItemDescription
30 \
As String
a fixed-length \
a
string
Variable-length
string
The string Item Name will always be 30 characters long. If you assign a string of fewer than 30 characters, ItemName will be padded with enough trailing spaces to total 30 characters. If you assign a string that is too long for the fixed-length string, Visual Basic simply truncates the characters. In order to remove trailing spaces while working with fixed-length string, you have functions like Trim and Rtrim. More on Strings A string is simply a bunch of characters by double quotes. When people enter information into a text box, Visual Basic stores that information as a string. Thus, even if you have a text box meant to hold an amount, it starts out as a string. Probably the most common operation done with strings is to put two strings together and concatenate. To concatenate two strings, ampersand (&) symbol is used. For example: Title$ = “Queen” Name$ = “Elizabeth” FirstElizabeth = Tiles $ & Name$ Gives “QueenElizabeth” The & joins the strings in the order in which you present them. Finally, it is quite common to build up a long string with the & sign before using it in a message box. For example: Message = “This program was created by” Message = Message & “Gary Cornell”
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING
36
MsgBox Message You can also use the & in the MsgBox itself: Message = “This program was created by” MyName = “Gary Cornell” MsgBox Message & MyName Object Data Type: In Visual Basic, forms, controls, procedures and record sets, are all considered as Objects. All programming activity revolves around these objects. Since VB is very much an object based programming language, it is very natural to use Object data types. An Object variable refers to an object within the application or in some other application. This object can be a text box or a form or a database. A variable declared as an object is one that can subsequently be assigned (using the set statement) to refers to any actual object recognized by the application. Dim objDb As database Set
objDb = opendatabase (“C:\SISI \ EIS . mdb”)
A variable declared as an object occupies 4 bytes
of storage.
The Variant Data Type: A variant data type is a variable that can change its type freely. It can accept text, numeric data or byte data easily without any hiccups. If the data type is not mentioned then by default it will be considered as a variable of variant data type. Dim VarValue
\ Variant
by
default.
VarValue = “100”
\ VarValue contains “100” (a string).
VarValue = VarValue – 70 \ VarValue now contains the numeric value 30. \ The ‘conversion is done automatically VarValue =
VarValue & “+”
\ VarValue now contains the string “30+”
The variant data type comes in handy when you are not sure about the incoming value. The variant data type can handle the values which the other variables can not handle. These values are The Null Value The Empty Value The Error Value The Null Value Null is commonly used in database application to indicate unknown or missing data. If you assign Null to a variable of any type other than variant, a trappable error occurs. Assigning Null to a variant variable doesn’t cause an error, You can also assign Null with the Null keyword: Z = Null
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING
37
You can use the IsNull function to test if a variant variable contains Null: If IsNull (x) Then Debug . print . . . . . . End If The Error Value In a variant, Error is a special value used to indicate that an error condition has occurred in a procedure. An error value is created by converting a real number using the CVErr function. However, unlike other kinds of errors, normal application – level error handling does not occur. The Empty Value A variant variable has the Empty value before it is assigned a value. The empty value is a special value different from 0, a zero-length string (“”), or the Null value. You can test for the Empty value with the IsEmpty function: If
IsEmpty (x) Then . . . . . . . .
A variant can be assigned the Empty value using the Empty keyboard. When a variant contains the Empty value, you can use it in expressions, where it is treated as either 0 or a zero-length string, depending on the expression. The Empty value disappears as soon as any value (including 0, a zero-length string, or Null) is assigned to a variant variable. A variant always takes up 16 bytes, regardless of data stored in it. Object, string, and arrays are not physically stored in the variant. Four bytes of the variant are used to hold either an object reference or a pointer to the string or array. The actual data is stored elsewhere. 2.7. CONSTANTS Visual Basic’s named constant feature allows creating and then using mnemonic names for values that never change. Constants are declared just like variables, and the rules for their names are also the same: 255 characters, first character a letter, and then any combination of letters, underscores, and numerals.
Constants
store
values
like
variables, but as the name implies, those values remain constant throughout the execution of an application. Using constants can make your code more readable by providing meaningful names instead of numbers. There are a number of built-in constants in Visual Basic, but you can also create your own Creating Your Own Constants The syntax for declaring constants is: [Public|Private]Const constantname[As type]=expression Constantaname should be a valid name As Type is the data type. expression is the numeric or string value that has to be assigned to the constant.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING
38
Other than the user defined constants there are many intrinsic or system defined constants provided by applications and controls. Scope of a Constant By declaring a Constant in the declarations section of a form, standard, or class module, rather than within a procedure, the Constant will be available to all the procedure in the module. By declaring a Constant in Public keyword, it is available throughout the application. Declaring a constant in procedure will be available to that procedure only. Const conPi = 3.1415926 1. A variable in the module cannot have the same name as any procedures or type defined in the module. 2. A local variable can have the same name as public procedures, types, or variables defined in other modules. If this variable is accessed form another module, it must be qualified with the module name. It is safer to have the names of variables different from procedure names or controls in other modules. The properties of shadowing can cause errors that are not easily identified and may show up very seldom for you to debug with ease. 2.7.1 Converting Data Type The values entered through the textbox will be stored as a string value. Suppose if the application is student mark sheet processing system. Marks are entered using the textbox. To process the marks these values has to be converted to numeric. For all such activities Visual Basic provides functions to convert values into data types that you need. The following table lists these functions. Conversion function
Expression
Cbool
boolean
Cbyte
Byte
Ccur
Currency
Cdate
Date
CDbl
Double
Cint
Integer
CLng
Long
CSng
Single
CStr
String
CVar
Variant
CVerr
Error
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING
39
2.8. CONTROL STRUCTURES The Control Structures in Visual Basic are 1. If condition then [statement] [Else statements] Which conditionally execute a group of statements, depending on the value of an expression. 2. for counter = start To end [Step step]
[statements] . . . . Next Which repeats a
group of statements a specified number of times. 3. do [ {while | Until } condition ] . . . . Loop which repeats a block of statements while a condition is True or until a condition becomes True. 4. while condition [statements] Wend which executes a series of statements as long as a given condition is True. 5. select Case test expression [case expression list –n [ statements –n] . . . . End select which executes one of several groups of statements, depending on the value of an expression. Variations of some of the above statements exist, but we will concentrate on the statements listed. The For . . . . Next Statement This structure is used when you want to execute a statement or a block of statements a certain number of time. Example For I = 1 to 10 Total = Total +I Next I This loop will compute the sum of the numbers from 1 to 10. The statement Total=Total+1 is performed 10 times.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING
40
START
SET UPPERLIMIT
PROCESS INCREMENT
IS UPPER LIMIT?
no
CONTINUE
END How does this loop work? 1. The for statement initializes the value of I as 1. Since 1 is less than 10, the next statement is executed. 2. The statement Total = Total +1 is executed. 3. The statement Next I increments the value of I by 1. 4. The control shifts to the beginning of the loop, where the value of I is checked. 5. If the value of I is more than 10, the loop terminates, else steps 2 to 4 are executed. Variations 1. The quantum of increments is decided by the [Step, step] keyword. Example: For I = 0 to 100 Step 5 the variable I will assume the value 0,5,10,15,etc. The code For I = 5 to 100 step 5 Debug.print I Next I
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING
41
will print all the number from 5 to 100 that are divisible by 5. The Decision Maker ……If The If conditions…… statement is used when the program has to perform an instruction or a block of instructions depending upon the value of an expression. If the expression returns True then a set of statements(s) is executed. The program may or may not execute any statement(s) if the expression returns False.
START
STATEMENTS
yes
IS
EXPRESSION
STATEMENTS
? NO
END
‘if . . . .’ Structure
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING
42
START
STATEMENTS
IS
YES YES
EXPRES SION ?
STATEMENTS
no YES
IS
STATEMENTS
EXPRESS ION ?
no
END
‘if ……elseif’ Structrue Syntax If condition Then [statement] [ElseIf condition-n [elseif
statements]……..
[Else [else statements]] End If Example 1 If String1 =String2 then MsgBox Both the strings are equal Example2 If CandidateAge <= 18 then juniors = juniors +1 else if candidateAge <= 50 then seniors = seniors +1
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING
43
Else oldies =oldies +1 End If In the two examples, when the If ….. Statement returns a true value; the statements following the Then keyword will be executed. In the first example, when the If…… does not return a true value, no action is taken. The Loop Do [{While | Until } condition] …..Loop This structure is used when we want the program to repeat a block of statements while a condition is True. Syntax Do [{While | Until } condition] [statements] [Exit Do] Loop
START
PROCESS
IS
CONDITI ON?
Yes NO
CONTINUE END Example code intI =1 Do While intI < 10 Intsum = intsum + intI
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING intI = intI+1 Loop How does it work? 1. The value of intI is initialized to 1. 2. The exit condition is first checked to see if intI is less than 10. If intI is less than 10, then the statements in the loop are executed 3. intsum = intsum +1 and intI = intI +1 are executed. 4. The keyword Loop returns the control to the DoWhile ……..statement, where the exit conditions is checked. The While Loop While condition [statements] Wend This structure executes a series of statement as long as a given condition is true. Syntax While condition [statements] Wend Example code Dim intI as Integer intI =1 While intI < 10 intsum = intsum +1 intI = intI +1 Wend Select case ……..End Select This method is used when the program has to execute on of several groups of statements, depending on the value of an expression. Syntax Select Case testexpression [Case expressionlist-n [statements-n]] ……. [Case Else [elsestatements]] End Select Example code Select Case CandidateAge Case <= 18 MsgBox you are in the Juniors Case <= 50
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
44
VISUAL PROGRAMMING
45
MsgBox you are in the Seniors Case Else MsgBox you are in the Oldies End Select
START
STATE EXPRESS
YES
IS VALU E1?
STATEMENTS
?
NO
IS VAL UE2
YES
STATEMENTS
? NO
STATEMENTS END
2.9. INPUT BOXES Input boxes, which are an alternative way of getting information from the user. Now, it is true that text boxes, which are the most common way for a Visual Basic application to accept data, but the InputBox function displays a modal dialog box on the screen –just like the MsgBox function. Modality is the principal advantage of input boxes; you sometimes need to insist that a user supply some necessary data before letting him or her move on in application. The disadvantages are that the dimensions of the input box are fixed beforehand, and you lose the flexibility that text boxes provide. Input boxes have a title bar that you can set. There is also a prompt; “This shows a sample input box”. There are always two command buttons labelled OK and cancel. Finally, there is a text area at the bottom. Visual Basic always places the focus in this text area when it processes a statement containing an InputBox function. The simplest syntax for the InputBox function is
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING
stringVariable = InputBox (promptString) this form uses the name of the project in the title bar of the input box. The full syntax for the InputBox function is variableName = InputBox (prompt[, default][, xpos][, helpfile, context])
The prompt parameter is a string or string variable whose value Visual Basic display in the dialog box. It is limited to roughly 1,024 characters.
The title parameter is optional and gives the caption used in the title bar. There is no default value; if you leave this out, the application’s name is used in the title bar.
The title parameter is also optional. It lets you display default text in the Edit box where the user will be entering information. If you omit this, the box starts out empty.
Also optional, both xpos are integral numeric expressions. Xpos is the distance in twips between the left edge of the input box and the left edge of the screen. Ypos gives the distance in twips between the top of the box and the top of the screen. (if you omit xpos, the box is horizontally centred; if you omit ypos, it will show up around one-third of the way down the screen.)
The two parameters helpfile and context are used together when you have a help message attached to the box
2.10 BUILT-IN FUNCTIONS A built-in function is simply a pre-packaged piece of code that accomplishes a single task. In this chapter, we can see some of the Visual Basic Built-in functions. Much of the programming needs analysis of data. This is as simple as splitting the full name in to first and last names. The built in string functions allows the user to extract, replace, concatenate and replace and so on. 2.10.1 String Function Space Function: You will often need to build up a string of spaces or a string of repeated characters. The function Space (NumberofSpaces) gives you a string consisting of only spaces. The function String (Number, StringofExpression) gives you a string (in the form of a variant) of repeated characters. The character repeated is the first character of the string expression in the second position of the function (the stringExpression), and the number of times the characters are repeated is determined by the value in the first position (Number). X$ = String (10,”z”) yields the string of ten z’s. Trim Function: One of the things you will always have to do is take care of extra spaces that users may have entered. You can remove the extra spaces by using the given trim functions.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
46
VISUAL PROGRAMMING Trim (Trim$) LTrim(LTrim$) RTrim (RTim$) For example, the Trim function (Trim$) removes spaces from both the left and right end of a string. For example: A$ = “
this has far too many spaces”.
TrimmedVersionofA$ = Trim$ (A$) TrimmedVersionofA$ = “This has far too many spaces”. Similarly, LTrim (LTrim$) removes spaces from the left end, and RTrim (RTrim$) removes space from the right. Case Conversion Functions: The next common task you will need to do for string manipulations is to change the case of the letters. As you might expect from the name, the Lcase (LCase$) function forces all the characters in a string to be lowercase. Similarly, UCase (UCase$) switches all the characters in a string to uppercase. NormalExp$ = “I am not shouting” Result$ = UCase$( NormalExp$) gives I AM NOT SHOUTING and Res$ = LCase$(Result$) gives “i am not shouting” Finding the Length of a String: Len( String) gives the length of the string. The function InStr ([where to start,] stringsearch, stringtofind) allows the user to find the position of the stringtofind in the string stringsearch from the starting position specified by the first parameter. Phrase$ = “QuickBASIC was Visual Basic’s distant ancestor” X = Instr (1, phrase$, “Basic”) The value of X is 6 because the string “BASIC” occurs in the phrase$ “QuickBASIC was Visual Basic’s distant ancestor”, string at the sixth position. In this case, the optional first position specifies from which position to start the search. If you leave this entry out, the search automatically starts from the first position. The syntax of the full function is InStr ([start,] string1, string2, compare]) Where, the compare parameter specifies the type of string comparison. If you set it to zero (equal to the built-in constant vbBinaryCompare) then the comparison is case sensitive regardless of the current setting of option compare. If you use the built-in constant
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
47
VISUAL PROGRAMMING vbTextCompare, you get a case-insensitive comparison again, regardless of the setting of Option compare. Thus, X = InStr (1, phrase$, “basic”, vbTextcompare) will always give you the value 6. The InStrRev Function InStrRev function, that starts searching from the back end of the string. InStrRev (OriginalString, Substring [, start [, compare]]) The Compare parameter is exactly as before. The Replace Function For example, suppose you want to change the string “JavaScript is the Best scripting language” to “VBScript is the Best scripting language” use Replace function. TestString$ = JavaScript is the best scripting language.” TestString$ = Replace (TestString$, “JavaScript”, VBScript”) StrComp Function: This function can be used instead of relational operators such as < or > to compare strings. For example If you use x = StrComp(A$,B$) , then x will get the value -1 if the string A$ is less than B$, 0 if both are equal, and 1 if A$ is greater than B$. 2.10.2 Numeric Functions The Rnd Function: The rand function prints the number between 0 and 1 at random The following code segment Private Sub Form_click ( ) Cls Dim I As Integer For I = 1 to 5 Print Rnd Next I End Sub Produces the results 0.7055475 0.533424 0.5795186 0.2895625 0.301948
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
48
VISUAL PROGRAMMING The Round Function Round (expression [, NumberofDecimalPlace]) allows the user to round off the number to the decimal places specified in the parameter. For example: Round (3.7) = 4 Round (3.76, 1) = 3.76 Round (3.786,2) = 3.79
Other Useful Numeric Functions: Sgn ( ) -
this function gives you a +1 if the number is positive, -1 if negative, and a 0 if it’s
zero. Abs ( ) - the Abs function give the absolute value of whatever is inside the parentheses. Abs (-1) = 1 = Abs(1). Sqr ( ) - the Sqr function returns the square root of the numeric expression inside the parentheses, which must be non-negative or a run –time error follows. Exp ( ) - the Exp function gives e to the power x, where e is the base for natural logarithms, and x is the value in the parentheses. Log ( ) - the log function gives the natural logarithm of a number. To find the common log (log to base 10) use Log10 (x) =Log (x) / Log (10) Trig Function: Visual Basic has the built-in trigonometric functions sin (sine), Cos (cosine), and Tan (tangent). The only problem is that Visual Basic expects the angle inside the parentheses following the functions to be in radian measure. To convert from degrees to radians, you need the value of . The formula is radians = degrees * / 180 2.10.3 The Date Function The Date function returns a date of the form month –day- year (mm-dd-yyyy) for the current date. The month and day always use two digits; the year uses four (for example, 0101-1999 for 1 January 1999). Date = “mm-dd-yyyy” Date = “mm/dd/yyyy” Where mm are numerals between 01 and 12, dd are days between 01 and 31, and yyyy are years between 100 and 9999. You will usually need to know what today’s date is. For this, Visual Basic has three functions, as summarized in the following table.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
49
VISUAL PROGRAMMING Function
Description
Now
Returns the date and time as stored in the system clock
Date
Returns the current date
Time
Returns the current time You will also occasionally need the DateSerial function. This returns a number that
you can use for date calculations. Its syntax is DateSerial (Year, Month, Day) Year is an integer between 0 and 9999 inclusive, Month is an integer with a value between 1 and 12, and Day should be some number between 1 and 31 depending on the month. For example, DataSerial (1998, 1, 35) will give you a date in February! 2.11 WRITING YOUR OWN FUNCTIONS AND PROCEDURES Sometimes you need to write or the same code more than once in the program with different parameters or at different places. Then you can define your own functions or procedures and use it wherever necessary. Writing a Simple function: In the code window choose tools/add procedure from the tool menu and the add procedure dialog box will pop up. Enter the name of the function. Choose the type as sub, function, property or event. And choose the scope as either public or private. User â&#x20AC;&#x201C; Defined Function : Public Function FunctionName (paramter1, paramter2,â&#x20AC;Ś..) Statements FunctionName = expression Statements FunctionName = expression Statements Etc. End Function where paramter1, paramter2, and so on are variables. As you have seen, these variables are referred to as the parameters or arguments of the function.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
50
VISUAL PROGRAMMING
51
UNIT – III
ORGANIZING INFORMATION VIA CODE, CONTROLS AND BUILDING 3.1. ORGANISING INFORMATION VIA CODE The fundamental structure for organizing information in Visual Basic is called a array. 3.1.1 ARRAYS An array is a set of similar items. All items in an array have the same name and are identified by an index. The elements of the array are accessed through index or position. Syntax Dim Varname [([subscripts])] as[New] type[,varname…..] Example: declarations of arrays. Dim name(10)as string Dim x(10 to 20) as integer. In the first case, ‘name’ is a set of 11 strings. name(0) is the first element of the array ‘name’. In the second case, the first element is x(10) of the array ‘x’. The array that we have seen above is a Fixed-Sized array. We know the total number of items in the array. There are other types of arrays such as Dynamic arrays and Multidimensional array. The scope of the array depends on the method of declaration. 1. To create a local array, use the Private statement in a procedure to declare the array. DIM Counters (10) As Integer 2. To create a module-level array, use the Private statement in the Declarations section of a module to declare the array. Private Counters(10) As Integer 3. To create a public array, use the Public statement in the Declarations section of a Form. Public Counters (10) As Integer In the case of fixed-sized arrays it is compulsory to enter the upper bound of the array in the parenthesis; the upper bound is the upper limit for the size of the array. A declaration such as the following Private Counters (10) As Integer will result in an array of 11 elements. To specify the lower bound of an array, provide it explicitly (as a Long data type) using the To Keyword.: Dim Counter (1 to 10) As Integer In the above declaration, the index numbers of Counter range from 1 to 10,
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING The Lbound is a function that returns the lower bound of an array. The Ubound returns the upper bound of an array. Example: Dim sinarray (24) X= Lbound(sinarray) debug.print x This will display 0 in the debug window. 3.1.2 Multi-dimensional arrays Arrays can have more than one dimension. A table of data will be represented by a multidimensional array. For example, if you want to record the sales figures for twelve months for three of the departments in the organization, you would declare the array as follows Dim Saleval(11,2)As Integer. Here the subscripts 11 indicates the months and the subscript 2 indicates the departments. This is a two-dimensional array. You can also have three-dimensional arrays. If you want to record the sales of five products in three departments for twelve months then you need a three dimensional array. Dim Saleval (11,2,4)As Integer. Where the subscript 11 indicates months, the subscript 2 indicates the three departments and 4 indicates the 5 products. Please remember that a multidimensional array takes up a lot of space. 3.1.3 Dynamic Arrays Dynamic Arrays are used when you do not know the number of elements for an array. For example, when you are reading a string into an array, you may want to have the capability of changing the size of the array at run time. A dynamic array can be resized at any time and this helps you to manage memory efficiently. For example, you can use a large array for a short time and then free memory to the system when you are no longer using the array. Alternatively you can increase the size of the array after having declared a smaller array. The ReDim is used in conjunction with the Dim statement while declaring these arrays. The alternative is to declare an array with the largest possible size and then ignore array elements you donâ&#x20AC;&#x2122;t need. However, this approach, if overused, might cause the operating environment to run low on memory. Declaring a Dynamic Array 1. You declare the array as dynamic by giving it an empty dimension list.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
52
VISUAL PROGRAMMING Dim DynSalevel () 2. Use the ReDim statement to allocate the actual number of elements. ReDim DynSalvel (11,4) ReDim is an executable statement and can appear only in a procedure. Unlike the Dim and Static statements it, makes the application carry out an action at run time. You can use ReDim each time you want to change the upper or lower bounds of a dimension. You cannot however change the number of dimension. The rules of syntax for dynamic arrays are the same as they are for fixed sized arrays. The scoping rules are also the same as they are for other variables. Example: Dim Salval( ) As Integer This statement will create an open-ended array’. ReDim Salval (12,6) This will create a two dimensional array. The values for the subscripts of the array can be passed using variables. 3.1.4 The Preserve Keyword Whenever the ReDim statement is used the previous array and its contents are destroyed. This is useful when you want to prepare the array for new data, or when you want to shrink the size of the array to take up minimal memory. In order to allow the array to ‘grow’ the preserve keyword is used. The statement ReDim Preserve Saleval (12,9) will not destroy the data that has already been entered. It will only add the value for the second dimension. In this case more columns are added to the table. In the case of a single dimension dynamic array, you can enlarge an array by one element without losing the values of the existing elements using Ubound function to refer to the upper bound. The Ubound function can be used to get the ubound of the array. ReDim Preserve DynSaleval (Ubound(DynSaleval) +1) 3.2. ORGANIZING INFORMATION VIA CONTROLS 3.2.1 Control Arrays When the same control name is used more than once while designing a Visual Basic application or by using CTRL+C, CTRL+V to copy an existing control from one place to another, Visual Basic asks you whether you really want to create a control array by popping up the message box. Clicking the yes button (or pressing ENTER) tells Visual Basic that you do want to make a control array. Thus, Control array is the bunch of related controls that you distinguish with an index just as you distinguish the elements of an array by its index. When Visual Basic creates a control array, it gives the first control an index property of zero, the second control an index property of 1 and so on.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
53
VISUAL PROGRAMMING
54
Like most properties of Visual Basic objects, you can change the index property at design time using the properties window. In fact, if you assign any number to the Index property of a control at design time, Visual Basic automatically creates a control array for you. This lets you create a control array without having to use two controls at design time. In theory, you can have up to 255 elements in a control array, but that would be very unusual, as it would waste too many windows resources. 3.2.2 Working with a Control Array Eg. Create a control array of two text boxes with a control name of txtMoney.
To
work with the change procedure for one of the two elements of txtMoney, move to the code window by double clicking one of the control array elements (i.e one of the textboxes) . The code window looks different with Index as parameter. As with arrays, the index parameter is the key to the smooth functioning of control arrays. For example, add the following code to the event procedure template. Private sub txtMoney_change (Index As Integer) If Index = 0 Then MsgBox “you typed in the text box with index 0” Else MsgBox “you typed in the text box with index 1” End If End sub Now, when you type in one of the text boxes: 1.
Visual Basic calls this event procedure.
2.
VB passes the index parameter of the control you typed in to the procedure. In this way, the event procedure can use the index to determine what to do. The If-
Then-Else, combined with the index parameter, lets the event procedure determine where you typed. Any event procedure that would work for a single control can be used for a control array of controls of that type. For example, the keypress event procedure for the control array of txtMoney text boxes now starts out as Private sub txtMoney_keypress (index As Integer, keyAscii As Integer). Instead of Private sub txtMoney_keypress ( keyAscii As Integer) as it would for an ordinary text box. Adding and Removing Control in a Control Array If you inadvertently add a control array at design time, you can remove it by changing the control name or deleting the control at design time. However, once you tell Visual Basic to create a control array, you must change all the names of all the controls in the control array before Visual Basic will let you eliminate the Index property.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING The Load Statement Once you have created a control array at design time, you can add controls while the application is running. To do this, you use a method called Load. Eg. Load txtMoney (I), Where I will be the index of the element. When the load event is used as given in the following code, No control is displayed on the screen.
Private Sub Form_Load ( ) Dim I As Integer For I =2 To 5 Load txtMoney (I) txtMoney (I) .Text = “Text box # ” + Str$ (I) Next I End Sub The problem is that whenever Visual Basic loads a new element of a control array, the object is invisible – the visible property of the new control is set to false. Change this to true. But even if you do, there is another problem you’ll need to cure: all other properties (except the Tab Index and control Array Index) of your new control are copied from the object that has the lowest index in the array. Private Sub Form_Load ( ) For I = 2 To 5 Load txtMoney (I) txtMoney (I).Text = “Text Box # ” + Str $ (I) txtMoney (I).Visible = True Next I End Sub When you run the above program, you can see only the last control, textbox with an index 5. Since the left and top property of all the control is same. For example, suppose you want to place all the text boxes (both the original ones and the newly loaded ones) running down the left-hand side of a form. You could use code like this in the Form_Load: Private Sub Form_Load( ) Dim I As Integer Const SPACING = 10 txtMoney(0) . Move 0, 0
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
55
VISUAL PROGRAMMING
56
txtMoney(0).text = “TextBox in control array #0” txtMoney(0).width = Textwidth (“
Text Box in control array #0
” )
txtMoney(1).Move 0, txtMoney(0), Top + txtMoney(0) . Height +SPACING txtMoney(1).Text = “Text Box in control array #1” txtMoney(1).width = Text (“Text Box in control array
#1
”)
For I = 2 To 5 Load txtMoney(I) txtMoney (I).Text = “Text Box in contrl array #” + Str $(I) txtMoney(I).Move 0,txtMoney (I - 1).Top + txtMoney(I-1).Height_ +SPACING txtMoney(I).Visible = True Next I End Sub The Unload Statement You use the Unload statement to remove any element of a control array that you added at run time via the load command. You cannot use the Unload statement to remove original elements of a control array, which is created at design time. For example, if you add the click procedure, Private sub Form_Click ( ) Static I As Integer If I < 4 Then Unload txtMoney (I+2) I = I +1 Else Exit Sub End If End sub Each click on an empty place in the form removes the next control in the control array. However, this routine will not remove the initial two elements in the control array because of the line If I < 4 Then . . . . . This extra precaution is necessary because you can only load or unload an element of a control array once. If you try to load or unload a control array element twice-in succession, Visual Basic gives a run-time error. 3.2.3 List and Combo Boxes Uses list boxes when you have a fixed list of choices. For example, suppose you are designing an application to provide information about the courses offered in the
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING
57
college/university. Visual Basic automatically adds vertical scroll bars whenever the list box is too small for the items it contains. Use a Combo Box when you want to list the choices and to edit the choices. This is a drop down list when you press the icon the list is populated. There are actually two types of combo boxes.
If the value of the style property is set to the default value of zero, you get a combo box with an arrow. If the user clicks the arrow, he or she will see the drop-down list of choice given in the box.
If the value of the style property of a combo box is 1, the user sees the combo box with the list already dropped down.
Here are examples of these two types of combo boxes: Notice that, in both cases, the user still has a text area to enter information. There is one other possible choice:
If the value of the style property of a combo box is 2, you will see a pull-down list box
Thus, although you draw a pull-down list box by using the combo Box icon, once you set the style proper to 2 (either via code or at design time), the text area disappears and what appears on the screen look like a different version of a list box. On the other hand, the events that this “pull-down list box” will respond to are those of a combo box and not those of a list box. There are also two kinds of list boxes, and working with the style property lets you
determine if the box shows little check boxes next to the items. You can even change this property at run time using one of
the built-in constants
vbListBoxStandard or
vbListBoxCheckBox.
Sorting List and Combo Boxes Items in a list or combo box can be sorted in ASCII order by simply setting the sorted property to be True. If you set the sorted property to True, Visual Basic will order the items in ASCII order. Otherwise, the order of the items depends on the order in which you placed them in the list box. You can set the sorted property to true at design or run time, as well as switch it back and forth via code as necessary. Manipulating the Items on a Combo Box We use to add or remove items from a list or combo box while the project is running. To achieve this use the AddItem method to add an item to a list or combo box. The syntax for this method is ListName.AddItem Item [, index] ListName is the control name of the list or combo box and Item is a string or string expression. If the sorted property is true for the list or combo box, then Item goes where ANSII order places it. If the sorted property is false, Visual Basic places Items at the position determined either by the index parameter or at the end of the list when you do not specify the
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING index. The index parameter must be an integer or integral expression. An Index value of zero (not 1) means you are at the beginning of the list. The index option has no effect on where the item is added to the list if the sorted property of the list box is set to true. If you do not add the initial items to a list or combo box at design time, then the most common place to do so is in the Form_Load or Form_Initialize procedure. For example, if the list or combo box had the control name of lstpresidents, the code to builds the list might start like this: Lstpresidents.AddItem You can also remove an item from a list while the program is running. The syntax for the RemoveItem method is ListName. RemoveItem Index Where, as before, ListName is the control name for the list or combo box and index is the position where the item was located. In addition to removing individual items on a list, you can use the clear method to remove all the items on the list. The syntax is ListName.Clear
Other Common List and Combo Box Properties Many of the properties of list and combo boxes determine how the information will appear. These properties work the same in list and combo boxes as they do in other controls. For example, the font properties determine which font is used to display the items in the list or combo box; the BackColor and ForeColor properties control what colours are used for the background and foreground, respectively. Similarly, properties such as height, Left, Top, and width control the shape and location of the list or combo box. The properties special to list and combo boxes let you get at the information in the box or the item the user has moved to within the box. They also allow you to have multiple columns in a list box. For example, when a user moves the focus to a list or combo box, he or she can select an item by using the ordinary windows conventions – the arrow keys, PAGE UP, PAGE DOWN, the END key, and so on. In fact, once the user moves the focus to the list or combo box, he or she can also use the windows shortcut or pressing a letter key to move to the first item in the list beginning with that latter. The item the user select is always highlighted. All these details are handled automatically by Visual Basic. Here are descriptions of the six list and combo box properties you will be working with most frequently for these controls. List:
This is a property of both list and combo boxes, and it is for all practical purpose like a
zero-based string array that contains all the items on the list. lstTheBox( 0 )
‘first item
lstTheBox( 1 )
‘the SECOND item
lstTheBox( 2 )
‘third item
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
58
VISUAL PROGRAMMING
59
This gives you another way to initialize the items in the list or combo box instead of doing it at run time. When you choose the list property in the properties window, VB opens up a list box where you can type the items. You will need to place each item on a separate line, and this must be done by pressing CTRL+ENTER and not the ENTER key between items. List Count:
This is a property of both list and combo boxes, and it gives you the number
of items on the list. Since the index property starts at zero, in order to analyze the contents of the list using a For-Next loop, write the limits of the loop as For I = 0 To lstBoxName. ListCount -1 For example, the following loop lets you remove a specific item from a list box that I calleld “TheItemToGo”. Dim I% For I% = 0 To lstBoxName. ListCount – 1 If lstTheBox.List (I%) = “TheItemToGo” Then lstTheBox.RemoveItem I% Exit For End If Next I% List Index:
This is property for both list and combo boxes. The value of the List Index
property gives the index number of the highlighted item, which is where the user has stopped in the list. If no item was selected, the value of this property is -1. A statement such as If ListIndex = - 1 MsgBox “No President Selected!” Else Info = Presidents (lstPresidents.ListIndex + 1) End If Text:
This is a property of both list and combo boxes, and it gives the currently selected
item stored as a string. This, of course, changes as the user moves through the list box. If you need the numeric equivalent of this string, just apply the correct conversion function function (Cint, CSng, etc.). Columns and MultiSelect:
The columns property controls the number of columns in a list
box. If the value is zero (the default), you get a normal single-column list box with vertical scrolling. If the value is greater than one, you allow multiple columns. The MultiSelect property controls whether the user can select more then one item from the list. There are three possible values for this property:
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING
60
Type of Selection
Value
No multiselection allowed
0
Simple multiselection
1
How It Works
Use
ordinary
windows
techniques
and
mouse
dragging
(SHIFT+arrow
keys,
CTRL+RIGHT
ARROW, and so on) to select more items. Extended multiselection
2
SHIFT+
mouse
click
extends the selection to include between
all
list the
items current
selection and the location of the click. Pressing and clicking the mouse selects or deslects an item in the list.
List Box Events List boxes respond to 12 events. The KeyUp, KeyDown, and KeyPress events work exactly as before. List boxes can also tell you whether they have received or lost the focus. However, the two most important events for list boxes are the click and Double-click events. An important windows convention is that clicking on an item selects the item but does not choose the item. This is reserved for double clicking on the item. In general, therefore, you do not write code for the click event procedure for a list box but only for the double- click event procedure. Another reason not to write code for the Click event procedure unnecessarily is that each time the user moves through the list, Visual Basic generates the click event. Combo Box Events Combo boxes respond to many of the same events as list boxes. You can analyze which keys were pressed or whether the box has received or lost the focus. The first event that is different is the change event. The change event occurs only for pulldown combo boxes and simple combo boxes (Style = 0 or 1). Visual Basic does not generate this event if you are using a pull-down list box(Style = 2). Visual Basic generates this event whenever the user enters data in the text area of the combo box or when you change the Text property of the combo box from code.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING Visual Basic calls the DropDown event procedure right after user clicks the arrow to drop the list box down to presses ALT+DOWN ARROW when the combo box has the focusbefore the list drops down. For this reason, this event procedure is mostly used to update a combo box before the list appears. Since you can have a pull-down list only when the style property is 0 or 2, this event is not invoked for simple combo boxes (Style = 1).
Associating Numbers with Items in List or Combo Boxes Needing to associate integers with items in a list or combo box is so common that a simple method of doing this was added back in Visual Basic 2. Of course, you could create an array to store this information and keep track of this array yourself, but you no longer need to do that â&#x20AC;&#x201C; at least as long as all you need is a (long) integer associated with the item. Whenever you create a list or combo box, Visual Basic automatically creates a long integer array called the ItemData array. This array is another property of the box, like the list array that you saw previously. In addition, like any property of a Visual Basic control, you can examine it or modify it. If you want to add the numeric data to entry in this ItemData array, You need to know the array index of the item. This is taken care of by the NewIndex property of the box. This property gives you the index of the last item added to the box. (If the sorted property is True, this is particularly useful information, since you have no idea where this item will end up.)
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
61
VISUAL PROGRAMMING
62
FIG – 3 EXAMPLE FOR LIST AND COMBO BOXES Here input box is used to get the name of the fruit from the user to add it in to the combo box. 1
FIG – 4 INPUT BOX
FIG – 5 INPUT IS ADDED TO THE COMBO BOX Here the message box is used to display the selected fruit.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING
FIG -6 â&#x20AC;&#x201C; USING MESSAGE BOX 3.2.4 The Flex Grid Control The flex grid control has more than 80 properties, 20 events, and 10 methods. The flex grid control lets you build spreadsheet-like features into your projects or display tabular information neatly and efficiently. This control displays a rectangular grid of rows and columns at design time. How many rows and columns you see at design time depends both on the number or rows and columns you have set and the current size of the grid. Each grid member (intersection of a row and column) is usually called a cell. Cells can hold text, bitmaps, or icons, and you can even have some cells holding text and other holding graphics. Numbers must be translated back and forth using the right conversion (Cint, CDbl and so on) and Str($) functions or the Variant data type must be used as you would do with text boxes. You can specify the contents, as well as the width and height of a row or column, and you can use code to control each cell individually you read or change whatever text is in the current cell. The grid control even includes a built-in word-wrap feature that you can activate via code or the properties window so users can enter text more easily. User can move from cell to cell by using the arrow keys or the mouse; Visual Basic handles such movement automatically. As the user of your control moves around the grid, Visual Basic keeps track of what the current cell is as the values of the Row and Col properties.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
63
VISUAL PROGRAMMING Users can work with contiguous groups of cells in the grid, usually called regions, by clicking a cell and dragging the mouse or by pressing SHIFT plus an arrow key to select the region. Once a region is selected, code can be used to analyze or change the contents. General Properties of the Flex Grid Control Many properties of the flex grid control are the same as those for the controls that you were already familiar with. For example, the Height and Width properties tell you how large the grid will appear; the Enabled property determines whether the grid will notice keystrokes or mouse activity. Similarly, if you set the Scrollbar property to a nonzero value(1 for Horizontal, 2 for Vertical, 3 for both), Visual Basic automatically adds the appropriate scroll bars when there is information of the grid that cannot be seen. Cols, Rows: These properties determine the number of rows and columns in the grid. The default values for each of these properties are 2, but you can reset them in code or via the properties window, as needed. They must be integers, and the syntax is GirdName.Cols=NumOfCols% GirdName.Rows=NumOfRows% You can also add an optional form name. For Example: frmDisplay.cols=10 Col, Row: These properties set or return the row and column for the currently selected cell inside the grid. These properties are only available at run time. As the user moves around the grid, the values of these properties change. By adjusting their values via code, you can specify the current cell directly. Since both col and row start out at zero, the top left corner cell has Col value 0 and Row value 0. ColPosition, RowPosition : Lets you move whole rows and columns around in your grid. The syntax is GridName.ColPosition(number) [=value] GridName.RowPosition(number) [=value] ColWidth, RowHeight : These two properties specify the width of a specific column or height of a specific row. They can only be set via code. Both are measured in twips. The syntax is GirdName.ColWidth(ColNumber%)=Width% GirdName.RowHeight(RowNumber %)=Height% Text, TextMatrix: The Text property sets or returns the text inside the current cell(the one given by the current values of the Col and Row properties). For example, the following fragment sets up a gird (the control name is the default-MSFlexGrid1) with four rows and four
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
64
VISUAL PROGRAMMING columns. Then we make the cell in the bottom right corner of the current cell. We add some text to that cell and then display it on the form. MSF1exGrid1.Cols = 4 ‘have four rows MSF1exGrid1.Rows = 4 ‘have four columns MSF1exGrid1.Col = 3 MSF1exGrid1.Row = 3 MSF1exGrid1.Text = “This would go in the button right corner” MsgBox MSF1exGrid1. Text & “is in cell 3, 3” MSF1exGrid1.Col = 0 MSF1exGrid1.Row = 0 MsgBox MSF1exGrid1. Text & “is in cell 0, 0” 3.3. BUILDING LARGER PROJECTS It is not possible to attach all the code to a single form in Visual basic. To take full advantage of VB starts using multiple forms. Multiple forms will add flexibility and power to the applications. To add more forms, open the project menu and choose Add Form. Navigating among forms: The project explorer window lists by name all the forms. The actual files have the .frm extension. VB stores each form as a separate .frm file and uses the .vbp file to keep track of where they are stored, along with any .frx file that is needed for the images attached to a form. 3.3.1 Methods for Forms Show : The show method shows the form on the screen and will also move the current form to the top of the desktop. The syntax is FormName.Show Load : The Load keyword places the form into memory but does not display it. Visual Basic also loads the form into memory whenever you refer to the properties or controls in code. This is called as implicit loading. Load FormName Hide: This keyword hides the form from the screen but doesnot unload it from memory. The syntax is
FormName.Hide
Or you can use the keyword me, Me.Hide Unload: The unload command removes the form from memory. All information contained in form variables are lost. The syntax is Unload FormName
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
65
VISUAL PROGRAMMING Activate/Deactivate events:
66 Visual Basic invokes the Activate event for a form whenever
a form becomes the active window within the current Visual basic project. The activate event is called
When the form becomes active
When the user clicks the form
When you use the show or setfocus method.
Visual basic invokes the deactivate event when the form stops being the active window within the current Visual basic project.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING
67
UNIT – IV WORKING WITH INTERFACE, MDI AND DATABASES 4.1. WORKING WITH INTERFACE 4.1.1 The Common Dialog Control In order to provide standardization in the interface for all windows compliant applications, Visual Basic has the CommonDialog Control. The Windows Common Dialog Control allows you to deploy the dialog boxes that it provides with all its applications. The Common Dialog Control lets you display the following dialog boxes
Open A File
Save a File
Set a Color
Set a Font
Print a Document. To activate Common Dialog Control, add the control to your form and call the method
or function that you want. Your application deals with the user in the same manner as Windows does. The common dialog control can display the following dialogs, using the specified methods. Method
Dialog Displayed
ShowOpen
Show Open Dialog Box
ShowSave
Show Save As Dialog Box
ShowColor
Show Color Dialog Box
ShowFont
Show Font Dialog Box
ShowPrinter
Show Print or Print Option Dialog Box
ShowHelp
Invokes the Windows Help Engine
Working with the Common Dialog Control Add the Common Dialog Control to your toolbox by right clicking on the toolbox and selecting ‘Components’ from the pop-up menu. Select “Microsoft Common Dialog Control 6.0” from the list of Components. Now this is available as a control in the toolbox. Draw it on your form. Please note that this control does not have an interface that the user will see and work on. During runtime it is not visible. However its methods can be invoked during runtime. Right click on the common dialog control and select properties from the pop-up menu. Set the properties for each of the method. To invoke the common dialog control, in a new project, add the Microsoft Common Dialog Control to the toolbox. Include Command Buttons to activate the controls. For eg. Assign the name as open, save, color, font and print.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING The File Open Dialog Box To open the file dialog box use the Show Open method. In the code window of the open command button write the code CommonDialog1.ShowOpen. Run the program. Click on the Open button, and you will see the File Open Dialog box. However, in order to get it fully functional there are a few more things that you have to do. 1. You have to specify the title for this dialog box. 2. If the user does not select a file and clicks on Cancel, you must be able to take appropriate action. 3. Having got a handle on the file, you need to open it, read the contents and display the same in the textbox. There are two ways you can give a title to the dialog box. By setting the title at design time By setting the title at runtime through code. Add the following line to the code for the Open Common Dialog Button. CommonDialog1.DialogTitle = “Select the file to Open” CommonDialog1.ShowOpen If the user clicks the Cancel button, Visual Basic returns an empty string for the filename. This will cause an error when you try to open such a file. There is a simple method to tackle this. Use the ‘On Error GoTo’ statement and add the necessary statements to exit the procedure without any use. On Error GoTo ClickedCancel ‘The above statement will pass the control to “ClickedCancel” in case of an error. You can ‘exit the function from there. commonDialog1.DialogTitle = “Select the file to open” commonDialog1.ShowOpen ClickedCancel: Exit Sub The following program segment illustrates the function of File Open dialog box, and to read and display the contents of a file. ‘Declaring the necessary variables for opening and reading the file. Dim intFileLength As Integer Dim Strdatabuffer As String Dim intfreefilenum As Integer On Error GoTo cancel Dim commonDialog1.DialogTitle =”Select the file to Open” CommonDialog1.ShowOpen ‘Getting the face file number
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
68
VISUAL PROGRAMMING intfreefilenum = FreeFile( ) ‘Opening the file. Open CommonDialog1.FileName For Input As # intfreefilenum intFileLength = LOF(intfreefilenum) strdatabuffer = Input(intFileLength, intfreefilenum) ‘ reading the contents of the file ‘displaying the text in the textbox. Text1.Text = strdatabuffer ‘Closing the file Close # intfreefilenum ‘Exiting the procedure if there is an error. Cancel: Exit Sub Saving a file In the previous section, user is allowed to open an existing file. If the user wants to create a new file, add some text and save it in a directory of his choice. In this case we have to show the File Save Dialog Box. Use the ShowSave method to allow the user to enter the name of the file, in which the text entered in the textbox has to be saved. In the ‘Save’ CommandButton add the following code Dim intfreeenum As Integer Dim intFileLength As Integer Dim strdatabuffer As Integer On Error GoTo cancel CommonDialog1.DialogTitle = “Enter the name of the file to save” CommonDialog1.ShowSave Intfreefilenum = FreeFile( ) Open CommonDialog1.FileName For Output As #intfreefilenum Strdatabuffer = Text1.Text Write #intfreefilenum, strdatabuffe Close #intfreefilenum Cancel: Exit Sub Changing the Color The common dialog control also provides the means to change the colour of the text or other controls on the form. In order to display the Color Dialog Box you must use the ShowColor method. Double click on the ‘Color’ button on your form to bring up the code window. Add following line. CommonDialog1.ShowColor
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
69
VISUAL PROGRAMMING Run the program and click on the ‘Colour’ button. This will display the Colour Palette. You can choose the colour of your choice. In order to change the colour of the text in the textbox, you must assign the colour chosen by the user from the Palette to the text in the textbox. Your code will look like this CommonDialog1.showColor Text1.Forecolor = CommonDialog1.Color Printing a document Add the following line to the Print button’s code. CommonDialog1.ShowPrinter. This helps the user to print the contents. If the printer is already installed, it can be chosen from the printers list. The Printer Dialog box displayed will be similar to the one on applications like Microsoft Word or Microsoft WordPad, etc. Through the Property Pages of the CommonDialog control, you can set option like the number of copies, pages from and pages to, landscape or portrait orientation. These properties can be set through code as well. In order to print the text entered in the textbox a certain number of times, we can write the code as follows. Dim intnumberofcopies As Integer Dim intI As Integer Dim strdatabuffer As String CommonDIalog1.ShowPrinter ‘We can get the number of copies that the user has given as follows intnumberofcopies = CommonDialog1.Copies strdatabuffer = Text1.Text For intI = 1 To intunmberofcopies Printer.print strdatabuffer Next intI Printer.EndDoc 4.1.2 RechTextBox Control Using CommonDialog control it is easy to use the interface in the application. We were able to create a small application that would allow the user to create a new file or open an existing file, add text to it save to it, save the changes and print the contents of the file as well. We could also make changes to the font size, the colour of the text, etc. It is possible for the user to create a word processor using this common dialog control. But we could not selectively change the font size, colour or indentation. These techniques are necessary for an effective word processor. Besides, we may want to add pictures to our text file or even a spreadsheet or some application. In order to allow the user
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
70
VISUAL PROGRAMMING to do all this, the conventional textbox could not be used. The conventional textbox can hold only plain text. Microsoft provides one such control called the Rich TextBox control. The Rich Text Box control allows the user to enter and edit text with more advanced formatting features than the conventional Text Box control. The Rich Text Box control provides a number of properties that can be applied to format a selected portion of text within the control. Select the portion of the text to be formatted and apply the necessary changes. You can make text bold or italic, change the colour, and create superscripts and subscripts. You can also adjust paragraph formatting by setting both left and right indents, as well as hanging indents. To add the control, from the projects/components, select the controls tab. Double click the Microsoft Rich Textbox control. A new component will appear on the toolbox. To change the colour and perform other formatting options use the following statements. Changing font: In the case of the Rich textbox, formatting changes have to be applied to the text after selecting it. In order to change the font of a portion or all the text in the rich textbox, select the text and call the font dialog box. Select the font type and click OK. The selected text will be displayed in the new format. CommonDialog1.ShowFont RichTextBox1.SelFontName = CommonDialog1.FontName Changing the Colour: To change the colour of the selected text or all the text in the rich textbox. The procedure is similar to that of changing the font. The code to achieve this is as follows. CommonDialog1.ShowColor RichTextBox1.SelColor = CommanDialog1.Color The Rich Textbox also allows you to indent the text. You can have a left indent, a right indent or hanging indent. Selndent(default is the left indent) specifies the distance between the left edge of the RichTextBox control and the left edge of the text that is selected or added. SelRightIndent specifies the distance between the right edge of the RichTextBox control and the right edge of the text that is selected or added. Hanging indent is the extra indent given to a line or lines in a paragraph over and above the indent given for the first line of the same paragraph. The selhangingindent specifies the distance between the left edge of the first line of text in the selected paragraph, and the left edge of subsequent lines of text in the same paragraph.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
71
VISUAL PROGRAMMING Changing the indent: In order to change the left indent of the selected text you need to provide the amount of indent required either at runtime or at design time. The amount of indent has to be given as an integer. The Rich Text box allows you to add .bmps, .gif and other pictures as part of the document. Even introduction of hyperlinks to create help files. The Rich Text box allows you to directly read data from a file and to save the data entered as on .rtf file. An .rtf file can be read by MS Word. 4.1. 3 The Microsoft Common Controls 6.0 Image List control: This control gives another way to store a group of images in a single place. You can use these images in other parts of your application. The Images tab in the dialog box gives the convenient way of adding images at design time. You can assign the image stored in the first place of ImageList to Picture control as Picture1.picture = ImageList1.ListImages(1).picture ListView Control: This control helps you display items in various ways. The items can be accompanied by both icons and text. The value of the View property determines way to display. Progress Bar Control: The Progress bar control is similar to using a vertical bar in the gauge control. It fills in a bar with rectangular chunks. Use the Align property to position the control. As in Scroll Bar the min and max value can be set. Slider Control: The slider control works similarly to scroll bar. The user can move the slider by dragging it, clicking the mouse to either side of the slider or using the keyboard. Just as the scroll bar the key properties are min, max, and value which determines the largest, smallest and the current values for the slider Status Bar Control: This control gives you a window, usually at the bottom of a form that you can use to display the status of the application. The align property governs where the status bar appears. Each status bar can be divided in to 16 panels. Tabstrip control: The tabstrip control provides another way to gives a form the look of a tabbed dialog box. It is not flexible as the tabbed dialog box.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
72
VISUAL PROGRAMMING
73
Toolbar control: The toolbar control helps to build the toolbars. Using the align property the toolbar can be placed in the window. By default the value is 1 which aligns the tool bar to top. If the images are to be added then add the images to the image list control. TreeView control: Tree view control has a nodes collection where each node holds information about the nodes in the control. The highest node is given by the Root property.
It looks like
windows explorer. 4.1.4 Menus Menus help the user to build a user friendly application. Visual Basic lets you build the menus up to six levels. Menus that contain sub menus are called hierarchical menus. Menu Editor You can create menus in Visual basic by using the menu editor window available by choosing Tools/menu editor. Caption text box : The text you enter in this box is displayed in the menu. Name Text box: Each menu item has a control name. The text entered in this box is assigned as a name of menu item. Ok and Cancel buttons: Click OK button when you have finished the menu creation successfully. Click the cancel button if you decide not to build the menu at all. Index box: Use the index box if you want to make the menu item as a part of control array. Shortcut box: The box let you add accelerator keys to your menu items. Accelerator keys are either function keys or ctrl+key combination that activate a menu item without opening the menu. The other properties, checked check box enable you have a check mark in front of the menu item, Enabled check box determines the value of enabled property of the menu item. A menu item that is enabled will respond to the click event. The visible check box is used to make the menu either visible or invisible. If the menu is invisible the sub menus are also invisible.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING
FIG – 7 SAMPLE MENU EDITOR
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
74
VISUAL PROGRAMMING
75
FIG - 8 MENU EXAMPLE 4.2. MULTIPLE DOCUMENT INTERFACE APPLICATIONS The MDI application allows the user to display more than one document at the same time. Documents or child windows are contained in a parent window, which provides a workspace for all the child windows in the application. WHY MDI FORMS? 1. An MDI Form acts like a container for the other forms in the application. Therefore the user can start an application, minimize it and close it with a single point control. One need not close all the constituent forms. As in the case of Word, click on the minimize button to minimize all the open documents. 2. Most of the control buttons and code for the various forms can be shared. All function like adding, displaying, sorting records, etc. is commonly used by most of the forms. The code for these can be shared. 3. Reduce the number of controls. Common controls can be available with the MDI form and shared by the other forms. In short the MDI forms will allow easier organization of the forms in your application, reduce the amount of code and the number of controls in your application.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING An MDI Application consists of 1. One MDI Parent form. 2. One or more MDI child form(s). 3. Optionally independent forms and modules. Creating a simple MDI application Start a new Standard Exe project. Click on Projects. From the drop-down menu, click on ‘Add MDI Form’ A form with a darker colour will be displayed. This is the MDI Form. 4.2.1 Features of an MDI form 1. An application can have only one MDI form. If a project already has an MDI form, the Add MDI form command on the project menu will be unavailable. 2. It can contain only those controls that have an ‘Align’ property or those controls that are not visible during runtime. This is because the internal area of an MDI form is defined by the area not covered by these controls. These are Toolbar, PictureBox, and Data control. The align property here is related to the alignment of the control on the form. 3. To place other controls on an MDI form, you can draw a picture box on the form, and then draw other controls inside the picture box. You can use the print method to display text in picture box on an MDI form, but not to display text on the MDI form itself. 4. An MDI form object can’t be model. 5. The menu for the child from will be displayed as the menu on the MDI form when the child forms have the focus. 6. The default autoshowchildren property displays the child forms automatically when they are loaded. 7. The default ScrollBars property will display the scroll bars when the child forms extend beyond the boundaries of the parent form. 8. The count property of the MDI form tells you the number of controls in the controls collection. To create an MDI child Form, select Form1(or add a new form) and set its MDI child Property to true. It is a standard form with the following attributes. 1. A child form cannot be moved outside the Parent form’s boundaries. 2. Activation a child form will result in the activation of the parent form. 3. When a child form is minimized, its icon will appear at the bottom of the workspace of the parent form. 4. When a child form is maximized, it fills the entire area of the parent form, and its menu will become the menu of the parent form. 5. There can be more than one child form in an application. 6. The icons for MDI parent, child and a standard form are different.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
76
VISUAL PROGRAMMING To create an instance of the form use the statements Dim NewForm As Form1 Newform.Show The statement ‘Dim Newform As New Form1’ creates a variable of the object type called ‘NewForm’ with all the properties of the object Form1. If Form1 has a dozen controls, the new object will have all the dozen controls. The ‘New’ keyword ensures the creation of a new instance of the Form1. The statement ‘Newform.Show’ will show the newly created object. In this case a copy of the object, Form1. To run the application, click File/New. By clicking twice to form1 and its copy will be displayed. To close all the instances of the form form1, click on the close button of the parent form. The ActiveForm Property: This property returns the form that is the active the application. If a control in the child form has the focus, it returns the name of that form. Syntax Object.ActiveForm In the click event of the MDI Form add the following ActiveForm.Text1.Text = “This is to test if we have got it right” Run the application. Create any number of instances of the child form and then click on the MDI form. The text string that you have entered will be displayed in the active form. Select one of the child forms at random and then click on the MDI form to check out if the ActiveForm property really works.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
77
VISUAL PROGRAMMING
78
FIG â&#x20AC;&#x201C; 9 MDI FORM 4.3. DATA BASES Why database We can store the data for our applications in simple text files or structured files, as was done in the good old days of COBOL. Earlier the user department would write to the EDP department and ask for a set of reports specifying the fields or data required. The EDP department would go to work on the computer and a couple of hours or days later produce the report. This is not the case now. The user department would like to generate its own reports, and within minutes too. A database is a collection of records that can be manipulated with ease. Further, all databases can be manipulated using SQL. Let us consider an example. We have to maintain details of payment due from all our customers. Therefore we have a file with details like Customer_Name, Address, Area_Code, Amount_Last_Paid, Last_Payment_Date, and Amount_Due. From the higher-ups there is a demand to know the payment due for Areaâ&#x20AC;&#x201C;A. Therefore you create another file with the above details for all customers of Area-A. Next, you receive payment from some of your customers. Of these, some belong to Area-A. While the other are from other areas. Now you have to update both the files, and send a fresh set of reports too. Imagine if some of the checks bounce? You will have to work on the files all over
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING again. Your misery can be further compounded if each area is handled by a different department or cost centre head, and they want a set of reports as well. However if the data were stored on a database, your job would become so much easier. Any report based on the data that you have, can be generated with ease. For example, a statement like “SELECT * FROM Customer WHERE AREA_CODE = ‘A’” will display all customers who belong to Area –A. You can specify the criteria for selection, and all records meeting that criterion will be selected and displayed. Besides, changes that you want to make to the data can be made in one place. This ensures data integrity and reduces work and associated problems. The tools available today for manipulation of databases are many. Apart from the usual reasons of data consistency and reduced data redundancy and so on there is another major advantage in using databases. That is data independence. Now what is data independence? To answer this question let us consider data stored in flat files. If the data is stored in sequential form, then the program must take this into account. If the data is stored using the indexed sequential format then the programmer must know the name of the index and use the same in his program. If due to some reason the index is modified then the program must be modified to accommodate the new index. We can see from the above that the program will have to be modified to accommodate physical storage of the data. This means that there is no data independence. Let us take another example. One user may want to view the data in the decimal format while another user may not need such a format. This means that two formats of data need to be stored. Using a database is an answer to these problems. You will see that different users can have different views of the same data. The user1 from the Accounts Department will be interested only in the amount that has to be paid to the supplier. Whereas the user 2 from the stores department will be interested only in the parts supplied by the supplier. However both the users will be tapping into the supplier data. With such an approach we can have many more views of the same data. Next, the conceptual view will map into a physical view of the database. The physical view of the database will map into the way the data is actually stored. This method of separating the physical storage from the user view will permit data independence. The views of all the users will be used to develop the conceptual view of the data and any change in the user’s view will be accommodated by the conceptual view. Therefore physical storage for the data will be not being affected. Similarly if the physical storage of the data is changed, it will not cause a change in the way the user views his data. The database acts as a buffer. Based on the above we can give a broad definition of a database as a set of integrated data that can support the requirements of more than one user. Further the data is stored with minimum redundancy and must be accessible with ease and must provided for data independence.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
79
VISUAL PROGRAMMING
80
4.3.1 Data Base Models A database can be defined as a collection of records stored in tables. It has set of rules and tools to manage these records. There are different types of databases, each with its own format. The most commonly know database types are
Relational Model
Network Model
Hierarchical Model
Codd and data conceived the Relational Database mode in the 1970s. in a relational model the data is stored in multiple tables with some ‘relationship’ between the tables in the order to reduce data redundancy. The relational model of a database is the most commonly used model today, and has the data stored in tables in a ‘row – column’ arrangement. Each table has a relationship with one or more tables. The relational model helps reduce redundancy of data, and helps maintain data integrity. Each can be identified by its (Roe – Column) position. Let us look at some definitions with respect to databases.
4.3.2 Tables A table is a basic repository in which data is stored, and has a specific structure for storing data. It is made up of one or more than one column. The data is stored in the form of Rows and Columns. A table may often hold information about one topic. E.g Students Mark Details S1.no.
Name
001
aaaaaaa
002
xxxxxx
language
English allied
70 45
major
85 52
65 85
70
84
This table consists of two records (rows) and six fields (columns). Rows: A record is one row in a table. The row will span across all the columns of the table, and each row has one full set of information about one ‘subject’, here it is related to one student. Every time a record is added a row is added. Columns : In the above example, each row has six columns or attributes, and every time an attribute of a record is added a column will be added. An attribute is referred to as a filed, and the Column type will be decided based on the type of data to be stored. One can set the data type, size, etc of a column. The data types possible are Text, Date, Integer, Boolean, Memo, Object, etc.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING The jet Database Engine is used. It is application independent engine that is used by all the Microsoft products like Excel, word, Access, etc. It is the native database engine that comes with Visual Basic, and is the natural choice for us to experiment with. Creating a Table: The table can be created using
DAO (Data Access Objects)
Microsoft Access
Visual Data Manager that comes with Visual Basic
Using Visual Data Manager the job of table creation and modification is very simple. The Visual Data Manager can work with Access, dBase, Paradox and text files as well.
4.3.3 Working with Visual Data Manager The Visual Data Manager options are available under the AddIns Menu. Click on the Visual Data Manager. Visual Basic responds by showing you the VisData Window. From the File menu select the option New. From the pop–up menu select Access. Depending upon the version of Visual Basic that is installed on your machine, you will be asked to choose the version the version of MDB. Select the latest version. Choose Access 2.0 if your application is going to work on window 3.X access 7.0 is for the 32- bit platform only. Enter the database name to save. Now Visual Basic will display two windows, the Database window and the SQL statement window. The Database windows will have an item properties click on the box with + to see the properties that have been set or available for this database. Creating a table: Right click the mouse in the database window. From the Pop–up menu select New Tables. This will result in another window being displayed with a number of text boxes, check boxes and a rabbit. Decide on the fields that each table will hold. Decide on the properties for each of the field. After entering the table name, click on the AddField button. You will see the AddField Dialog Box. The field in this dialog Box are Name: Enter the name of field you want to add Ordinalposition: Enter the relative position of the field. Type: Enter the type of data for this field. Eg. integer, Text, Long, etc. Validation Text: Message to be displayed in case the user enters invalid data for that field. Size: Enter the size of the field. Fixed length: If selected, creates a field with a fixed size. Variable length: Allows the user to modify the size of the field by dragging its borders. ValidationRule: Lets you determine what data is valid in a field as it is added. DefaultValue: Enter the default value for the field. AutoIncrField: Automatically adds the next field if you are at the end of the table.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
81
VISUAL PROGRAMMING AllowZero Length: Allows you to have a zero–length string as a valid setting. Required: if the checkbox for this is clicked, it means that the table will not be updated if the field is a Null string. For example, Employee Number cannot be a Null string. Add: Appends the current field definition to the current table. Close: Closes the form when you have finished adding fields. Optional information: You may have noticed a button Add index. This button will help you to build an index for that table. The details to be provided for this function are Name:
Enter the Name of the index.
Indexed Fields:
Select the fields used to build the index from the Available Fields ListBox that lists the fields in the current table.
Primary Index:
You can specify if the index is to be the primary index. You can have only one primary index.
Ignore Nulls:
By clicking the ignore Null check box, you can tell the data manager not
to include Null value in the index. Click OK when you are through. The new index will now get appended to the index list. The other properties that can be modified are Ordinal Position Validation Rule Default Value Allow Zero Length Required All the other properties cannot be modified. If however you have to modify the field property anyway, then simply delete that field and create once again. Note: If a field is an indexed field, it cannot be deleted or modified. In this case you must delete the index or relation and then make the necessary changes to that field. Copying a table:
You can copy an entire table with the data and structure to another
database. In the database window, right-click on the table that you want to copy. From the pop-up menu choose ‘copy structure’. Enter the destination database where you want to copy the table. 4.3.4 The Data Control A database can be created easily with the help of the Visual Data Manager. The tables can be populated by simply entering the data in the respective fields. Next we need to create an application to display the data from the database, and allow the users to add new records or modify existing data. To create such an application we have to 1. Establish a connection with the database. 2. Extract the fields from the relevant database.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
82
VISUAL PROGRAMMING 3. Display them on the form. 4. Accept changes made to the data on the form and update the database. How does the Data control Work ? In order for the Data control to deliver the goods, two properties need to be set. These properties can be set at runtime or design time. The properties are Database Name: This specifies the name of the database that must be opened. Record Source:
This specifies the name of the table(s) of the database from which
the data has to be extracted. When we run the program after setting these properties, Visual Basic connects to the database specified, and returns a set of records from the table(s) in the form of a Recordset. A Recordset is an object that points to the data in the database. It is the set of records returned, based on the RecordSource property of the Data control. The RecordSource property can be the name of a table in the databases or an SQL statement that selects fields from one or more tables. Using the Data control: Let us take a look at the data control. The Data control is part of the standard toolbox. It looks like this. Draw the Data control on the form as you would draw a textbox control. It has buttons for moving from record to record. You have buttons to move to the next or last record and to move to the previous and first record. You can also set the caption property for the Data control. Setting the properties for the Data Control: We will take a look at the important properties of the Data control. BOFAction : Action to be taken when the user reaches the beginning of file. EOFAction : Action to be taken when we reach the end of file. Caption: This tells the Data control the type of database that will be accessed. It could be FoxPro, dBase, Paradox, Access, etc. the default is Access. Database Name: Specifies the name of the database that the Data control will access. Give the name of the file that contains the database. Recordset Type: This property specifies the type of recordset object the control will use to access the database. There are three options: 1. Table. 2. Dynaset. 3. snapshot. RecordSource: The RecordSource property specifies the source of the records accessible thorough bound controls on your form. If you set the RecordSource property to the name of an existing table in the database, all of the fields in that table are visible to the bound controls attached to the Data control.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
83
VISUAL PROGRAMMING 4.3.5 The Bound Controls Some of the controls can be â&#x20AC;&#x153;boundâ&#x20AC;? to the Data control. Each bound control is bound to one field of the Recordset. They display the fields from the current record of the Recordset. Depending on their properties, they may also allow the user to edit the data displayed and pass the edited data back to the Data control. The following controls are all data-aware and can be bound to a single field of a Recordset managed by the Data control. Label TextBox Check Box Image OLE List Box Picture Combo Box The following controls are all capable of managing sets of records when bound to a Data control. All of these controls permit several records to be displayed or manipulated at once. DBList DBCombo DBGrid Binding the Bound Controls: Select Text1 in the form In the properties window do the following. 1. Click on DataSource property. Set it to the name of the data control. From now on this text box will display a field from the Recordset returned by the data control. 2. Click on Data Field. A List of fields available will drop down. Select the field name which you want to bind in the text1. This displays the current record of the Recordset. When the user moves from record to record using the navigation button of the data control, it displays the contents of the selected field of the current record. Set the appropriate captions for the Label Box controls. Click on the buttons on the Data control and watch as record after record is displayed in the Text Box without writing any code. Make changes to the data in the text box and check if the changes are updated in the database. The Data control automatically handles the record navigation; it can accept changes and also update the changes made to the data. The data control cannot handle some of the problems that are likely to occur in real life applications. The data control is initialized before the initial Form load event for the form on which it is placed. If any error occur during this
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
84
VISUAL PROGRAMMING initialization step, a non-trappable error results. If the .mdb is missing or has been renamed, your program will not be able to trap this simple error. Therefore you will need to use code after all. Adding a New Record: The AddNew method adds a new record at the end of the file, and clears the contents of the textbox. Deleting a Record: The delete method deletes the current record. Updating the Database: The Data control itself handles the task of updating the database with the changes made to the current record, when you move the record pointer to another record. UpdateRecord and UpdateControls Method: These methods are special to the Data control. The UpdateRecord method allows the user to save the changes to the current record and continue editing. This will be of great use when the number of fields to be edited on the form is large. The UpdateControls method does the reverse of the above. This method will be of use when the user wants to roll back editing changes made to the current record before updating. Finding a Record: User of our program will find it very tedious to click away and till they reach the record that they want to view. We need to provide a shortcut to enable them to view a particular record. Let us use the Find method. The find method works only when the records type is a Dynaset or snapshot. If the Recordset type is set to Table type, then you have to use seek method. 4.3.6 The DBGrid Control The DBGrid control displays fields from a recordset object as a series of rows and columns, and enables manipulation of this data. The data-aware DBGrid control is like an enhanced Grid control. Once the properties are set, it gets populated automatically with the data from the Recordset object. You only need to fix the number of columns. The total number of rows is indeterminate. A DBGrid control can have as many rows as the system resources can support and about 1700 columns. Eg. Start a new project. On the form add the following control One Data Control One DBGrid Control
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
85
VISUAL PROGRAMMING If you do not have the DBGrid control, as part of your ToolBox (which is usual), Right click on the ToolBox. Select Components from the pop-up menu. From the list display thereafter, click on DBGrid control. Click on OK and you have it on your ToolBox. Set the properties for the controls as follows Data Control Data Source : C: \VB\Biblio.mdb RecordSource: pulishers DBGrid Control DataSource: Data1 Now run the program. 4.3.7 Activex Data Objects ActiveX Data Objects (ADO) is the new data access technology. The DAO with the help of ODBC can let you connect to jet, ISAM databases and other Relational databases. However, today’s data access requirements are not limited to handling only relational data. We need to access data from other sources as well, such as mail, internet content, directory data from other machines and others. The technology required to access information from these different data sources is different. Therefore, the data access model will have to change to accommodate the new requirements. 4.3. 8 OLE DB The general solution Microsoft offers to this problem is OLE DB, a set of component object model (COM) interfaces that provide uniform access to data stored in diverse information sources. OLE DB is defined as a new low-level interface that is part of the Universal Data Access platform. It is defined as a general-purpose set of interfaces designed to let developers build data access tools as components using the component object Model (COM). OLE DB enables applications to have uniform access to data stored in DBMS and non-DBMS information containers, while continuing to take advantage of the benefits of database technology without having to transfer data from its place of origin to a DBMS. This means that OLE DB is not restricted to ISAM, Jet, or even relational data sources, but is capable of dealing with any type of data, regardless of its format or storage method. In practice, this versatility means you can access data that resides in an Excel spreadsheet, text files, or even on a mail server such as Microsoft Exchange. OLE DB has what it calls ‘providers’ which let you access the different data sources. For different data source you have different data providers. Services of OLEDB 1. A Cursor Service. A cursor is defined as a temporary, read-only table that saves the results of a query with an assigned name. The cursor is available for browsing, reporting, or other uses until it is closed.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
86
VISUAL PROGRAMMING 2. A service to perform batch updates. 3.A shape service to build the data in the form of a hierarchy. 4.A remote data service provider for managing data in multi-tier environments over connected or disconnected networks. Unfortunately Visual Basic cannot access the OLE DB directly because of its sophistication. The ADO acts like the intermediary between the application and the OLE DB. ADO ADO enables your client applications to access and manipulate data in a database server through any of the OLE DB providers. According to Microsoft, “ADO’s primary benefits are ease of use, high speed, low memory overheads, and a small disk footprint. Ado supports key features for building client / server and Web-based applications”. The goal of ADO is to gain access, to edit, and update sources. It provides classes and objects to perform each of the following activities: Connection make a connection to a data source. You can access a data source using the connection object. A connection represents an open session or connection to a data source. Unless a connection object specifies the name of the data source, the provider that will be used to access the data, and other parameters. Your application can gain access to a data source directly (sometimes called a twotier system), or indirectly (sometimes called a three-tier system) through an intermediary like the internet information server. After gaining access to a data source, ADO ensures that the updates made to the data source are made such that there is data consistency and integrity. A transaction delimits the beginning and the end of a series of data access operations. If you cancel the transaction or one of its operations fails, ADO ensures that the changes made are ‘rolled back’ such that the ultimate result will be as if none of the operations in the transaction had occurred. Command - Create an object to represent an SQL command. Once a connection has been established with the data source, the data has to be extracted. This is done using the command object. The command adds, deletes and updates data in the data source, or retrieves data in the form of rows in the table. Parameter - specify columns, tables, and values in the SQL command as variable parameters. The command to retrieves data can be qualified using parameters. Parameters are arguments to a command that alter the result of the execution of the command. For example, you could issue the same data retrieval command repeatedly, varying your specification of the information to be retrieved each time.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
87
VISUAL PROGRAMMING Recordset - Execute the command and store the result, if the command is row returning, in a cache. Allow the user to sort, view or edit the data. If necessary, update the data source. Although ADO allows you to access any type of data, our discussion here is limited to data from a database. The command object when executed will return a set of rows from one or more tables. This set of row is called a Recordset. This is not different from the definition of the recordset in the DAO object model. The Recordset is placed in local storage. However, there is no object that represents a single row of a Recordset. The Recordset is the primary means of examining and modifying data in the rows. The Recordset object allows you to:
Specify which rows are available for examination
Traverse the rows
Specify the order in which the rows may be traversed
Add, change, or delete rows
Update the data source with changed rows
Manage the overall state of the Recordset.
Field: A row of a Recordset consists of one or more fields. If you envision the Recordset as a two-dimensional grid, the fields line up to form columns. Each field (column) has among its attributes a name, a data type, and a value. It is this value that contains the actual data from the data source. To change the data in the data source you have to modify the value of the field object. In order to make sure that every occurrence of a particular field in all the tables is modified, you can use the transaction method of the connection object. Error : Errors can occur at any time in your application, due to the data source being corrupted or renamed by somebody, or the password being changed or for many other reasons that a programmer can under send. These results in not being able to establish a connection, execute a command, or perform an operation on an object in a state (for example, attempting to use a Recordset object that has not been initialized). The error object behaves like the error object in DAO. Property : Each ADO object has a set of unique properties that either describe or control the behaviour of that object. There are two types of properties: built-in and dynamic. Built-in properties are part of the ADO object, and are always available. Dynamic properties are added to the ADO object’s properties collection by the underlying data provider, and exist only while that provider is being used. Collection:
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
88
VISUAL PROGRAMMING Just as in DAO, ADO provides collections, a type of object that contains other objects of a particular type. The object in the collection can be retrieved with a collection method, either by name, as a text string, or by ordinal as an integer number. ADO provided four types of collections: The connection object has errors collection, which contains all error object created in response to a single failure involving the data source. The command object has the parameters collection, which contains all parameter objects that apply to that command object. The Recordset object has the field’s collection, which contains all field objects that define the columns of that Recordset object. In addition, the connection, Command, Recordset, and field objects all have a Properties collection, which contains all the property objects that apply to their respective containing objects. Events: This is new in ADO. ADO 2.0 introduces the concept of events to the programming model. Events are notifications that certain operations are about to occur, or have already occurred. If you know that an event is about to occur, for example a commit or a delete, you have the opportunity to examine the parameters and take suitable action. This is just like windows asking your permission to delete the files from the recycle bin. The events that inform you about the completion of a particular operation allow the application to proceed with the next step. Event handlers called after an operation completes notify you at the completion of an asynchronous operation. ADO 2.0 introduces several operations that have been enhanced to optionally execute asynchronously. Open operation is notified by execution complete event when the operation concludes. There are two families of events: Connection Events – Events are issued when transactions on a connection begin, are committed, or rolled back, when commands execute, and when connections start or end. Recordset Events – Events are issued to report the progress of data retrieval in the following case: when you navigate through the rows of a Recordset, object, when you change a field in a row of a Recordset, change a row in a Recordset, or make any change in the entire Recordset.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
89
VISUAL PROGRAMMING
FIG – 10 – CONNECTING TO THE DATABASE USING OLEDB CONTROL
FIG -11 EXAMPLE FOR MSFLEX GRIDAND DATA GRID
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
90
VISUAL PROGRAMMING
91
UNIT – V GRAPHICS, BASIC FILE HANDLING AND CREATING ACTIVEX CONTROLS 5.1.INTRODUCTION TO GRAPHICS The graphic methods in Visual Basic allow you to control each dot that appears on the screen. Certain combinations of hardware, software and monitors can divide the screen into more than 1,000,000 dots and theoretically choose from a palette of more than 16,777,216 (256 * 256 * 256) colours for each pixel. 5.1.1 Fundamentals of Graphics To draw on the screen, from Visual basic the commands are passed to windows, windows in turn tells the display adapter to how to display the images. To save a copy of the object in memory set the AutoRedraw property to true. The effects of setting the AutoRedraw property to true are slightly different for forms and picture boxes.
For a resizable form, Visual basic saves a copy of the entire form. Thus, when the form is enlarged no graphics information is lost.
For a picture box, Visual Basic saves an image only as large as the current size of the box. Nothing new will appear even if the box is enlarged later.
Thus, drawing to picture boxes requires less memory than drawing to forms, even if the picture box fills up the form. 5.1.2 Screen Scales The default scale for forma and picture boxes is twips, that is 1.20 of a printers point and 1/440 of an inch. The default size for a VGA monitor of 14 inch size is 640 x 480 and in twips the size is 7485 x 4425. Coordinates
Location
(0,0)
Top left corner
(7485, 0)
Top right corner
(0, 4425)
Bottom left corner
(7485, 4425)
Bottom right corner
(3742, 2212)
Roughly the center
Other Screen Scales: There are other six screen scales. These scales can be set by using the ScaleMode option. Once you set the scalemode property, the size of the window can be found using the ScaleHeight and ScaleWidth.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING
92
ScaleMode
Units
1
Twips
2
Points (72 per inch)
3
Pixels
4
Characters
5
Inches
6
Millimeters
7
Centimeters
Custom Scales: The screen is normally numbered with (0,0) as the top left corner. This is obviously inconvenient for drawing tables, charts, graphs and other mathematical shapes. In mathematics, we use the Cartesian (X-Y) system, with X measuring from left to right and Y from bottom to top. You can use the command Scale (-320, 240) â&#x20AC;&#x201C; (320, -240) to set up the new coordinate system with (0,0) at the centre of the form. Then the coordinates specify the four corners are, (-320, 240) ( 320, 240) (320, -240) (-320, -240) The general syntax of the Scale method is Scale (LeftX, TopY) â&#x20AC;&#x201C; (RightX, BottomY) 5.1.3 The Line and Shape Controls The shape control can be used to display rectangles, squares, ovals and circles. Using this you can draw the rounded rectangles and rounded squares. The Line control can be used to draw the lines with various thickness. Shape: This determines the type of the shape. There are six possible settings Setting of the Shape Property
Effect
0
rectangle
1
Square
2
Oval
3
Circle
4
Rounded Rectangle
5
Rounded square
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING
93
The Line Control: The Line control has 15 properties. The most important property for the line control at design time is BorderStyle and BorderWidth. BorderWidth property sets the thickness of the line. The BorderStyle property sets the style of the line like solid, dashed and so son. Value of BorderStyle
Meaning
0
Transparent
1
Solid
2
Dashed
3
Dotted
4
Dash dot
5
Dash dot dot
6
Inside Solid
FIG – 12 – EXAMPLE FOR GRAPHIC PRIMITIVES 5.1.4 Graphics via Code Instead of drawing shapes at the design time using the methods the drawings can be carried out using codes. Colour:
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING
94
If the colour is not specified, then the Visual Basic uses the foreground colour for all the graphics methods. There are four ways to specify colours. The first way is at design time using the palettes that show up in the property window. The second way is by using the hexadecimal code in the code or at design time. The third way us to use the RGB function. The syntax for the function is RGB(AmountofRed, AmountofGreen, AmountofBlue) where the amount of color is an integer between 0 to 255. The last method is by using the QBColor function.
QBColor(colorcode) where colorcode is an integer value between 0 and 15. code
Color
Code
Color
0
Black
8
Gray
1
Blue
9
Light blue
2
Green
10
Light green
3
Cyan
11
Light cyan
4
Red
12
Light red
5
Magenta
13
Light magenta
6
Brown
14
Yellow
7
White
15
High intensity white
Pixel Control: This control is used to turn on the pixel. The syntax for this method is PSet(Col, Row) [, ColorCode] 5.1.5 Lines and Boxes In addition to shape and line controls, Visual Basic provides the graphic primitives to draw the geometric figures such as lines, boxes, circles, ellipses and wedges with single statements. The Line method takes the form Line (StartCol, StartRow) â&#x20AC;&#x201C; (EndCol, EndRow), ColorCode This method draws the line between the specified coordinates using the color specified in the colorcode. Visual Basic keeps track of where it stopped plotting. This location is usually called the last point referenced(LPR) and the values of the CurrentX and CurrentY variables store this information. For example Line - (160, 90) Draws a line from the last point referenced to the point with the coordinates (160, 90).
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING
95
Boxes: Line method with little modification draws a rectangle. Line (FirstCol, FirstRow) â&#x20AC;&#x201C; (SecCol, SecRow),CCode, B draws a rectangle in the given colour code, whose opposite corners are given by FirstCol, FirstRow and SecCol, SecRow. 5.1.6 Filled Boxes In the above method instead of B use BF to get the filled box. Filled Style, Fill Color: Boxes are usually solid or empty but visual basic allows you to use seven different patterns to fill boxes. Settings of FillStyle Property
Effect
0
Solid
1 (Default)
Empty
2
Horizontal line
3
Vertical Line
4
Upward Diagonal
5
Downward Diagonal
6
Cross
7
Diagonal Cross
5.1.7 Circles, Ellipses and Pie charts The Circle method is used to draw the circle. The syntax is Circle (0,0) , 0.5 The last point referenced (CurrentX, CurrentY) after a Circle method is always the center of the circle. The color code can also be added to the circle method. Circle (0,0), 0.5 , CCode would draw a circle of radius of 0.5 in the colour specified in the colorcode CCode. The method Circle (Xrad, Yrad), Radius, CCode, StartAngle, EndAngle draws an arc of the circle starting at the angle given in radians by StartAngle and ending with EndAngle. Ellipses and Aspect ratio: By adding one more option the same circle draws an ellipse. The syntax for the method is Circle [step] (XCenter, YCenter), radius, , , , aspect.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING
96
If the aspect parameter is less than 1, the radius is taken in the column direction and the ellipse is stretched in the horizontal direction. If the aspect parameter is greater than 1, the radius is taken in the row direction and the ellipse is stretched in the vertical direction. 5.2. BASIC FILE HANDLING 5.2.1 File Commands Visual basic has six commands that interact with the operating system and mimic the usual operating system commands that handle files and drives. Mkdir “testdir” – Creates a subdirectory called “testdir” in the current directory. Mkdir “C:\testdir” – Creates a subdirectory to the root directory of the C drive. ChDrive – Changes the logged drive for the underlying operating system ChDir
- Changes the default directory
RmDir – Removes a directory Name - Changes the name of the file Kill
- Deletes a file from a disk.
5.2.2 File handling Functions File Copy Function: FileCopy function copies a file from the source path to another path. FileCopy source, destination This function does not allow wild cards. FileDateTime function: This function returns the date and time a file was created or last modified. The syntax is FileDateTime(pathname) The GetAttr function: The GetAttr function returns an integer. The syntax for the function is GetAttr (pathname) As integer
Attribute
Constant
Value
Normal
vbNormal
0
ReadOnly
vbReadOnly
1
Hidden
vbHidden
2
System
vbSystem
4
Volume
vbVolume
8
Directory
vbDirectory
16
Archive
vbArchive
32
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
VISUAL PROGRAMMING The SetAttr Function: The SetAttr function sets the attribute information for files. The syntax for this function is SetAttr Pathname, attributes. For example, SetAttr FIleName$, vbHidden, vbReadOnly would hide the file and set it as read only. 5.3. BUILDING YOUR OWN ACTIVEX CONTROLS Prior to the development of Visual Basic 5, VB developers relied on C++ to create a new reusable controls. Visual Basic 5 has the provision to create new controls. Choose ActiveX control from the New Project dialog box. The form in the middle of the user control designer is user control form. You can add control or controls correspondingly you can add the code to interact. Usually text box is a control, which accepts the user value as a string. To do arithmetic computations the input entered through the text box has to be converted to numeric value. So, you can create a numeric text box control using ActiveX control. Design a numeric text box with the properties:
The current value
A minimum acceptable value
A maximum acceptable value
A range value that allows you to easily set a symmetric range.
Add two custom events to the user control
BadKey for when the user tries to type something like a letter in the box
BadValue for when the user exceeds the range or copies a non number into the box.
1. Choose ActiveX control from the New Project dialog box. 2. Add a textbox to the user control. 3. Change the name of the usercontrol1 to NumericTextBox Testing the control:
Choose File/Add project.
Choose Standard EXE and click open. Now the project explorer will contain both the projects.
Double click the form in the project2.
Double click on the Numeric Text box line in the project explorer to make the user control active.
Close the control designer.
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
97
VISUAL PROGRAMMING ď&#x201A;ˇ
To use the new control, double click the icon of the new control in the tool box.
These steps allows you to create a control of your own and adding the control to your project. Still you have to add events to make the control as a numeric text box. After selecting usercontrol, add the events you want. To add custom events, for example add the given code to lostfocus event. Private sub txtValue_LostFocus( ) If Not (IsNumeric(txtValue.Text)) Then RaiseEvent BadValue(NotNumeric) End IF End Sub
Add the following information in the declarations of the general section of the user control form. Public Event BadValue(WhatsWrong As Integer) Public Event BadKey( ) Test the control by placing it in some project.
------------------------------------------THE END------------------------------------------
FOR MORE DETAILS VISIT US ON WWW.IMTSINSTITUTE.COM OR CA LL ON +91-9999554621
98
VI SUALPROGRAMMI NG
Publ i s he dby
I ns t i t ut eofManage me nt& Te c hni c alSt udi e s Addr e s s:E4 1 , Se c t o r 3 , No i da( U. P) www. i mt s i ns t i t ut e . c o m| Co nt a c t :9 1 +9 2 1 0 9 8 9 8 9 8