Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 17

1 1

Windows Programming : User Interfaces(Connection between the computer Windows Memory Management : Older versions: 16-bit, segmented memory 
and the user Two types: Command Line GUI--Graphical (Visual) Dictated by processor architecture  Hard to program )  Newer versions: 32-
Command Line Interfaces : User types commands ==> must remember  bit, flat memory model  Easier to program As old programs terminate, new
Results Scroll by  Text-based  “Interactive” but hard to use  Flow of info: ones start; code swapped into and out of memory  Fragmentation can occur
keyboard --> program--> Display  No direct interaction between user and screen Windows must consolidate memory space  Moves blocks of code / Data
Visual (Graphical) Interfaces : continually Several instances of a program ( code only loaded into memory once
1. Show Graphical Objects (images, 5. Use graphics to organize user  program instances share same code )  Programs can share code located in
icons, buttons, scroll bars) on screen workspace other files (Dynamic linking)
2. User interacts using pointing device ( 6. Present user intuitive ways of Static vs. Dynamic Linking :Static Linking : code incorporated into executable
Direct, intuitive, intimate interaction) accomplishing tasks(e.g., copy files at link time / Dynamic Linking : Linker generates relocation info ( Put into
3. Objects can be dragged, buttons by dragging executable )  DLL loaded when needed  Relocation info used to get DLL
pushed, etc.... 7. Environment allows many tasks to function code as needed
4. Better way of using screen space be performed simultaneously DLL’s : Dynamic Link Library : DLLs - introduced with the first releases of
( Panes can overlap  Underlying ( Different tasks share screen the Microsoft Windows OS, and today are a fundamental structural component of
panes can be brought to forefront space ) the OS DLLs allow certain code fragments to be compiled into a single library,
Desktop metaphor (like papers on 8. Visually rich way of conveying and to be linked to by multiple programs. This means that only one copy of the
a desk) •Well, not exactly! ) information
library needs to exist, and multiple programs can share the functions and the data
WYSIWYG display of documents
Main Feature of GUIs: btween them. (eg of DLL ; COMDLG32.DLL -controls the dialog boxes 
THE WINDOW ( Rectangular area of screen onto which a program draws text GDI32.DLL-contains numerous functions for drawing grphics, dsplying txt and
and graphics.  User interacts with program using pointer device to select objects managing fonts  KERNEL32.DLL -contains hundreds of functions for the
inside. Some window components:( border, title bar, client area, menu bar, scroll management of memory and various processes)
bars, max/min/close buttons, tool bars, etc.) Pros/Cons of Dynamic Linking (Smaller programs (code is not there)  DLL
Brief History of GUIs : 1968, ARPA-funded Stanford Research Center (Doug can be used by many programs with no memory penalty : Only loaded once! 
Englebart) first windows (screen sliced up into overlapping panes)  only Updates to DLLs don’t require recompilation of programs using them
textual info underlying windows can be popped to the top selection done with  Disadvantage--DLL must be present at run time==>no standalone programs
light pen invented the mouse ) Device Independent Graphics Interface :
Xerox PARC--Alto Computer ( 1970  First GUI  Cursor tracked position of  Windows programs don’t access hardware devices directly
mouse  WYSIWYG  Windows with precise text  Displayed more than   Make calls to generic functions within the Windows ‘Graphics Device
just text First interactive painting program) Interface’ (GDI)
Recent History (PCs) : ( 1983, Apple Lisa (failure)  1984 Apple Macintosh--
standard for GUIs  1985 Microsoft releases Windows 1.0  Difficult to  The GDI translates these into HW commands
program  Prone to crashing  Needed hardware not yet available  1987
Windows 2.0 (still real mode only)  1988 Windows/386 (Virtual 86 mode on  May use device drivers (HW control programs)
386==>multiple DOS sessions in windows)
Recent History (Microsoft)1990 Windows 3.0  80x86 protected mode, up to 
16Meg memory, cooperative multitasking  1992 Windows 3.1, Windows   Thus graphics I/O done in a “standard” way
for Workgroups 3.11  TrueType fonts, multimedia, protected mode only;  Programs will run unaltered on other HW platforms
Networking  1993 Windows NT  32-bit flat memory space, 16 MB, thread- Windows API : The interface between an application and Windows  A library
based pre-emptivemultitasking, separate from DOS, multi-platform, networking, of functions Windows programs can call  Several versions (Win16 (16 bit apps
secure)  1995 Windows 95  Runs on 4 Meg, long file names, plug and play, for Windows 3.xx) Win32 (32 bit apps for Windows NT/95) Win32s
new controls, new desktop/window style  Hybrid 16/32 bit OS, depends on (patches Win16 to create 32 bit apps that run under Windows 3.xx)
DOS, lacks security of NT, no portability to RISC  1998 Windows 98  Web- Win32 API Programming : (• Event-driven, graphics oriented • Example:
like interface, legal issues User clicks mouse over a program’s window area—(Windows decodes HW
Other GUI-Windowing Systems : IBM OS/2: Presentation Manager  signals from mouse / – figures out which window user has selected /– sends a
Commodore Amiga: Intuition  Atari: GEM  Sun Microsystems: NeWS  message to that window’s program: /• "User has clicked over (X,Y)” /• "Do
The X Window System (Developed at MIT, networked graphics programming something and return control to me” /– Program reads message data, does what's
interface, independent of machine architecture/OS (but most used under UNIX) ) needed, returns control to Windows )
Win32 API Programming : Event-Driven Programming (Messages)  Menus Overview of Win32 API Program Structure--2 main tasks:
and other Resources  Text and Graphics  Mouse and Keyboard Bitmaps, • Initial activities • Process messages from Windows (the message loop)
Animation, Timers  Child Window Controls Child and Popup Windows  PSEUDOCODE : • Initialize variables, memory space  • Create & show
Dialog Boxes  The Clipboard program's Window  • Loop (– Fetch any msg sent from Wndws to this pgm / –
Microsoft Foundation Class (MFC) Programming : If message is QUIT ) • terminate program, return control to Windws (– If
1. The MFC Class Hierarchy 6. File Handling and Printing message is something else )  • take actions based on message & parameters  •
2. The Application/Window 7. Dialog-Based MFC Applications and return control to Windows  • End Loop
Approach Common Dialog Boxes API : Application Programming Interface (API is a set of routines, protocols, and
3. The Document/View Approach 8. Windows Multimedia tools for building software applications  API is set of commands, which
4. Using “AppWizard” & 9. Network Proging (TCP/IP) with interfaces the programs with the processors.  API consists of thousands of
“ClssWizrd” MFC functions, structures, and constants that can declare and use in projects
5. Drawing, Menus, & Dialog Boxes 10. HTML-based Applications with Classical Windows programming ( Use C to access raw API functions
with MFC MFC directly /No C++ class library wrappers to hide API / Hard way to go, but most
Features of Windowing Systems : Consistent user interface : Display within a basic & flexible /Provides understanding of how Windows and application
window  Menus to initiate program functions Make use of controls: program interact / Establishes a firm foundation for MFC programming /We will
(predefined windows used with main program window / examples: buttons, scroll try to do both
bars, edit controls, list boxes, drop-down list boxes / Dialog box--popup window Essential Parts of a WndwsPgm ( • I. The source prg (.c/.cpp file):  – A.
containing several controls )  Programs have same look and feel  Same built- WinMain() function  • 0. declartions, initialization, etc.  • 1. register window
in logic to: (draw text/graphics /display menus /receive user input (controls, dialog class  • 2. create a window based on a registered class  • 3. show window,
boxes, use of mouse ) make it update its client area  • 4. the message loop (get msages from
Multitasking : Every program acts like a RAM-resident popup  Programs run Windows, dispatch back to Windows for forwarding to correct callback msge-
“simultaneously”  Each program’s output occupies its own window  processing function) – B. WndProc(): the msg-processing function.
Windows can be moved and sized  User can switch between programs The WinMain() Function (• int PASCAL WinMain (HINSTANCE hInstance,
Windows Multitasking Features :Cooperative (Windows 3.xx) (Programs must HINSTANCE hPrevInstance,  LPSTR lpszCmdLine, int nCmdShow); •
give up control so others can run / Programs coexist with other programs ) WinMain() starts first  • int exit code returned to Windows  • PASCAL l-to-r
Preemptive (Windows NT, 95, 98) (Thread-based--System timer allocates time parameter passing on stack  • 4 parmeters passed in from Wins  – hInstance: a
slices to running program threads ) handle, identifies current pgm instance  – lpszCmdLine: string containing
Under both systems, code is moved or swapped into and out of memory as needed. command line args  – nCmdShow: how window is to appear when shown
Windows Object Orientation : A window is handled like a C++ object ( Has a PROGRAMMING PARADIGMS Categories of Programming paradigms The
user-defined type (Windows class) , Instances of class created at run time , various categories of programming paradigms are:
Messages sent to windows affect their behavior ) 1. 2.1. Aspect-oriented programming : In software engineering, the programming
2 2
paradigms of aspect-oriented programming (AOP), and aspect-oriented software be written in different languages (C++, , etc.) and interfaced together seamlessly. 
development (AOSD) attempt to aid programmers in the separation of concerns, COM programs (or "COM clients") can be written in most langages that allow object-
specifically cross-cutting concerns, as an advance in modularization. AOP does so orientation.
using primarily language changes, while AOSD uses a combination of language, RegisterClass(&wndclass); ( typedef struct tagWNDCLASS {  UINT style;
envrnmnt, and mthod. Terminology (Cross-cutting concerns: Adv: Point-cut: LRESULT CALLBACK lpfnWndProc)();  int cbClsExtra;  int cbWndExtra;
Aspct: HINSTANCE hInstance;  HICON hIcon;  HCURSOR hCursor;  HBRUSH
2. 2.2 Functional programming : Functional programming is a programming hBackground;  LPSTR lpszMenuName  LPSTR lpszClassName } WNDCLASS;
paradigm that treats computation as the evaluation of mathematical functions and if (!RegisterClass (&wndclass)) return 0;  Sets general properties of all windows
avoids state and mutable data. ( Higher-order functions : Pure functions : based on class // ShowWindow (hWnd,nCmdShow); (• makes window visible on
Recursion : screen  • hWnd: which window to make visible • nCmdShow: how (normal,
3. 2.3 Generic Programming : Generic programming is a programming paradigm minimized, etc.) – set by Windows environment when program is started; –
for developing efficient, reusable software libraries OOP value is passed in from Windows; – "normal" can be overridden ) //
4. Object-oriented programming : Fundamental concepts CreateWindow() arguments: (window class name  window caption  window
 Class: A class defines the abstract characteristics of a thing (object), the style (OR of style masks)  initial x , y position in pixels  initial width , height
properties and methods defined by a class are called members. parent window handle (if main window, NULL)  window menu handle (NULL if
 Object: A particular instance of a class. The set of values of the attributes of a class menu used)  program instance handle (passed in from Windows)  creation
particular Object is called its state. parameters (for extra data, usually NULL) // UpdateWindow (hWnd); ( • Causes client
 Inheritance: ‘Subclasses’ are more specialized versions of a class, area to be updated  • Painted with background brush 
 Encapsulation: Encapsulation conceals the functional details of a class from The Message Loop : (• User interaction-->a msg sent to a window • Lots of other
objects that send messages to it actions-->messages • A message structure: – HWND hwnd; // target window
 Abstraction: Abstraction is simplifying complex reality by modelling classes handle – UINT message; // msg ID value--WM_*** – WPARAM wParam; // data
appropriate to the problem, and working at the most appropriate level of passed in msg  – LPARAM lParam; // more data in msg  – DWORD time; // time
inheritance for a given aspect of the problem. msg was sent  – POINT pt; // mouse cursor position (x,y)
5. Polymorphism: Polymorphism allows you to treat derived class members just like GetMessage() : (• Program must keep checking for messages • Use message loop
their parent class' members. with GetMessage() • BOOL GetMessage( LPMSG lpMsg, //ptr to msg struct
6. 2.6 Service-orientation : Service-orientation is a design paradigm that specifies HWND hWnd, //target window UINT wMsg1, //1st msg in range UINT wMsg2,
the creation of automation logic in the form of services. Services inherit a number //last msg in range)
of features of software components, including: (Multiple-use / Non-context-specific GetMessage() (• Reads next msg from app's msg queue • Fills MSG struct pointed to
/ Composable / Encapsulated ) by first param. • Place in a loop: while (GetMessage(&msg, NULL, 0, 0))  { ... }
Language Oriented Programming: The Next Programming Paradigm :  return(msg.wParam);  • Returns non-0, except for WM_QUIT msg  •
( Understanding and Maintaining Existing Code /Domain Learning Curve /What Terminates msg loop & returns control to
Is a Program in LOP? ) Message Processing ( • What goes inside the message loop:  TranslateMessage
MFC Library ( Microsoft’s C++ Interface to Windows API  O-O Approach to (&msg)-"  Cooks" keyboard input  Converts raw key codes to ANSI codes
Windows Programming  Some 200 classes  API functions encapsulated in the DispatchMessage (&msg)-Sends  message on to Windows, which  forwards it to
MFC  Classes derived from MFC do grunt work  Just add data/functions to program's "Window Procedure":
customize app Provides a uniform application framework Windows : The Window Procedure ( • "callback" function (called by Windows)
Class-based Windows programming ( Microsoft’s MFC Library / Borland’s OWL • Should contain a switch/case statement :  – Looks at message ID of current
Library /Encapsulate the API functions into classes /Provide a logical framework for message  – Acts appropriately on "interesting" messages  – Forwards other
building windows applications messages to default Window procedure--DefWindowProc()
Microsoft Visual C++ ( 2 Windows app development systems / C programs using WndProc()- 2nd member of WNDCLASS structure  Programmer must write this
Win32 API /C++ programs using MFC / Some Developer Studio IDE Components function 
Text/Resource Editors /C/C++, Resource Compilers / Linker / Debugger / Wizards WndProc() LRESULT CALLBACK WndProc (  HWND hWnd, UINT wMessage,
/On-line Help  WPARAM wParam, LPARAM lParam) Parameters-Same as first four fields of
Some MFC Characteristics ( Reusable code  Smaller executables  Faster program MSG structure: – window associated with message – message ID (what message is) –
development  But a steep learning curve is required  And there is less flexibility  message data (wParam & lParam)
Prg must be written in C++ Require the use of classes==> Prgrmmr must knw OOP The WM_DESTROY Message (• Sent when user does something to kill window  •
Sequential Programming : Stdard Event-Driven Programming : Designed to WndProc() should respond by calling:  – PostQuitMessage();  • Windows sends
programming--program solicits input avoid limitations of sequential,  procedure- WM_QUIT msg to queue  • wParam = 0 implies: (– 0 returned by GetMessage() in
(polling loop)  Approach follows a driven methodologies  Prcss events as they WinMain() /– so program exits WinMain()'s message loop / – and return to Windows )
structured seqe of events eg-- happen-non-sequential  Prg doesn’t solicit • WM_COMMAND--User clicked on menu item, LOWORD(wParam) = menu item
averaging grades: (Input name /Input input  OS detects an event has happnd ID • WM_*BUTTONDOWN--left/right muse button pressed (* = L or R,
first grade / Input second grade / (e.g.., there’s input) and sends a msg to the lParam=x,y coordinates)  • WM_MOUSEMOVE--mouse moved (lParam=x,y
Input third grade / Calculate prg Prgrm then acts on the msg Msg can coords)
average/Output average ) occur in any order • WM_CHAR--User pressed valid ANSI code character keyboard key combination
Sequential vs. Event-Driven Programming : Stndard Sequential prgramming: (wParam=ANSI code)  • WM_PAINT--Part of window was exposed & should be
Program does something & user responds  Program controls user (the tail wags the redrawn  • WM_KEYDOWN--keyboard key pressed (wParam= virtual key code)
dog)  Event-Driven Programming: Used by Windows  User can act at any Windows Data types : (Hungarian Notation : The Win32 API uses the so-called
time  User controls program (the dog wags the tail)  OS really is in cntrl (coor "Hungarian Notation" for naming variables. Hungarian Notation requires that a
dinates msg flow to different applications) Good for apps with lots of user variable be prefixed with an abbreviation of its data type, so that when you are reading
intervention the code, you know exactly what type of variable it is. The reason this practice is
4. Comparison of all programming paradigms : As with all immature technologies, done in the Win32 API is because there are many different data types, making it
widespread adoption of AOP is hindered by a lack of tool support, and widespread difficult to keep them all straight.
education. Some argue that slowing down is appropriate due to AOP's inherent ability to  LPVOID : LPVOID data , a "pointer to a void object". ANSI-C stndrd
create unpredictable and widespread errors in a system. Implementation issues of some  LONG, INT, SHORT, CHAR : specific length. LONG notation  LONG
AOP languages mean that something as simple as renaming a function can lead to an variables are typically prefixed with an "l" (lower-case L). UINT notation 
aspect no longer being applied leading to negative side effects. Programmers need to be UINT variables are typically prefixed with an "i" or a "ui" to indicate that it is an
able to read code and understand what's happening in order to prevent errors1. While integer, and that it is unsigned.  CHAR, UCHAR notation 
they have grown accustomed to ignoring the details of method dispatch or container-  DWORD, WORD, BYTE  These data types are defined to be a specific length,
supplied behaviors, many are uncomfortable with the idea that an aspect can be injected regardless of the target platform DWORDs (Double WORDs),  WORDs (Single
later adding behavior to Functional programming is very different from imperative WORDs BYTEs are strictly unsigned 8-bit values
programming. The most significant differences stem from the fact that functional  STR, LPSTR TCHR TCHAR can hold either standard 1-byte ASCII
programming avoids side effects, which are used in imperative programming to  HANDLE HANDLE important data objects in Win32 programming. Inside the
implement state and I/O. Pure functional programming disallows side effects kernel, Windows maintains a table responsible for. Windows, buttons, icons, mouse
completely. Disallowing side effects provides for referential transparency, which makes pointers, menus, and so on, all get an entry in the table, and each entry is assigned a
it easier to verify, optimize, and parallelize programs, and easier to write automated unique identifier known as a HANDLE.  If you want to pick a particular entry out
tools to perform those tasks. Aspects emerged out of object-oriented programming and of that table, you need to give Windows the HANDLE value, and Windows will
computational reflection. AOP languages have functionality similar to, but more return the corresponding table entry.  HANDLEs are defined as being unsigned
restricted than met object protocols. Aspects relate closely to programming concepts 32-bit quantities in <windows.h>, but HANDLEs should never be used like integers.
like subjects, mixins, and delegation. Using AOP judiciously to develop your own code HINSTANCE : HINSTANCE variables are handles to a program instance.
can result in powerful succinct expressiveness. Using AOP to add to code written by Each program gets a single instance variable, and this is important so that the
someone else (especially when you don't have the source code) is risky. kernel can communicate with the program.
COM : Component Object Model (Microsoft implemented a technology known as the HINSTANCE variable to the kernel, so that the kernel knows where the new
COM for Windows.  COM essentially takes the object-oriented programming window belongs to. If you want to communicate with another program, it is
paradigm to the next level, by standardizing the class interface, and allowing classes to frequently very useful to have a copy of that program's instance handle.
3 3
HINSTANCE variables are usually prefixed with an "h", and furthermore, Visual C++
since there is frequently only one HINSTANCE variable in a program, it is Using Microsoft Visual C++ Developer Studio ( Self-contained environment for
canonical to declare that variable as such: HINSTANCE hInstance; Windows program development: (– creating – compiling – linking – testing
 HMENU:If your program has a drop-down menu available (as most visual Windows /debugging ) /• IDE that accompanies Visual C++
prgrams do) that menu will have an HMENU handle associated with it. To dsp the Visual Studio Components : The Editors C or C++ source program editor
menu,orto alter its cntnts, you need to access to this HMENU handle.HMENU (cut/paste color cues, indentation, / generates text files )
handles are frequently prefixed simply an "h". Resource Editor (icons, bitmaps, cursors, menus, dialog boxes, etc. / graphical,
 WPARAM, LPARAM  WORD-length (16-bit) parameters, and LONG-length (32- WYSIWYG, Integrated / generates resource script (.rc) files / integrated with text
bit) parameters. These parameter types were defined as being WPARAM (16-bit) and editor )
LPARAM (32-bit). However, in modern 32-bit systems, WPARAM and LPARAM The Compilers ( • C/C++ Compiler : – translates source pgms to machine
are both 32 bits long. The names however have not changed, for legacy reasons. 
language / – detects and reports errors /– generates object (.obj) files for linker ) 
WPARAM and LPARAM variables are generic fnc prmeters, and are frequently type-
cast to other data types including pointers DWORDs.
• Resource Compiler: (–Reads .rc file /– Generates binary resource (.res) file for
Resource Script : The resource compiler compiles a special type of file Resource linker )
scripts contain GUI data, and, when compiled, can be linked into a program. The The Linker : (reads compiler .obj/.res files / accesses C/C++/Windows libraries /
program then can access the data contained in the resource script. Types of resources : generates executable (.exe or .dll) )
Here is a list of common resources:  Drop-down Menus Popup Menus  Text
Strings Keyboard Accelerators (keypress combinations, such as [Ctrl]+[C] to copy
text) (Icons ,Bitmap Images ,Dialog Boxes ,Version information ,Mouse Cursors )
Making a Resource Script :The syntax for writing resource scripts is similar to C. For
instance, the resource script compiler uses the standard C preprocessor. This is
important because you must include the header file <afxres.h> to make a resource
script. Also, most resource scripts contain macro values, so programmers will
frequently store the related macro definitions in a header file "resource.h". This way, the
same macros can be included and used in the main program files.
Using a Resource : Once a resource is stored in your executable there are various
methods to access it. These methods differ depending on what type of resource you are
trying to access. For instance if you want to access a string resource, you would need to
use the LoadString function; correspondingly the LoadIcon function is needed to access The Debugger powerful source code debugger ( integrated with all parts of Dev
an icon. To access a resource you must have the instance handle of the executable file Studio : (• Features /– breakpoints /– tracing through/over functions / – variable
that contains the resource. This means, that if you obtain an instance handle to another
watch windows /– much more )
executable (or DLL) file, you can access the resources remotely! Occasionally,
prgrmmers will create DLL files that contain nothing but resources for use in other prgs.
The Wizards : • AppWizard : (– Windows code generator for MFC apps ,–
MAKEINTRESOURCE : The MAKEINTRESOURCE keyword that we will automatically creates working program skeletons )  • ClassWizard (– facilitates
occasionally see when dealing with resources is an important keyword, and a program easy extension of AppWizard¬generated classes / – used to tailor AppWizard-
will crash (or not even compile) if it is not used correctly so taking a minute to generated MFC skeletons )
understand it is well worth the effort. Resources are all stored with a name which can Online Help : (• Can be accessed by: – InfoViewer book/chapter / – Topic
be a string or a numerical identifier. If it is numerical, the number must be no larger (keyword search-->relevant topics/articles) – F1 help (help on item under mouse
than an unsigned 16-bit integer (65535, max). Resources are all called by name, that is cursor) – The Web: MSDN (Microsoft Developer Network)
the system is expecting an unicode string with the name of the resource. However if we InfoViewer Online Help : Platform, SDK, and DDK Documentation Platform
use a numerical identifier we need to inform the system that we are doing so, SDK Reference Functions Win32 Functions (Alphabetical listing) Messages
Graphics Device Interface : Jump to: navigation, search The Graphics Device Win32 Messages (Alphabetical listing) Structures Win32 Structures (Alphabetical
Interface (GDI) is a Microsoft Windows application programming interface and core listing)
operating system component responsible for representing graphical objects and MSDN Library : Visual Studio 6.0 Documentation  Visual C++ Documentation
transmitting them to output devices such as monitors and printers. GDI is responsible Reference  Microsoft Foundation Class Library & Templates  Microsoft
for tasks such as drawing lines and curves, rendering fonts and handling palettes. It is Foundation Class Library  Class Library Reference  Platform SDK Graphics
not directly responsible for drawing windows, menus, etc.; that task is reserved for the and Multimedia  Win32 API Reference  Win32 Functions in Alphbetical
user subsystem, which resides in user32.dll and is built atop GDI
Order)
Windows Platform SDK (Microsoft Windows SDK, Platform SDK, are Other Advanced Tools : ( SPY++ / PVIEW / ActiveX utilities, a gallery of
software devlopment kits from Microsoft that contain header files, libraries, software components / More Using Developer Studio 97 and Visual C++ 6.0 : ( •
samples, documentation and tools required to develop  Obtaining the SDK To prepare many kinds of applications / – Win32 Console
SDK support for older operating system Tools, headers and libraries Components : ( Menu bar / Several tool bars (• Project Workspace Window (left)
Obtaining the SDK : Windows SDKs are available free on the Microsoft / – InfoView, FileView, ClassView, ResourceView / • Editor Window (right) / –
Download Center, in ISO and Web-download formats. Users can install the entire Enter C/C++ code / Output Window (bottom). / – System messages (errors) )
SDK or choose to install only some SDK components, such as code samples Applications (DOS programs) / – Win32 API Apps / – Win32 MFC apps / –
demonstrating only native development or only the tools for managed DLLs / – Lots of others )
development. Some Windows SDK components are also included in Microsoft Toolbars : ( Contain icons--instant routes to main menu functions  Output,
Visual Studio. The latest Windows SDK is the Microsoft Windows SDK for Workspace, Standard, Build, Edit, InfoViewer, Resource, etc.  May not be
Windows 7 and .NET Framework 4, released May 21, 2010[3]. This SDK release visible  If not, right click on any visible toolbar  Brings up following popup
supports Windows 7, Windows Server 2008 R2, Windows Vista, Windows Server window  Can activate a toolbar by clicking on its check box )
2008, Windows XP SP3, and Windows Server 2003 R2 and is compatible with Projects and Workspaces ( • Project : – collection of interrelated source files –
Visual Studio 2010, Visual Studio 2008, and Visual Studio 2005 SP1, including compiled/linked to generate a Windows executable ) / • Project Workspace (–
Visual Studio folder with all information relating to a project  – also used to refer to
SDK support for older operating systems : A developer might want to use an older Visual Studio desktop window )• Project info stored in .dsw and .dsp text files
SDK for a particular reason. For example, the Windows Server 2003 Platform
Important Dev Studio Generated Files Temporary Dev Studio generated files
SDK released in February 2003 was the last SDK to provide full support of Visual
• .dsp Project file • Many are huge can (should) be
Studio 6.0. Some older PSDK versions, including the February 2003 SDK can still
• .c or .cpp C/C++ source rmvd!
be downloaded from the Microsoft Download center
• .h C/C++ header • .ilk Incremental link file
Documentation : (The Windows SDK documentation includes the following:
• .dsw Workspace file • .pch Precompiled header
Manuals documenting managed code development  Manuals documenting
• .rc Resource script • .pdb Precompiled debugging info
Win32 development  "New in Windows Vista" topics; All SDK
• .res Compiled resource • .idb Incremental debug info
documentation is part of the online and disc-based MSDN Library
• .ico Icon • .ncb Supports viewing classes
Tools, headers and libraries
• .bmp Bitmap image • .aps Supports viewing resources
The Windows SDK contains the following: (For Win32 development: 1,915
• .exe Executable program • .bsc Browser information file
Headers / 348 Libraries / 100 Tools )
• .dll Dynamic Link Library • .clw Supports ClassWizard
Device Context: A data structure defining the graphic objects, their associated
• .obj Machine code translations • .opt Workspace configuration
attributes, and the graphic modes affecting output on a device.. Device Context : •
• .plg Build log file
Windows programs don’t draw directly  on HW, but on a “Device Context”
Windows Program Configurations : ( • Debug : – appends debugging info  –
(DC)  – Abstracts the device it represents  – Like a painter’s canvas  –
produces more and larger files ) / Release : – no debugging info  – optimized for
Specifies drawing attribute settings  • e.g., text color (– Contains drawing objects
size & efficiency)
 • e.g., pens, brushes, bitmaps, fonts  – Must be obtained/released from
Setting the Configuration : ( Click "Build" on Main Menu Choose "Select
Windows
Active Configuration” Choose configuration (“Debug” or “Release”) •
4 4
Default is “Debug” ) programs must contain two classes derived from hierarchy: (– An application class
Create a Win32 App w/ Dev Studio : ( • Startup : (– click ‘Start’ on Task Bar / – derived from CWinApp • Defines the application 2. • provides the message loop (–
‘Programs | Microsoft Visual Studio | Microsoft Visual C++’) A window class usually derived from  CFrameWnd : • Defines the
• Creating Project (– ‘File | New’ from menu / – ‘Projects’ Tab (if not chosen) / – application's main window 3. These & other MFC classes brought in by using
‘Win32 Application’ / – Name the project (e.g. winapp1) / – ‘OK’ #include <Afxwin.h>
“Win32 Application, Step 1 of 1” Window : – Select “An Empty Project” / • Click Message Processing under MFC (.1. Like API programs, 2. MFC programs must
“Finish” • “New Project Information” Window handle messages from Windows . API mechanism: big switch/case statement
• Click “OK” / • Inserting source files into project: ( – Open new C++ file, type or . 3. MFC mechanism: "message maps" (lookup tables) 4. . Table entries: –
copy/paste the code into the program / “File | New | Files tab | C++ Source” / Make (Message number  – Pointer to a derived class member message-processing
sure “Add to Project is checked” / Enter a file name (e.g., winapp1) / Type or function • These are members of CWnd )
paste in the resulting Edit window / – To see/modify a file added to project: /click Message Mapping : . Programs must: (– Declare message-processing functions
FileView tab in Workspace Window /click on file name in FileView window • e.g., OnWhatever() for WM_WHATEVER message  – Map them to messages
• Building Project: (– ‘Build | Build winapp1” from menu / • Shortcut key: F7 / – app is going to respond to (• Mapping by "message-mapping macros” • Bind a
Project will be compiled/linked / – Messages will appear in Output Window message to a handler function • e.g., ON_WM_WHATEVER() ) . Most MFC
• Running Program: (– ‘Build | Execute winapp1” / • Shortcut key: Ctrl-F5, or application windows use a window procedure, WndProc(), supplied by the library
click exclamation point . Message maps enable library window procedure to find the functin corresponding
• Cleanup: (– Copy source, header, resource files to disk /– Copy .exe from to the current msg.
project's Debug directory /– delete project directory from hard drive ) STEPS IN WRITING A SIMPLE MFC PRG (App/Window Approach)
Exiting Developer Studio: (– ‘File | Exit’ from menu ) DECLARATIONS (.h) 1. Declare a window class derived from
MFC Windows Programming (App/Window Approach) : . The Microsoft CFrameWnd (e.g., CMainWin)- ( . Class Members: – The constructor – Message-
Foundation Class (MFC) Library (. A Hierarchy of C++ classes designed processing function declarations : (• e.g., void OnChar ()
to facilitate Windows programming  . An alternative to using Win32 – DECLARE_MESSAGE_MAP() macro: • Allows windows based on this class
API functions . A Visual C++ Windows application can use either Win32 API, to respond to messages • Declares that a msg map will be used to map messages to
MFC, or both  Microsoft Foundation Classes : . About 200 MFC classes functions • Should be last class member declared
(versus 2000+ API functions)  . Provide a framework upon which to build 2. Declare an application class derived from CWinApp (e.g., CApp)-
Windows applications . Encapsulate most of the Win32 API in a set of logically . Must override CWinApp's InitInstance()
organized classes virtual function: – Called each time a new instance of application is started
characteristics of MFC: . 1. Convenience of reusable code: (– Many tasks – i.e., when an object of this class is instantiated – Purpose is for application to
common to all Windows apps are provided by MFC  – Our programs can inherit initialize itself  – Perfect place to put code that does stuff that has to be done
and modify this functionality as needed  – We don't need to recreate these tasks each time program starts
 – MFC handles many clerical details in Windows programs ) IMPLEMENTATION (.CPP) 1. Define constructor for class derived from
2. Produce smaller executables: ( – Typically 1/3 the size of their API CFrameWnd (CMainWin) . Should call member function Create() to create the
counterparts ) window . Does what CreateWindow() does in API  2. Define message map class
. 3. Can lead to faster program development: – But there's a steep learning curve-– derived frm CFrameWnd (CMainWin)-BEGIN_MESSAGE_MAP(ownr, base)
Especially for newcomers to object-oriented programming List of "message macros"[e.g., ON_WM_CHAR() ]  END_MESSAGE_MAP()
. 4. MFC Programs must be written in C++ and require the use of classes 3. Define (implement) message-processing functions declared in declarations (1)
. Programmer must have good grasp of: (– How classes are declared, instantiated, above  4. Define (implement) InitInstance() overriding function-(. Done in class
and used  – Encapsulation – Inheritance – Polymorphism--virtual functions derived from CWinApp (CApp):  – Should have initialization code for each
Important MFC Classes (. CObject: At top of hierarchy ("Mother of all classes") new app instance:  • Create a CMainWin object .pointer to program's main
. Provides features like: – Serialization (• Streaming object’s persistent data to or window  – (Used to refer to the window, like hWnd in API programs)  •
from a storage medium (disk reading/writing)  – Diagnostic & Debugging Invoke object'sShowWindow() memberfunctionInvoke object's
support )  . All its functionality is inherited by any classes derived from it UpdateWindow () member function • Must return non-zero to indicate success
Important Derived Classes-(. 1. CFile: Support for file operations . 2. CArchive:  – [MFC's implementation of WinMain() calls this function]
Works with CFile to facilitate serialization and file I/O .3.CDC: Encapsulates the 5. Create an instance of the app class (CApp) . Causes AfxWinMain() to
device context (Graphical Drawing) . 4. CGdiObject: Base class for various execute
drawing objects (brushes, pens, fonts, etc.) . 5.CMenu: Encapsulates menu – It's now part of MFC [WINMAIN.CPP] . AfxWinMain() does the following:
mngmnt 6. CCmdTarget: Encapsulates message passing process & is parent of: – – Calls AfxWinInit()-• which calls AfxRegisterClass() to register window class
CWnd: Encapsulates many important windows functions and data members (– – Calls CApp::InitInstance() [virtual function overridden in 4 above]-• which
Example: m_hWnd stores the window’s handle  – Base class all windows are creates, shows, and updates the window – Calls CWinApp::Run()-• which calls
derived from  – Most common: )• CFrameWindow: Can contain other windows CWinThread::PumpMessage()-• which contains the GetMessage() loop .
– ("normal" kind of window we've used) • CView : Encapsulates process of After WinApp::Run() returns: – (i.e., when the WM_QUIT message is received)
dsplaying and interacting with data • CDialog: Encapsulates dialog boxes . . AfxWinTerm() is called-– which cleans up and exits
CCmdTarget also parent of: – CWinThread: Defines a thread of execution & is Menus :Windows provides support for complex menus— (Popup menus Menu
parent of: • CWinApp: Most important class dealt with in MFC applications: ( bars that are graphics images Enabled/disabled/grayed-out menu items 
• Encapsulates an MFC application • Controls following aspects of Windows Checked/unchecked menu items Menu items with associated bitmaps Menu
programs: – Startup, initialization, execution, shutdown – An application items that change dynamically as program runs Good for pgms that operate in
should have one CWinApp object – When instantiated, application begins to run more than one state Or to support beginner/advanced versions of menu
– CDocument (• Encapsulates the data associated with a program ) Creating Menus : Can write source .RC resource script file containing menu
MFC Classes and Functions : definition  l Or use Developer Studio's menu editor to create menu visually
Primary task in writing MFC program--to create classes (. Most will be derived Simple Menu Syntax— MenuName MENU  BEGIN  /* menu definition
from MFC library classes  . MFC Class Member Functions—(Most functions goes here */  END
called by an application will be members of an MFC class (. Examples: Menu Syntax : MenuName: string used to find menu data in program resources
ShowWindow()--a member of CWnd class  . TextOut()--a member of CDC  Menu Items – Go between BEGIN and END  – Can only be MENUITEM or
LoadBitmap()--a member of CBitmap ) . Apps can also call API functions directly POPUP  Menu Item Syntax— MENUITEM string, MenuID options or
 – Use Global Scope Resolution Operator, for example: – MENUITEM SEPARATOR  Latter Causes horizontal line between previous
::UpdateWindow(hWnd); . Usually more convenient to use MFC member and following menu items
functions Menu Item Syntax MENUITEM string,   MenuID, Option  – String: Menu
MFC Global Functions-. Not members of any MFC class (. Begin with Afx prefix item's characters enclosed in " ”  – MenuID: Number passed as
(Application FrameworKS)  . Independent of or span MFC class hierarchy LOWORD(wParam) with WM_COMMAND msg  • Usually given a constant
. Example: (AfxMessageBox()  – Message boxes are predefined windows name  –Option: (• Appearance: ENABLED, GRAYED, or INACTIVE • Check
– Can be activated independently from the rest of an application State: CHECKED, UNCHECKED )  – Refers to check mark next to menu item
Some Important Global Functions AfxAbort() -- uconditionally terminate an Changing Menu Item Status
app Popup menus – Used when number of menu items gets too big  – Can have
. AfxBeginThread() -- Create & run a new thread . AfxGetApp() -- Returns a nested popups (up to 8 levels) Popup syntax – POPUP string options -> – string: (•
pointer to the application object . AfxGetMainWnd() -- Returns a pointer to Gives popup title--what will appear on menu bar • No ID needed since popup titles
application’s main window . AfxGetInstanceHandle() -- Returns handle to not selectable & don't generate messages – Some options: MENUBARBREAK
applications’s current instance . AfxRegisterWndClass() -- Register a custom MENUBREAK
WNDCLASS for an MFC app Menu Resource : None (since menu created dynamically in program)
A Minimal MFC Program (App/Window Approach) : 1.. Simplest MFC But still must assign constant values to menu item names (IDM_*)
5 5
Done in the menu2.h  Must be included along with resource.h Inserts code into appropriate places in program (. Code then can then be
Constants : ARROWCURSOR, GLUECURSOR, & CUTCURSOR Customized by hand . Can be used to create new classes or derive classes from
Cursors: – ID="CUTCURSOR", filename: cutcur.cur – ID="GLUECUR", MFC base classes
filename: gluecur .cur) – Create/insert into project with Cursor Editors . Add new member variables/functions to classes )
Bitmaps: – ID="CUTBMP", filename: cutbmp.bmp – ID="PASTEBMP", SKETCH Application :. Example of Using AppWizard and ClassWizard
filename: pastebmp.bmp – ID="ARROWBMP", filename: arrowbmp.bmp . User can use mouse as a drawing pencil Left mouse button down: – lines in
– Use Bitmap Editor to create bitmap resources – Same way as Cursor Editor is window follow mouse motion . Left mouse button up: – sketching stops
used . User clicks "Clear" menu item – window client area is erased . Sketch data
Single Versus Multiple Document Applications (points) won't be saved (– So leave document (CSketchDoc) class created by
 The single doct interface (SDI)  multiple document interfaces (MDIs) AppWizard alone ). Base functionality of application (CSketchApp) and frame
 similar to MDI but is designed  several doc within the same app window (CMainFrame) classes are adequate – Leave them alone . Use
for simpler applications  Windows Software Development Kit ClassWizard to add sketching to CView class
 work with only one document (SDK) provides for MDI Sketching Requirements :(. If left mouse button is down: – Each time mouse
and one view at any givn time  use the document view architecture prvded moves: • Get a DC / • Create a pen of drawing color / • Select pen into DC /• Move
 use the document view by MFC & addtinl lvl of fnctinlty to deal to old point / • Draw a line to the new point /• Make current point the old point /•
architecture provided by MFC with multiple docs and views Select pen out of DC )
Variables(. BOOLEAN m_butdn . CPoint m_pt, m_ptold . COLORREF
Document/View Approach : (. App/Window approach creates application and
m_color . CDC* pDC
window objects  . Mirrors Win32 API program organization . Main
Steps in Preparing SKETCH . 1. File / New / MFC AppWizard (exe) – Enter
difference--MFC automates & masks details . But data & rendering of data are
name: Sketch – Step 1: Choose “Single Document” (SDI App) – Take
intertwined . Frequently, data members exist in window class :(– Example in
defaults for Steps 2-6 . 2. Build App --> Full-fledged SDI App with empty
MSG1.CPP: Output string & position both defined in window-based class (•
window and no functionality . 3. Add member variables to CSketchView – Can
Output string is data • Position is user defined ) . Conceptually data is different
do manually in .h file . 3. Easier to: (– Select ClassView tab and expand (+) • Note
from
member functions & variables – Right click on CSketchView • Choose “Add
rendering of data  . In an App/Window they are mixed  together in same
member variable” • Type: CPoint • Name: m_pt • Access: Public (default) –
window class  . Frequently need to have different views of same data – (e.g.,
Repeat for: • CPoint m_ptold • BOOL m_butdn • COLORREF m_color • CDC*
displaying data in a window or on a printer) . So it would be good to separate
pDC . . 4. Use ClassWizard (Icon or Ctrl-w) to set up message map and handler
data
function – Message Maps tab – Class name: CSketchView
and data presentation
Repeat process for WM_LBUTTONUP handler – Scroll to WM_LBUTTONUP –
Doc/View Achieves Separation :. Encapsulates data in a CDocument class
Click: Add Function, Edit Code: – Enter: m_butdn = FALSE; . Repeat for
object . Encapsulates data display mechanism data in a CView class object
WM_MOUSEMOVE – Scroll to WM_MOUSEMOVE – Click: Add Function,
. Classes derived from CDocument – Should handle anything affecting an
Edit Code: if (m_butdn) { pDC = GetDC(); m_pt = point; CPen newPen
application's data . Classes derived from CView (– Should handle display of
(PS_SOLID, 1, m_color); CPen* pPenOld = pDC->SelectObject (&newPen);
data and user interactions with that display Other Classes still Needed . Still need
pDC->MoveTo (m_ptold); pDC->LineTo (m_pt); m_ptold = m_pt; pDC-
to create CFrameWnd and CWinApp classes . But their roles are reduced
>SelectObject (pPenOld);
Documents : . Document (– Contain any forms of data associated with the
} . 5. Initialize variables in CSketchView constructor – Double click on
application (pure data)  – Not limited to text  – Could be anything  • game
CSketchView constructor (Classview) – After “TODO…”, Add code: m_butdn =
data, graphical data, etc.
FALSE; m_pt = m_ptold = CPoint(0,0); m_color = RGB(0,0,0); . 6. Build Project
Document Interfaces . Single Document interface (SDI) application – Program
and Run
that deals with one document at a time – All our programs to date have been SDI
Menus and Command Messages . User clicks on menu item . WM_COMMAND
apps . Multiple Document Interface (MDI) application – Program organized to
message sent . IDM_XXX identifies which menu item . No predefined handlers
handle multiple documents simultaneously – Multiple open documents can be
. So message mapping macro is different . ON_COMMAND(IDM_XXX, OnXxx)
of same or different types – Example of an MDI application: Microsoft Word
– OnXxx() is the handler function – Must be declared in .h file and defined in .cpp
Views : . A rendering of a document; a physical representation of the data
file – Object ID: CSketchView highlighted – Messages: • Scroll to
. Provides mechanism for displaying data stored in a document . Defines how
M_LBUTTONDOWN • Click: Add Function, Edit Code: – After “TODO…” enter
data is to be displayed in a window . Defines how the user can interact with it
following code: m_butdn = TRUE; m_ptold = point;
Frame Window : . Window in which a view of a document is displayed
Adding Color and Clear Menu Items to SKETCH App . 1. Resource View
. A document can have multiple views associated with it – different ways of
(Sketch resources) – Double click menu – Double click IDR_MAINFRAME menu
looking at the same data . But a view has only one document associated with it
– Add: “Drawing Color” popup menu item with items: • IDM_RED: “Red” •
MFC Template Class Object :. Handles coordination between documents,
IDM_BLUE: “Blue” • IDM_GREEN: “Green” • IDM_BLACK: “Black” •
views, and frame windows . In general: – Application object creates a
IDM_CLEAR: “Clear Screen” . 2. Add menu item command handler functions
template... – which coordinates display of document's data… – in a view…
(message map) – ClassWizard (Ctrl-w or icon) • Class name: CSketchView
– inside a frame window Template/Document/View/Window
• ObjectID: Select IDM_BLACK • Messages: Select COMMAND
Serialization:Provides for storage/retrieval of document data Usually to/from a
• AddFunction / OK / Edit Code • After “TODO…” enter ff. Code:
diskfile CDocument class has serialization built into itSo in
m_color = RGB(0,0,0); Repeat for IDM_BLUE, Code: m_color = RGB(0,0,255);
DOCUMENT/VIEW apps, saving/storing data is straightforward
Repeat for IDM_GREEN, Code: m_color = RGB(0,255,0); Repeat for IDM_RED,
Dynamic Creation: In Doc/View approach, objects are dynamic . Doc/View
Code: m_color = RGB(255,0,0); Repeat for IDM_CLEAR, Code: Invalidate();
program is run – Its frame window, document, and view are created dynamically
Bitmaps, Animation, Timers, DirectX
– Doc/View objects synthesized from file data – Need to be created at load
Bitmap: An Off-screen Canvas Rectangular image, can be created with almost
time – To allow for dynamic creation, use dynamic creation macros • in
any paint program Data structure that stores a matrix of pixel values in memory
classes derived from CFrameWnd, CDocument, and CView)
Pixel value stored determines color of pixel  Windows supports 4-bit, 8-bit
Dynamic Creation Macros : DECLARE_DYNCREATE(class_name) – in
(indirect) and 16 or 24-bit (direct) pixel values  Can be stored as .bmp file (static
declaration(.hfile)IMPLEMENT_DYNCREATE(class_name, parent_class_name)
resource data) Can be edited; can save any picture Takes up lots of space (no
 (in .cpp file) . After IMPLEMENT_DYNCREATE() macro is invoked: (–
compression) A GDI object, must be selected into a DC to be used Think of as
Class is enabled for dynamic creation – Now a template can be created
the canvas of a DC upon which drawing takes place Must be compatible with a
Document/View Programs :. Almost always have at least four classes derived
video display or printer  Can be manipulated invisibly and apart from physical
from: (– CFrameWnd – Cdocument – Cview – CWinApp ) . Usually put
display device  Fast transfer to/from physical device ==> flicker free animation
into separate declaration (.h) and implementation (.cpp) files . Because of
Does not store info on drawing commands
template and dynamic creation, there’s lots of initialization . Could be done by
Using Device Dependent Bitmaps :A. Create and save bitmap using a paint editor
hand, but nobody does it that way
--> image.bmp file Add to prg's resource script file – e.g.: IDB_IMG BITMAP
AppWizard : Tool that generates a Doc/View MFC prg framework automatically
image.bmp – easier to: “Insert | Resource | Bitmap | Import” B. Instantiate a
(. Can be built on and customized by programmer . Fast, efficient way of
CBitmap object CBitmap bmp1; C. Load it from the pgm's resources:
producing Windows Apps . Performs required initialization automatically .
bmp1.LoadBitmap(IDB_IMG); D. Display the bitmap 0. Get a ptr to the screen
Creates functional CFrameWnd, CView, CDocument, CWinApp classes .
DC (as usual), pDC 1. Create a memory device context compatible with the
After AppWizard does it's thing: (– Application can be built and run – Full-fledged
screen DC CDC dcMem;  dcMem.CreateCompatibleDC(pDC); 2. Select
window with all common menu items, tools, etc.
bitmap into the memory DC CBitmap* pbmpold = cMem.SelectObject(&bmp1);
ClassWizard :. Message handling in a framework-based MFC application
3. Copy bitmap from memory DC to device DC using BitBlt() or StretchBlt()
facilitated by using ClassWizard . A tool that connects resources & ser-
4. Select bitmap out of memory DC
generated
A Memory DC : Like a DC for a physical device, but not tied to device Used to
events to program response code (Writes C++ skeleton routines to handle messages
6 6
access a bitmap Bitmap must be selected into a memory DC before Child Window Controls : Windows created by a parent window l An app uses
displayable on physical device  CreateCompatibleDC(pDC) --> memory DC them in conjunction with parent  Normally used for simple I/O tasks  Let user
with same attributes as device DC  SelectObject() selects bitmap into DC (– choose commands, view status, view/edit text, etc.  Properties, appearance,
Subsequent copying from memory DC is fast since data sequence is same as on the behavior determined by predefined class definitions – But behavior can be
device customized – Easy to set them up as common Windows objects • buttons, scroll
Bit Block Transfer in WindowspDC->BitBlt (x, y, w, h, &dcMem, xsrc, ysrc, bars, etc.  Allow user to display/select info in standard ways l Windows
dwRop)–Copies pixels from bitmap in source DC(dcMem) to destination DC Environment does most of work in: – painting/updating a Control's screen area
(pDC)–x,y: upper left hand corner of destinationrectangle–w,h: width, height of – determining what user is doing  Can do the "dirty work" for the main window
rectangle to be copied–xsrc, ysrc -- upper left hand corner of sourcebitmap–dwRop Often used as input devices for parent window Are the "working components"
-- raster operation for copy of dialog boxes  Windows OS contains each control's WinProc – so messages to
Raster Ops How source pixel colors combine with current pixel colors  Boolean controls are processed in predefined way  Parent window communicates with
logic combinations (AND, NOT, OR, XOR, etc.) – Currently-selected brush controls by sending/receiving messages  Windows Environment automatically
pattern also can be combined – So 256 different possible combinations – 15 are repaints a Control upon exposure Example: WordPad ("File"|"Open") – Conatains
named l Useful for special effects Raster Ops (first time) most of “classic” controls – There are 20 other predefined "Common Controls”
Animated Graphics : Creating a moving picture – Give illusion of motion by – Most first appeared in Windows 95 – Some came with Internet Explorer
continual draw/erase/redraw – If done fast, eye perceives moving image In a – Implemented in Comctl32.dll Six “Classic” Control Types  Go back to first
single-user (DOS) application, we could do the following: versions of Windows  Implemented in User.exe Type Window Class MFC Class
Do Forever{ /* compute new location of object */ /* erase old object image */ ----------------------------------------------------
/* draw object at new location */ } Static Text “STATIC” CStatic Button “BUTTON” CButton Edit Control
In Windows, other programs can’t run while this loop is executing  Need to keep “EDIT” CEdit List Box “LISTBOX” CListBox Combo Box “COMBOBOX”
giving control back to Windows so other programs can operate Two methods: CComboBox Scroll Bar “SCROLLBAR” CScrollBar l All are windows
– Use PeekMessage() Loop (for Win32 API) • Override OnIdle() (for MFC) The Common Controls TYPE WINDOW CLASS MFC CLASS
– Use a Windows Timer ---------------------------------------------------
PeekMessage() vs. GetMessage() : GetMessage() only returns control if a Animation “SysAnimate32” CAnimateCtrl ComboBoxEx “ComboBoxEx32”
message is waiting for calling programPeekMessage() returns (with 0 value) if CComboBoxEx Date-Time “SysDateTimePick32” CDateTimeCtrl Header
no “SysHeader” CHeaderCtrl Hotkey “msctls_hotkey32” CHotKeyCtrl Image
active messages are in the system PeekMessage() loop can take action (redraw List N/A CImageList IP Address “SysIPAdress32” CIPAddressCtrl List View
image) if PeekMessage() returns 0 PeekMessage() doesn't return zero for “SysListView32” CListCtrl Month Calendar “SysMonthCal32” CMonthCalCtrl
WM_QUIT (like GetMessage()) – So App must explicitly check for a WM_QUIT Progress “msctls_progress32” CProgressCtrl Property Sheet N/A
message to exit the program CPropertySheet ReBar “ReBarWindows32” CReBarCtrl
PeekMessage(lpMsg , hWnd, uFilterFirst, uFilterLast, wRemove); The first 4 MFC CSplitterWnd class, which is used to provide window splits and to manage
parameters are same as GetMessage. Last one: specifies whether message should the resizing of other Pane windows.
be removed from the Queue Splitter Styles A CSplitterWnd supports two styles “static splitters,” the panes
PeekMessage() message loop while (TRUE) // Do forever {   if (PeekMessage are created when the splitter window is created, and the order and number of panes
(&msg, NULL, 0, 0, PM_REMOVE) ) { // non-zero means we must handle msg     never change. Splitter bars are used to resize the different panes, and the different
if (msg.message == WM_QUIT) return msg.wParam; else{ TranslateMessage panes are usually of different view classes.
(&msg);         DispatchMessage (&msg); } } else // { zero (idle); do other stuff - In “Dynamic splitters,” additional panes are created and destroyed as the user
draw next animation frame } } splits and un-splits new views. starts out with a single view, and splitter boxes are
BALL Example Animation App A Win32 API -- (Ball bouncing off walls) provided to initiate splitting. If the view is split in one direction, an additional view
BALL.H – Define menu item constants – Define ball constants: (VELOCITY, object is dynamically created to represent the new pane. If the view is split in two
BALLRAD, MINRAD) BALL.CPP – Global variables: • _dDrawOn: toggle directions (possible with the keyboard interface), then three new views are created
animation on or off • _nXSize,_nYSize: window width, height--to determine if ball to represent the three new panes. When the split is active, the splitter box is drawn
is inside • if window is resized, we need to change these as a splitter bar between the panes. Additional view objects are destroyed when the
WM_SIZE message :Sent anytime window is resized by the user  user removes a split, but the original view (row 0, column 0) remains until the
Vertical/horizontal size of client area – Least significant two bytes = horizontal splitter window itself is destroyed. Microsoft Excel or Microsoft Word are
size in pixels – Most significant two bytes = vertical size  examples of the dynamic splitter style.
Helper function DrawBall() – Draws ball in new position for each new frame – you must specify the maximum number of rows and columns that the splitter will
Called each time PeekMessage() returns 0 manage. For a static splitter, panes must be created to fill all the rows and columns.
MFC OnIdle() Virtual Function:In CWinThread::Run() there is code like:Do For a dynamic splitter, the first pane is automatically created when the
foreverwhile {!::PeekMessage(…)}if (!OnIdle(lIdleCount++) ) CSplitterWnd is created.The maximum number of panes you can specify for
bIdle=FALSE;PumpMessage loopSo a derived app class can override OnIdle()to static splitters is 16 rows by 16 columns. The recommended configurations are: 1
enact its own idle-processingfunctionality row x 2 columns : usually with dissimilar panes 2 rows x 1 column : usually
Parameter lCount: # of times OnIdle() has beencalled since last message was with dissimilar panes 2 rows x 2 columns : usually with similar panes
processed–Framework does its processing when lCount is 0 or 1Return value: The maximum number of panes you can specify for dynamic splitters is 2 rows by
non-zero means OnIdle() will be calledagain if message queue is still emptySo 2 columns. The recommended configurations are: 1 row x 2 columns : for
structure the override as follows:BOOL CMyApp::OnIdle(LONG lCount) columnar data 2 rows x 1 column : for textual or other data2 rows x 2 columns
{ CWinApp::OnIdle(lCount); if (lCount = = 2) // Do Idle processing (i.e., : for grid or table oriented data
next fame of animation) return TRUE }–Note call to base class function so Error Detection and Exception Handling Techniques: Structured Exception
framework can donecessary idle processing first Handling  is a way to handle exceptions within a program. It is a mechanism
Timers -- Another Way to do Windows Animation :An input device that for handling both hardware and software exceptions.
notifies an app when a time interval has elapsed (– Application tells Windows the
An exception is an event (most likely, an error) that occurs while the program is
interval
running. To prevent the program from crashing, the event may be captured,
– Windows sends WM_TIMER message each time interval elapses encoded in
processed, reported, and hopefully handled properly so that the program can
lParam
continue in a workable state.
Using a Timer :Allocate and set a timer with: (SetTimer (hWnd, timerID, interval,
NULL); • Win32 API HWnd::SetTimer (timerID, interval, NULL); • MFC two types: hardware exceptions and software exceptions.
– Interval in milliseconds – Last parameter the address of a “timer procedure” that
will receive the WM_TIMER messages • NULL means msg goes to application’s Hardware exceptions are triggered by the CPU. usually are caused by illegal
queue • I.e., to application’s WndProc() operations such as dividing by zero, floating-point overflow, disk read errors, null
From that point on, timer repeatedly generates WM_TIMER messages and resets pointer accesses, array subscript range errors, and out-of-bounds memory
itself each time it times out – Could be used to signal drawing the next frame of an addressing.
animation!!!  WM_TIMER handler: OnTimer(timerID)  When app is done Software exceptions always result from the operating system or the programs
using a timer, stop timer messages and remove it with: KillTimer(timerID); themselves, such as array subscript range errors, null pointer accesses, or invalid
Sprites:Little bitmaps that move on screen Frequently used in game programs parameter specified.
. Could restore background and just BitBlt() the sprite over it  But there's a __try Identifies a guarded body of code
problem – sprite consists of desired image enclosed in a rectangle – so when _except Identifies an exception handler
blitting is done, background color inside enclosing rectangle will wipe out the __finally Identifies a termination handler
background area on destination bitmap – moving object will have a "halo" around Structured Exception Handling Functions
it – will also always have a rectangular shape The following functions are used in SEH:
7 7
AbnormalTermination  GetExceptionCode GetExceptionInformation Apply Code Changes : If program changes were made while debugging the
RaiseException SetUnhandledExceptionFilter UnhandledExceptionFilter program, this option allows the code to be recompiled. The shortcut key is
MFC Error and Exception Handling:The macros are TRY, CATCH, and THROW. Alt+F10. This is a new feature in Visual C++ 6.0.
In contrast, the C++ exception keyword equivalents are try, catch, and throw.
Break Execution : Go: Run to Cursor  Step IntoStep OverStep OutStop
Here is a list of the MFC exception macros: AND_CATCH Debugging: Debugger Windows : The DevStudio IDE comes with quite a few
AND_CATCH_ALL CATCH CATCH_ALL END_CATCH
useful windows to assist in debugging. A few of the important ones are
END_CATCH_ALL THROW THROW_LAST TRY
TRY { } CATCH() { } AND_CATCH() { } END_CATCH covered here.
and Variables Window :The Variables window provides a quick-and-easy view to
TRY{}CATCH_ALL(){ THROW_LAST();}END_CATCH_ALL variables involved in the debugged program.
Predefined Exceptions for MFC
ArchiveException—A serialization exception condition. These are constructed and There are three window tabs:Auto— Displays variables on the current line of code
thrown from inside CArchive member functions. CDAOException—An and the previous statement. Also displays return values from functions.Locals—
exception condition from the MFC database classes based on data access objects Displays the local variables of the function that currently is being debugged.This
(DAOs).  CDBException—An exception condition coming from the database — Displays the object pointed to by this. The routine currently at the clientside
classes. CFileException—A file-related exception condition. These objects debugger is the this object.
are constructed and thrown in CFile member functions and in member functions of Watch Window : You can use the Watch window to specify local or global
derived classes. CInternetException—An exception condition coming from the variables that are to be monitored while the program is being debugged. The
Internet classes. CMemoryException—A memory exception that signifies an Watch window, like the Variables window, can change the values of local
out-of-memory condition. Memory exceptions are thrown variables.
newCNotSupportedException—An exception that results from a request of a
feature not supported. COleDispatchException—Handles exceptions specific to QuickWatch Window : You use the QuickWatch window to quickly find the
the OLE IDispatch interface. COleException—An exception condition from an values of SQL variables and parameters.
OLE operation. CResourceException—Generated when a resource cannot be Registers Window : The Registers window displays the contents of the CPU
found or allocated. CUserException—Thrown to stop an end-user operation in
Registers, floating-point stack, and flags. You can use the Registers window to
the same manner as covered in the earlier section on C++ exception handling,
using the throw/catch exception mechanism. add Registers to the Watch window. You also can change Register and flag
Using CDaoException values during a debug session.

The CDaoException is used for DAO-based database access. Call Stack Window : The Call Stack window displays the stack of function calls
that are still active. Whenever a function is called, it is pushed onto the stack.
Debugging ASSERT and TRACE macros, the AssertValid and Dump member Whenever a function returns, it is popped off the stack.
functions, the CMemoryState
to detect bugs throughout development, Disassembly Window:The Disassembly window displays code instructions in
Techniques for Debugging Your MFC Application disassembled form. You can set the breakpoint on any instruction and step
Make sure the debugger is positioned onscreen so that it doesn't overlap the through the code just like regular code.
program. Otherwise, the debugger might obscure the program being debugged.
Memory WindowYou use the Memory window to view large amounts of data
From the TRACER application, select the Multiple Application Debugging
option when debugging an application and one or more DLLs. The Multiple that are not fully displayed in the Watch and Variables windows. Such data
Application Debugger option also is useful in tracking the order of events. includes buffers, large strings, and other large data objects.

DebugBreak(); AfxDebugBreak(); AfxDump :AfxDump is a pointer to an Using Spy++:Spy++ is a Win32-based utility that gives a graphical view of the
object derived from the CObject class. system's processes, threads, windows, and window messages. You can view the
The TRACER.EXE Utility :Included on the Tools menu of Developer Studio is the parent-child window relationships, as well as the flag settings and window
MFC Tracer application. positions.
Tree View:The Tree view displays a tree of all windows and controls in the
You can set the following options with TRACER: Database TracingEnable
TracingInternet Client TracingMain Message DispatchMain Message system. One of the tools of this view is the Window Finder tool. You can use
PumpMultiple Application DebuggingOLE TracingWM_COMMAND this tool to locate disabled child windows and discern which window to
Dispatch highlight if there are many child windows that overlap each other.
 MFC Diagnostic Features:( Trace Output— Check Program Messages View :The Messages view views the message stream associated with
Assumptions .ASSERT_VALIDMacro— Track Memory allocations Detect each window. Message views also can capture messages from a thread or
Memory Leaks— Use Object Dumps— )
The TRACE Macro:The TRACE macro is active only in the debug version of process. This view is helpful when you want to look at messages sent to
windows owned by a specific thread or process. The initialization messages
MFC.
can be captured this way.
The ASSERT Macro: You use the ASSERT macro to check assumptions made by
Processes View : You use the Processes view to examine a specific system
the functions in the program.
process. Processes are identified by module names, or they are designated as
This example shows how you can use the ASSERT clause:int FunctionResult = "system processes."
AnyFunction(x);ASSERT (FunctionResult < 0);
The ASSERT_VALID Macro:You use the ASSERT_VALID macro to test the Threads View : The Threads view displays all the threads with associated
validity of an object's internal state. ASSERT_VALID calls the AssertValid windows.
member function of the object passed as its argument. You can search for a specific thread by using its module string or thread ID as a
Using DEBUG_NEW to Track Memory Allocation: To assist you in keeping search criterion. To find all threads owned by a module, enter the module name in
track of memory being allocated, the macro DEBUG_NEW is supplied with the Module box, leaving the Thread box blank.
Using Spy++ : Spy++ is a Win32-based utility that gives a graphical view of
the debug version of MFC.
the system's processes, threads, windows, and window messages. You can view
Breakpoints and Single-Stepping : Using breakpoints is an excellent method of the parent-child window relationships, as well as the flag settings and window
debugging. Combined with single-stepping (stepping through the code one line positions.
at a time), this method is very effective at pinpointing exactly where a Tree View : The Tree view displays a tree of all windows and controls in the
problem occurs. system. One of the tools of this view is the Window Finder tool. You can use
You can set a breakpoint at any line of code in the program. After the program is this tool to locate disabled child windows and discern which window to
started, it stops at the line of code that has the breakpoint and does not execute it highlight if there are many child windows that overlap each other.
unless you single step forward or continue running the program.
Threads View:The Threads view displays all the threads with associated windows.
To add a breakpoint, select the line of code in which you want the breakpoint to
appear. Then press F9, or click the hand icon on the Build minibar. A red dot Using the OLE-COM Object Viewer :The OLE-COM Object Viewer is an
appears next to the selected line of code. To remove a breakpoint, press F9 or click application supplied with Visual C++ that displays the COM objects installed
the hand while your cursor is positioned in the line of code.
8 8
on your computer and the interfaces they support. You can use this Object
Viewer to view type libraries, which can be quite interesting as well as helpful
Using the Process Viewer :The Process Viewer lists all the processes currently
running on a computer. You can sort and select these processes to view all the
threads that stem from each selected process.
Performing Remote Debugging : To perform remote debugging, the Remote
Debug Monitor is implemented. The Remote Debug Monitor is a small program
that sits on the target computer, which communicates with the debugger and
controls the execution of the program being debugged.
Troubleshooting : If the development environment can't find the executable,
make sure that you give the correct directories for the correct computers.
PLIST :The PLIST program converts the results from a .PBT file into a
formatted text file.
The syntax for PLIST follows:PLIST [options] inputfile
9 9
VB Long -2,147,483,648 to 2,147,483,647
The integrated Development Environment :IDE is the term used in the Single -3.402823 * 103 to -1.401298 * 10 45 for negative values. 1.401298 *
programming world to describe the interface and environment that we use to create 10-45 to 3.402823 * 10 38 for positive values.
our applications. It is called integrated because we can access virtually all of the Double -1.79 * 10 308 to -4.94 * 10 -324 for negative values 4.94 * 10 -324 to
development tools that we need from one screen called an interface. 1.79 * 10 308 for positive values
The VB IDE is made up of of components (Menu Bar : Tool Bar :Project Date January 1, 100 to December 31, 9999
Explorer :Properties Window :Form layout Window :Toolbox :Form Designer
:Object Browser
Menu Bar :This is bar display the commands that are required to build an
application. The main menu items have sub menu items that can be chosen when Data Type Conversion :Visual Basic functions either to convert a string into an
needed. integer or vice versa and many more conversion functions. A complete listing of
Tool Bar :The toolbar in the menu bar provide quick access to the commonly used all the conversion functions offered by visual basic is elucidated below.
commands. Toolbox :The toolbox contains a set of controls that are used to place Conversion To Function : Boolean Cbool  Byte Cbyte 
on form at design time thereby creating the user interface area. Additional controls Currency Ccur  Date Cdate Decimals Cdec
can be included in the toolbox by using the Components menu item of the Project Double Cdbl  Integer Cint Long Clng Single
menu. A toolbox is represented in Picture (Label / Textbox / CommandButton Cn=sng String Cstr Variant Cvar Error
OptionButton Frame Checkbox Listbox / Combobox VScrollBar HScrollBar CVErr
DriveListBox Timer FileListBox /DirListBox Line Shape Data /ImageOLE Note: A conversion function should always be placed at the right hand side of the
The pointer provides a way to move and resize the control and forms.  Label calculation statement.
display a text that the user cannot modify or interact with.  Frame control serves Procedure: Visual basic programs can be broken into smaller logical components
as a visual and functional container for control. Checkbox display a True/False called procedures. Procedures are useful for condensing repeated operations such
or yes/no option. Textbox is a control used to display message and enter text. as the frequently used calculations, text and controls manipulation etc. The benefits
The Listbox display a list of items from which a user can select one. of using procedures in programming are: It is easier to debug a program with
ComboBox contains a textbox and Listbox. This allows the user to select an procedures, which breaks a program into discrete logical limits. Procedures used in
item from Dropdown Listbox, or to type in a selection in the textbox.  one program can act as building block for other programs with slight modification.
HScrollBar and VScrollBar controls allow the user to select a value within the A procedure can be sub, function or property procedure
specified range of value. -> Timer control executes the timer events at specified Sub Procedure :A sub procedure can be placed in standard, class and form
intervals of time. Dirlistbox allows the user to select the directories and paths, modules. Each time the procedure is called, the statement between Sub and End
which are displayed Shape control use to draw shape on form. Image control Sub are executed. Syntax [private | public ] [ static] Sub Procedure_Name
is used to display icons, bitmaps, metafiles etc OLE control is used to link or [ (arg_list)] [Statements]End Sub : Argument list is separated by commas. Each
embed an object, display and manipulate data from other windows based argument acts like a variable in the procedure. There are two type of sub
applications. Picturebox displays icons/bmp/jpg and metafiles. It displays text procedures namely general procedures and event procedures.
or acts as a visual container for other controls. CommandButton control which Event Procedures :An event procedure is procedure block that contains the
is a part of an option group allows the user to select only one option even if it control’s actual name, an underscore ( _ ), and the event name Syntax
display multiple choices. The FileListBox display a set of files from which user Private sub Form1_Load( ) Statement block End sub //This is event for form1.
can select the desired one. The DriveListBox display the valid disk drives and Execute when load form. General Procedures :A general procedure is declare
allows the user to select one of them. Line control to draw a line on form. when several event procedure perform the same action. It is good programming
Data control enables the user to connect to an existing database and display practice to write common statements in separate procedure and then call them in
information from it. the event procedure
Project Explorer :Docked on the right side of the screen, just under the toolbar, is Function Procedures :Function are like sub procedures, except they return a value
the project Explorer window. It display objects of your project like forms, classes to calling procedure. They are especially useful for taking one or more pieces of
and modules. All the object that make up the application are packed in a project. data, called arguments and performing some tasks with them. Then function return
Properties Window :The properties window is docked under the project explorer value that indicate result of the task.
window. It exposes the various characteristics of selected objects. Form e.g. The following function procedure calculates area of circle of given radius.
Layout :The form layout window use to place the form starting position after you Function Area(a as double) as doubleArea = 3.14 * a^2 End Function
runs it. Control Flow Statements :Control statements are used to control the flow of
Variables, Data Types and Modules : Variable are used for storing values program’s execution. Visual Basic supports control structures such as If
temporarily. Declaring a variable tells Visual basic to reserve space in memory. It -------Then, If -------Then ------Else--End If. Select----Case and Loop structures,
is not must that a variable should be declared before using it. A defined naming such as Do While-------Loop, Do-----Loop while and For…..Next method.
strategy has to be followed while naming a variable. (A variable name must begin If….Then….Else statement :The If… then block is used for conditional
with alphabet letter and should not exceed 255 characters. It must be unique execution of one or more statements. Syntax:
within the same scope. It should not contain any special character like %,&, #, If Condition Then Statements End If //The statement is execute only if the given
@ or $ ) condition is true. The condition is usually a comparison, but it can be any
Syntax :(Dim variable [as type] For e.g Dim str as string Dim I as integer ) expression that evaluates a numeric value
Scope of variables :A variable is scoped to a procedure-level(local) or module- If….Then …. Else Statement : To execute one block of code if condition is false.
level depending on how it is declared. A variable is declared in general declaration Syntax:If Condition Then Statements Else Statements End If
section of a Form, and hence is available to all the procedures. Local variable are Select ……..Case Statement : Select…Case structure is an alternative to If …
recognized only in the procedure in which they declared. They can be declaring Then ….Else If for selectively execute a single block of statement from among
with dim and static keyword. multiple blocks.Syntax Select Case Index Case 0 Statements Case 1 Statements
Local Variable: Local variable is one that is declared inside a procedure. This Case n Statements End Select : Select …. Case statement evaluates an expression
variable is only available to the code inside the procedure and can be declared once at the top of the block where as if…then else structure evaluates different
using dim statement as given below Dim I as integer expressions for each Else If statement.
Static Variables :Static variables are not reinitialized each time visual basic Do While…..Loop statements : The Do While …. Loop is used to execute
invokes a procedure and thus retains or preserves value even when a procedure statements until a certain condition is met. Following do while .. loop counts from
ends. 1 to 100
e.g.Static in as integer Count=1 Do while count < 100 Count = count + 1 Loop
Module Level Variables :Module level variables are available to all the procedure Do…Loop While Statement : The do…..loop While Statement first execute the
in the module. They are declared using Public or private keyword. statements and then test the condition after each execution. The following program
e.g. public nk as integer private st as string declaring a variable with public block is same to first one(like Do While loop) Count = 200 Do Text1.text =
keyword makes it available throughout the application even for the other modules. str(count)Count=count + 1 Loop While count < 300
A variable can have same name with different scope. The program execute the statements between do and loop while structure in any
Data Type: By default Visual Basic variables are of variant data types. The variant case. Then it determines weather the count is less than 300. If so, the program
data type can store numeric, date/time or string data. When a variable is declared, a again execute block until it gets false.
data is supplied for it that determines the kind of data they can store. Do….Loop Until statement : The do….loop until structure execute the
A list of visual basic data types are given below statements until the condition is satisfied. It is an infinite loop if the test fails and to
Type Name Values Range get released from this loop we can use CTRL + BREAK combination or End From
Byte 0 to 255 Run menu. The following code entered in the Form Load() procedure illustrates the
Boolean True or False structure.
Integer -32,768 to 32,767 Private Sub Form_load() Do X$ = INputBox$(“Password ?”) Loop until X$ =
10 10
“Sunil” End Sub If not specified, Sunday is assumed.
The For….Next Loop statement : The for…Next Loop is another way to make firstweekofyear Optional. A constant that specifies the first week of the year.
loops in visual basic Syntax For Var_name = Start_val to End_val [ Step Number] If not specified, the first week is assumed to be the week in which January 1
Statements Next [Var_name] For I = 1 to 100 step 1Text1.text = str(I)Next I occurs.
Exit For and Exit Do Statement : A For…Next Loop Can be terminated by an Dim TheDate As Date ' Declare variables.  Dim Msg  TheDate =
Exit For Statement. Consider the following statement block InputBox("Enter a date")  Msg = "Days from today: " & DateDiff("d", Now,
For I = 1 to 100 Text1.text = str(i)If I= 50 then Exit For End if Next , In this TheDate) MsgBox Msg
example loop is for 1 to 100 but we stop or exit from loop by using exit for DatePart() Returns an integer containing the specified part of the given date 
statement in it. Same we can exit from do loop I = 1 Do while I < 100 Text1.text = DateValue() Convert a string into date format.
str (I) I = I+ 2  If I > 50 then  Exit Do  End If  Loop String Functions : ( StrComp() :Compare two strings Lcase(): Convert the
With ….. End With Statement : When properties are set for objects or methods given string into lower case. Ucase():Convert the given string into Upper case.
are called, a lot of coding is included that acts on the same object. It is easier to Len():Return a length of given string Format():Convert a given string into given
read the body by implementing with With… End With statement. For e.g suppose format. Lset(),Rset() :Justify a string Instr(): Return a variable(long) specifying
we want to set properties for Form then the position of the first occurrence of the string within another. Letf() Return
With form1 .backcolor = qbcolor(2).enabled = True .MaxButton = false .Font = specified number of character from left side of given string Rigth() : Return
“Times” End with In the above coding, the object form get all its properties specified number of character from Right side of given string Trim() Return a
which we set in with block. given string by removing all it’s blank space from left and right side.Mid() Return
Modules : Code in visual basic is stored in the form of modules. The three kinds of a specified number of character from mid of given string. Ltrim()Trim all blanks
modules are Form module, Standard module, and class modules. A simple of left hand side. Rtrim() Trim all blanks of Right hand side.
application may contain a single form and the code resides in that Form module Working with Forms : In visual basic, the form is the container for all the
itself. As the application grows, additional Forms are added and there may be a controls that makes up the user interface. A form may fill entire screen or have
common code be to executed in several Forms. To avoid the duplication of code, a other forms within it. It may be a custom dialog box. When a Visual basic
separate module containing a procedure is created that implements the common application is executing, each window it displays on the Desktop is Form.
code. This is a standard module. Class module is a foundation of the object Setting Form Properties Border Style : None No border is shown.  Fixed
oriented programming in visual basic. New objects can be created by writing code single A single-pixel width border is shown Sizable This is default setting.
in class modules. Each module can contain variable declaration or procedures. Fixed Double A double-pixel width is shown around the form.  Fixed
Array in Visual Basic : A sequence of variables by the same name can be ToolWindow this type of border is use for toolbars.  Sizable Toolwindow Same
referred using array. The individual elements of an array identified using an index. as fixed toolwindow, but border are resizable.
Arrays have upper and lower bounds and elements have to lie within those bounds. Caption : The title for the window is store in the caption property.
Each index number in an array is allocated individual memory space. We can Control Box :This is determine weather the control box, available by clicking the
declare array of type variant, user defined types and object variables. upper left corner /icon of a window. Icon This property specify the icon for the
There are two types of array : Fixed size array: The size of array always remains window in the upper-left corner of the window
the same : Dynamic array: The size of can be changed MousePointer : This property sets the value that indicate the type of mouse
Fixed Size Array : Fixed array can be declared by giving a name with the upper pointer displayed.
limit in the parentheses. The long data type. : e.g dim lengths(10) as Integer MaxButton/MinButton :Set max or min button of window which are present on
In the above illustration, lengths is a name of the array and the number 10 include title bar.
in the parentheses is the upper limit of the array. This create array having 10 Moveable :By setting it false it is possible to prevent the user from moving
elements with index number from 0 to 9. Dim length(1 to 10) as Integer having window.
lower limit 1 to upper index number 10. Dim marks(50,50) it create two MDIChild :This property specifies if this window must be shown within a
dimensional array. Dim marks(1 to 10,1 to 10) it create two dimensional array with multiple document interface (MDI) window.
lower and upper limits. StartUpPosition :Set the starting position of window.
Dynamic array : There will be a situation when the user may not know the exact Displaying Forms :Show Method :The show method is used to display the form
size of the array at design time. Under such situation, a dynamic array can be object. For e.g. to display the form frmcalculator, the following code is written.
initially declared and can add elements when needed instead of declaring the size Frmcalculator.show
of the array at design time. Dim newarray( )  The actual elements can be allocate Using Load Statement :The load statement is used to load a form or control into
using ReDim statement  ReDim newarray( n )  Each time on the executing the memory but does not display it. To load the form frmcalculator, the following code
ReDim statement, the current data of array is lost and the default value is set.  should be enter.
But if we want to change the size of array without lost any previous elements then Hiding and Unloading Forms :Using the Hide Method :The hide method hides
use keyword Preserve ReDim Preserve newarray(20) a form. For e.g., the following code hides the form object frmcalculator
User-Define Data Type : Variable of different data types when combined as a Frmcalculator.Hide
single variable to hold several related information is called user-define data type. Using the Unload Statement :The unload statement removes the form from the
A type statement is used to create new type. User-define type can only be private in display and releases the memory. The following code should be entered to unload
form while in standardmodules can be public or private. e.g.  Private type frmcalculator from memory. Unload frmcalculator
student Name as string Age as integer Per as double  End type  e.g.Creating Setting Run time and design time properties :Many properties can be set at
variables  Dim s1 as student  e.g.  Or creating array  Dim s(10) as student either design time or runtime. At design time, the controls are added to a project,
Accessing members of user-define type : Variable name.member name e.g. their properties set and relevant code is written. To set properties at design time
text1.text = s1.name accessing name of student s1 following steps are followed. Select the control or object whose properties you
Visual Basic Built-in Functions : Many built-in functions are offered by Visual want to set. Activate the property window Scroll to the property you want to
Basic that fall under various categories.  Date function  Format functions set 4. Enter a new setting. At run time properties can change by program’s
String functions code. This is done by  Object.propertyname = value e.g Private Sub
Date Functions : Now Return current system date and time.  Year() Return Form_Load()Form1.backcolor = QBcolor(3) Form1.Caption = “Sample
year number from given date.  Month() Return month number from given date. Application” Form1.WindowStatus = VBNormalForm1.Width =
Day() Return day of given date.  WeekDay() Return week day number from 5000Form1.Height = 5000End Sub
given date.  Hour() Return hour number form given time.  Minute() Return Creating and Using Controls : A control is an object that can be drawn on a
minute from given time Second() return second from given time. Form object to enable or enhance user interaction with an application. Controls
DateAdd() : Return a date to which specific interval has been added.( Syntax: Classification of controls : Visual Basic Controls are broadly classified as
DateAdd(interval,number,Date)  Where interval is “M” ,”D” or “Y” Number standard controls, Active X controls and insert-able objects. Standard controls such
to add in date  Date in which you want to add.  ( e.g. as CommandButton, Label and frame controls are contained inside .EXE file and
DateAdd(“m”,3,”02/14/2002”) it return 06/02/2002 (add 3 month in date)_) are always include in the ToolBox which cannot be removed. ActiveX controls
DateDiff() : Returns a Variant (Long) specifying the number of time intervals exist as separate files with either .VBX or .OCX extension. They include
between two specified dates.  Syntax DateDiff(interval, date1, date2[, specialized controls, few from them given below  MSChart control The
firstdayofweek[, firstweekofyear]]) Communication control 
The DateDiff function syntax has these named arguments: The Animation control TreeView control The Picture clip control SysInfo
Part Description control
interval Required. String expression that is the interval of time you use to Text Box Control : A TextBox control, some times called an edit field or edit
calculate the difference between date1 and date2. control, display information entered time at designtime, entered by the user at run
date1, date2 Required; Variant (Date). Two dates you want to use in the time or assign any value at run time.
calculation. Some Properties of a Text Box : Name This is a name used in program to
firstdayofweek Optional. A constant that specifies the first day of the week. identify the control  MaxLength Set maximum no of characters that can be
11 11
entered in control. MultiLine weather a control can accept multiple lines or not. Pop-Up Menus :A pop-up menu is a floating menu that is displayed over a form
PasswordChar It replace the text of control with given character with. Text independent of the menu bar. Pop-up menus are also called context menus.
to assign text to control at design time. Command Button A command Button Because the items displayed on the pop-up menu depend on where the pointer is
control to begin, interrupt, or end a process. When chosen, a Command Button located when the right mouse button is clicked. Any menu can be displayed as a
appears pushed in and so is sometimes called push button. Properties of a pop-up menu at run time provided it has one menu item. The following code
command button control To display text on a command button control, set its displays the colors menu when the user clicks right mouse button over the form at
caption property.An event can be activated by clicking a command buttonA run time.
button’s background color can be set by setting Backcolor property. Text color Private Sub Form_MouseDown (Button As Integer, Shift As Integer, X As Single,
of a command button can be set using forecolor property. Font can be change Y As Single) If Button = 2 Then PopupMenu cc End If End Sub
using font property. Enabled or disable buttonTooltip text can be set using Making menu control invisible :It run time if user wants to enable and disable to
Tooltip property. A button click event is handled whenever a command button is menu items, it is possible by setting the Enabled property to True or False. When a
clicked. To add a click event handler, double click on button at design time, which menu item is disabled, it is dimmed and cannot be selected. But it is still visible
adds a subroutine like the one given below. and the menu items seen. Mnu_green.Enable = False But if you want to hide menu
Private sub Command1_Click() ..... . . . End Sub item from display set visible property false for it. Mnu_green.Visbile = False
Using option button control :Option button a set of choices from which a user Using Check Marks :In some programs we may require check marks to be placed
can select only one button by Clicking at run time. Assigning the value property in the menu items. To place a check mark in a menu item, the checked property is
to True in code like Option1.Value = True • Using the shortcut keys specified in set to true. The following example code entered in the Form_load( ) procedure
the caption of a label To disable Option button at run time its Enabled property set places a check mark in the menu item Red.  Mnured.checked = True
to False. Menu Control Array: A menu control array is a set of menu items on a menu that
Using Listbox and ComboBox Controls ListBox and ComboBox controls share the name and event procedure. Each menu control array element is identified
present a set of choices that are displayed vertically in a single column. If the by a unique index value, indicated in the Index property box on the menu editor.
number of items exceed the value that can be display, scroll bars will automatically When the member of the menu control array recognizes an event, visual basic
appear on the control. These scroll bars can be scrolled up and down or left to right passes the index property value to the event procedure as additional argument. The
through the list. event procedure must include the code that can check the value of the index
Adding items to a list :It is possible to populate the list at design or at run time. property.
Design Time: To add items to a list at design time, click list in the property box Mouse Events :Visual basic applications respond to various mouse events, which
and then add the items. Press CTRL + ENTER after adding each item. are recognized by most of the controls. The main events are MouseDown,
Run Time: The AddItem method is used to add items to a list at run time. The MouseUp and MouseMove. MouseDown occurs when the user presses any mouse
AddItem method uses the following syntax: Object.AddItem item, Index button and MouseUp occurs when the user releases any mouse button.
The item argument is string that represents the text to add to the list. MouseMove occurs whenever the mouse pointer is moved to a new point on the
The index argument is an integer that indicates where in the list to add the new screen. These events use the arguments button, Shift, X, Y and they contain
item. information about the Mouse’s condition when the button is clicked. The first
Removing Items from a List : The RemoveItem method is used to remove an argument is an integer number called button. The value is 1 if left button is clicked
item from a list. The syntax for this is given below. Object.RemoveItem.index and 2 if right button is clicked. The second argument is an integer called shift. The
Selecting an Item from a list : To access the items in a listbox we use the value of this argument indicates weather the mouse button was clicked
ListIndex and List properties. The list index property sets the index number of the simultaneously with the Shift key or Alt key. The third and fourth arguments X and
currently selected item. The first item in the list having index number 0. ListIndex Y are the coordinates of the mouse location at the mouse button was clicked  e.
return -1 if no item is selected. The list count return total number of items in g. This is program to draw a line on form with the help of mouse.  First method
listbox. the starting points, when you press mouse button down to draw line (MouseDown
Sorting the List : To sort the list set sorted property to True. events) Private Sub Form_MouseDown(Button As Integer, Shift As Integer, X
Using ComboBox :A Combo Box combines the features of Textbox. This control As Single, Y As Single)  Form1.CurrentX = X Form1.CurrentY = Y End
enables the user to select either by typing text into combo box or by selecting an Sub
item from list. There are three types of Combo Box styles that are given below. Second method for drawing a line on current points (Mouse/Move events) 
Dropdown Combo (style 0)  Simple Combo (style 1)  Dropdown list (style 2) Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X As Single,
Using ScrollBar Control : The Scrollbar is a commonly used control, which Y As Single) If Button = 1 Then  Line (Form1.CurrentX, Form1.CurrentY)-
enables the user to select a value by positioning it at the desired location. It (X, Y) End If End Sub
represents a set of values. The min max property represents the minimum and Dragging and dropping : Dragging is a process of clicking the mouse button in a
maximum value. The value property represents its current value. control and moving the mouse while holding down the mouse button. The action of
Managing Menus : Creating and managing menu at Design Time Visual Basic releasing the mouse button after the dragging is called dropping. The following
applications can be enhanced by adding menus to it. It offers a convenient and drag-and –drop properties, events and method are supported in Visual Basic.
consistent way to group commands and easy way for users to access them. The DragMode property enables automatic or manual dragging of a control. DragIcon
menu bar appears appear below the title bar and it may contain one or more menu property specifies the icon that is display when the control is dragged. DragDrop
titles. When a menu title is clicked it displays a set of menu items under that title. event is recognized when a control is dragged onto the object. DragOver event is
Each menu item corresponds to a menu control that is defined in a menu editor and recognized when a control is dragged over the object. Drag method starts or stops
performs a specific action. manual dragging.  All the controls except menus, timer, lines and shapes
Using the Menu Editor : A menu editor can be used to add new commands to the support the above mentioned properties and method. Forms recognize the
existing bars. A menu editor can be added only after opening a project. To display DragDrop and DragOver events but they do not support Drag method and the
a menu editor command is chosen from the Tools menu or menu editor button is properties DragMode and DragIcon. To develop an application to explain drag and
clicked in the tool bar. Writing Code form menu Control Each menu control has drop events we use a image, textbox and command button  Private Sub
click event, which is execute when the menu item is selected or clicked. The Command1_DragOver(Source As Control, X As Single, Y As Single, State As
following code is entered in the code window for green color option of menu. Integer) Dim inf As String info = "NOW DRAGGING " info = info + img.Tag 17
Private sub grn_Click() Form1.backcolor= QBcolor(2)  Grn.Enabled = False  info = info + " OVER THE Exit button"  info = info + " STATE" +
 Blue.Enabled = True Red.Enabled = True  End sub Str(State)  Text1.Text = info End Sub
When the green color is selected by clicking on it, form backcolor will be change Private Sub Form_DragDrop(Source As Control, X As Single, Y As Single) 
into green color and that green option form menu is make disable and to other’s Text1.Text = ""  img.Move X, YEnd Sub Private Sub
enable. Adding a Separator Bar and Shortcut key. : Separator bar is a line that Form_DragOver(Source As Control, X As Single, Y As Single, State As Integer)
separates the menu items, which is mainly useful for obtaining clarity. To add it in Dim inf As String  info = "NOW DRAGGING " info = info + img.Tag 
menu, Right click on the form select menu editor Place the pointer where you want info = info + " OVER THE FORM"  info = info + " STATE" + Str(State) 
to insert separator In the caption TextBox ‘-‘ is typed and give any name Using Text1.Text = info  End Sub
Access and Shortcut keys ::Access keys allow the user to open a menu by In this program when user drag image icon on form or command button related
pressing the Alt key with a letter key. To open the Edit menu message will be display on the screen, and when release the mouse the image will
in all Windows applications, for e.g. you can press Alt-E. .  Access key is be place or move on the current location of mouse pointer.
designed by the programmer and they are marked with an underline character. To File Controls : Usually you use the Common Dialog File Open and File Save As
assign to get file names and file paths from the user, but sometimes that just won’t do. For
Access key to menu item, add & sign before letter. e.g. “&File”.Shortcut e.g. you have a program where you want to let user select files but don’t want to
Keys ::Shortcut keys are similar to access key has a special meaning in menu use dialog boxes, In that and similar cases, you can use the visual basic file
design, but inside a opening menu, they run a command when pressed. To assign a controls: The Drive List Box, Directory List Box and File list Box
shortcut key to a menu command, dropdown the shortcut list in the menu editor Drive List Box: Use this tool to draw a drive list box in a form, you get currently
and select a keystroke. selected drive in a drive list by using its Drive property, and when the user changes
12 12
the drive in the control, a Change event is generated. But File controls always work return the color of a particular pixel.  Line(x1, y1) – (x2, y2), Color Line
with each other. e.g. Here in e.g when the user selects a new drive, we pass that method draw a line from x1,y1 to x2,y2 of given color, x1 ,y1 is a starting point
new drive on ot a directory list box, dir1 using that drive as the new root directory coordinates and x2, y2 is ending points.  Visual Basic provides a much
in Dir1: Sub Drive1_Change() Dir1.Path = Drive1.Drive End Sub simpler way to draw a box.  Line(600,600) – (1000,1000), Qbcolor(4),B B
Using The Directory List Box : The directory list box control displays directories option is used with Line Method to draw a box. A Circle method is used to draw
as a hierarchical set of folders. The important property of the list box is Path a variety of circular and elliptical shapes. To draw a circle Visual Basic required
property, which holds the path of the current directory. When the user changes the the location of the circle’s center and length of its redius. Circle(1400, 1200),
current path, a Change events is generated. For example, when the user makes a 500
change in directory list box, dir1, we can pass the new path to file list box, File1 Multiple Document Interface (MDI) : MDI stand for Multiple Document
Sub Dir1_Change() File.Path = Dir1.Path End Sub Interface. A Multiple Document Interface is used for opening many Windows at
Using The File List Box Control : The file list box control lets you display the the same time. All the document windows are contained in a parent window, which
files in a directory as a list of names. The important properties of the File list box provides a workspace in the application. Visual Basic applications can have only
are Path and FileName properties. In our e.g. we load file select from File List one MDI form, which contains all the child forms. A child form is an ordinary
box to Picture Box and txt file in RichText Box. So when we click on File name Form that has its Child property set True. Child form are display within the internal
following event get execute. Private Sub File1_Click() On Error Resume Next Dim area of MDI form at run time.
fname As String fname = File1.Path + "\" + File1.FileName Text1.Text = fname If Add new MDI form to Project: To add new MDI form, select it from project
LCase(File1.Pattern) = "*.bmp" Or LCase(File1.Pattern) = "*.gif" _ Or menu or right click on project name in Explorer window and select Add, MDI
LCase(File1.Pattern) = "*.ico" Then Picture1.Picture = LoadPicture(fname) ElseIf form.
LCase(File1.Pattern) = "*.txt" Then rtb.FileName = fname End If End Sub To all other forms of your project set MDIChild property True to associate these
Graphics for Application : Visual Basic provides a variety of ways to create and forms with parent form. e.g. In this example we create a MDI form having two
use graphics in an application, which adds styles, interest and visual structure to child form Name Form1 and Form2 after clicking on Load form Option of Form
the interface of an application. Graphic objects such as lines, circles and bitmaps menu, show form1 and on form2 show form2. window use to show list of open
can be displayed in visual basic in a quicker and easier way. The number of times form Steps:
a twip is used by all visual basic movements, sizing and graphical drawing 1 Open New project  Add MDI form from project menu  Add Form
statements is limited to one. A twip is a unit that specifies the dimensions and from project menu  To form1 and Form2 set MDIChild property to True
location of the graphics objects. There are 1440 twips in one inch. Thses Create the menu Form Load Form1 Load Form2 Exit Window Enter
measurements designate the size when printed. following code in MDI form  Private Sub loadfrm1_Click () Form1.Show End
The coordinate system is a two dimensional grid that defines the location on the Sub
form or any other container which is represented as(X, Y). X represents the Private Sub loadfrm2_Click () Form2.Show End Sub
location of a point on the X-axis and Y represents a point on the Y-axis A color is Debugging in Visual Basic : Debugging is a process by which error are identified
represented by long integer and there are four ways of specifying it at run time. and resolved in source code. In visual basic error can occur anywhere during entire
They are specified using RGB function, QBColor function, and using one of the development cycle such as Design time , Compile time , Run Time
intrinsic constants listed in the Object Browser and by entering a color value Design Time Bugs :Errors that occurs in the IDE and before the program is
directly compiled are called design-time bugs. These are the most common ones. These
RGB(255,0,0) return Red color RGB(0,255,0) return Green color RGB(0,0,255) bugs are caused by misuse of some component. The following e.g. shows a
return Red color QBcolor function takes a single number that specifies a Quick function that works as long as a textbox control is passed to it. If any other type of
Base color number from 0 to 15 and returns a long integer that can be used in control (say text box, here, the extra space causes the problem) is passed, it fails to
visual basic color property. Form1.backcolor = QBColor(4) execute and an error is reported this is a design time error, which is display the
Using Graphics Controls : Visual Basic provides three controls to create moment the user navigates to the next statement. Sub settext( ctrl as text box, txt as
graphical applications such as image, Line and shape. These controls are very String) Ctrl.text = Lcase(Trim$(txt) + “ : ” + Date$ End sub
useful at design time. The main advantage of graphics controls is that we can On entering the first statement of the above coding in the general declaration
create an application with less code. section, the following error is report.
Line Control : A line control is a straight-line segment that is drawn at design Compile-time bugs : Compile-time bugs are those that occur when we attempt to
time. The position, length, color and style of the line control can be positioned to create the program executable file (EXE) or run the project. Visual Basic can
customize the look of an application locate compile-time bugs if the Visual Basic application is set up correctly. Visual
Shape Control : A shape control is a Visual element that contains several Basic set the several points to users, which can be change as needed. Compile-time
predefined shapes. In order to view a specified shape, the control is added to the bugs are detected by visual basic automatically when the program is compiled
form by double clicking it. The default shape will be rectangle. The shape property using F5. If the Start With Full Compile option is used, the Compile On Demand
is selected from the properties window, which drops down a list of shapes, from can be turned on, and the developer will not find any bugs until the line of code
which the user can select the desired one. The FillColor, FillStyle properties of the with the bugs is actually executed. Compile errors occur as a result of incorrectly
Shape control can be changed so that desigred color and style can be obtained. constructed code such as Next statement without a corresponding For statement or
Image Control : An image control is a rectangular portion into which picture files programming mistakes that violate the rules of Basic, such as misplace word,
can be loaded. The picture files include bitmap files, icon files and metafiles. missing separator, or type mismatch. Compile errors included syntax errors. These
Adding Pictures: Line control and shape control are used for drawing geometrics include mismatched parentheses or an incorrect number of arguments passed to an
shapes such as lines, circles, squares and so on. For drawing more complex figure intrinsic function.
we can use a picture file. A picture file can be loaded on a form, image control or Runtime bugs : A Visual Basic runtime error is the exception generated by Visual
Picture Control. Basic when it ascertains that the code is about to perform something illegal. An
A picture can be added by the following two ways at design time. :In the illegal function could be something as simple as trying to determine the size of a
properties window of the Form, the Picture property is selected. Visual Basic file that dose not exist or attempting to multiply two numbers, the result of which
displays a dialog box from which a picture file can be selected. Similarly a picture exceeds the storage space that could be contained by the data type. However,
can be loaded in a PictureBox and Image control. A picture can be paste on form using an error handler could prevent this error dialog box from being shown and
or into PictureBox or Image control save the program from crashing. By practices we can also use our knowledge that a
A picture can be added by the following ways at run time. : LoadPicture particular error identified by its error number will be generated to help guide our
function is used to specify the filename and assign the picture to the Picture logic. This sort “inline” error handling is very powerful and can be handled using
property. Picture1.Picture = LoaPicture(“C:\Image\sst.jpg”) : Any picture loaded an error handler that checks for the condition of, say Error 57, and then does
to a form, PictureBox or Image control can be copied to another Form, PictureBox something to avoid the situation. This error can be finally rectified by changing the
or Image control. Set picture1.picture = Image1.Picture : A picture can be copied code suitably. E.g. Consider the following example where we declare two variable
from ClipBoard object : Removing Picture A picture can be removed at run time x and y. try dividing x (assign a value 9) by y (assign 0), assigning the quotient to
using LoadPicture function without arguments. Set image1.picture = LoadPicture(“ another variable z. Private sub Form1_load() Dim x as Integer Dim y as Integer
“) : Moving and Sizing Pictures Dim z as Integer X=9 Y=0 Z=x /y
If a form, PictureBox or an Image control is moved, the picture associated with it End Sub Visual Basic Debugging Tools The best way to keep bugs out is to
also moves automatically. The autosize property of a picture box can be set to True prevent then in the first place. Visual Basic gives a programming several tools,
in order to automatically expand and accommodate a new picture. include IDE options and compile directives, to help achieve this goal.
Using Graphics Methods Every graphics method draws output on a Form, IDE Options : Visual Basic offer several IDE option that can help the user write
PictueBox or to the printer object. The following statement draw a point on the better code. Auto Syntax Check Required Variable Declaration  Auto List
form Members Auto Quick Info Auto data Tips Option Explicit Option
Form1.PSet(500,500): The PSet method draw a point at x, y co-ordinates that is Compare Text Additional settings and debugging aids can be viewed in a dialog
specified by its arguments. box shown in the fig. using the following steps Select Option from Tools Menu
Form1.Cls : Clear all the graphics PixelColor = point(30,40)  Point method Choose the Editor tab in the Option dialog box
13 13
Require Variable declaration: This option explicitly inserts the Option Explicit of c is displayed in the Immediate window using the Debug.print statement.
statement in each new form, module, or class created. A dim, private, public, Using a Breakpoint to selectively Halt Execution :At run time, a breakpoint tells
ReDim or static statement must be used to declare a variable before the value is VB to halt before executing a specific line of code. A breakpoint can be set or
assigned to it. If an undeclared variable is used, an error occurs at compile time. removed at design time or at break mode. To set or remove a breakpoint,The
e.g. Option Explicit  Private sub Form1_Load()Sum = 0End sub insertion point is moved to the line of code where the breakpoint is to be set or
Auto Syntax Check: The Auto Syntax Check option forces Visual Basic to check removed. The Toggle Breakpoint is chosen from the Debug Menu or Toggle
the line of code when the user moves the cursor off the line. e.g. button is chosen in the Toolbar or press shortcut key F9.
Private sub Form1_load() Dim a integer End sub In this program Dim a here Writing Error Handlers Visual Basic has specific built-in ways to handle runtime
required “As” so compiler give a error message when we try to move cursor to errors, called trappable errors. When such an error occurs, you can direct the
next line.Auto Quick Info: The Auto Quick Info in Visual Basic display ant execution of your program to an error handler, which is a section of code written
required or Optional parameters for methods. VB display all possible parameters specifically to deal with errors.
while highlighting the one we are currently entering. Auto Quick Info makes it On Error GoTo Label. : The visual basic On error Goto statement is the
easier to use methods and properties because we no longer have to remember or foundation of handling trappable errors. When you execute an On Error GoTo
look up all the arguments it’s properties and methods. Debugging Tools are Label Statement in your code. Execution is transferred to the code starting at label
designed to help the user with logic and run-time errors. Visual Basic provides if a trappable error has occurred. The code following that label is your error
several buttons in the ToolBar that are helpful for debugging. They are handler. Private Sub Form_Load() Dim a, b, c As Integer On Error GoTo diverror
Breakpoint: Defines a line in the code window where Visual Basic suspends a =10 b =0 c=a/b MsgBox "Value of C =: " & c diverror: MsgBox "Divided by
execution of application Instant Watch: Lists the current value of an expression Zero Error", vbCritical, "Error" End Sub
while the application is in the break-mode. Calls: Presents a dialog box that shows In this example value of b is zero, if don’t trap error then our program is terminate
all procedures that have been called but not yet run completely. with an error, but in this
Stepping Visual Basic provides several built-in methods for controlling the we trap error and give appropriate Message to user.
execution of the program in real time. It is possible to execute the program line by Err : It is a object Contains information about run-time errors. When a run-time
line or procedure by procedure or a combination of the two. These basic debugging error occurs, the properties of the Err object are filled with information that
actions are called Stepping. Because it enables the developer to walk through the uniquely identifies the error and information that can be used to handle it. To
program, examining the variables and logic, stepping is the most powerful generate a run-time error in your code, use the Raise method. Main Properties of
debugging tool offered by Visual Basic. The various debugging commands are Err object Err.Number : Return error number Err.Description : Return error
discussed below. description e.g. you may show this error message in program. MsgBox "Des: " &
Step Into: Execute the next executable line of the code in the application and steps Err.Description & "NUMBER : " & On Error GoTo line# : Besides using a label
into procedures. This enables to check every line of code as it is being executed. to start an error handler, you can refer to an error handler by line number in visual
This option can be accessed from debug menu or by pressing F8. basic, using on error goto line# statement.
Step Over: Execute the next executable line of the code in the application without e.g. 1 Private Sub Form_Load() 2 Dim a, b, c As Integer 3 On Error GoTo 8 4
stepping into procedure. The procedure the user steps over does execute, but a=10 5 b =0 6 c=a/b 7 MsgBox "Value of C =: " & c 8 MsgBox "Divided by Zero
Visual Basic does not walk through the stepped-over procedure line-by-line. Error", vbCritical, "Error" 9 End Sub
Shortcut key is Shift+F8. Using On Error Resume Next : The On Error Resume Next statement provides
Step Out: Moves program execution back to the calling procedure. This is the an easy way to disregard errors, if you want to do so. Once you execute this
functional equivalent of Exit sub or Exit Function. It is simple exits the current statement, execution continues with the next line of code if the current line
procedure without executing any more code in that procedure. generates an error, and the error is disregarded.
Set Next: Enables the user to move program execution to any executable line of On Error GoTo 0 : To turn off error trapping, you can use the On Error GoTo 0
code in the current procedure. While debugging an application, we should clearly statement.
understand which of the three modes such as design time, run time or break mode Err Function: Returns a Variant of subtype Error containing an error number
we are in at a given time. Break mode of an application is viewed by clicking specified by the user. Syntax : CVErr(error number) The required errornumber
CTRL+BREAK at run time. argument is any valid error number. Remarks : Use the CVErr function to create
Using the Debugging Window :Debug window is one of Visual Basic’s window user-defined errors in user-created procedures. For example, if you create a
that allows to run individual commands immediately, by typing in the command function that accepts several arguments and normally returns a string, you can have
and pressing the Enter key. It automatically opens at run time. In break mode, your function evaluate the input arguments to ensure they are within acceptable
the debug window can be used to execute individual line of code, View or change range. If they are not, it is likely your function will not return what you expect. In
values of variables and properties, and view watch expressions. At run time, it this event, CVErr allows you to return an error number that tells you what action
can be used to display data or messages as the programs as the program runs. At to take.
design time, the developer can view the previous output to the Debug window, but Note that implicit conversion of an Error is not allowed. For example, you can't
cannot execute code. The debug window has two part-Watch window and directly assign the return value of CVErr to a variable that is not a Variant.
immediate window. The split bar separates the Debug window into two panes. The However, you can perform an explicit conversion (using CInt, CDbl, and so on) of
upper pane display the Watch Window. The lower pane display the Immediate the value returned by CVErr and assign that to a variable of the appropriate data
Window. type.
Watch Window : Watch pane displays the current watch expressions, which are e.g Sub Test()  Debug.Print CalculateDouble("345.45robert")  End Sub  '
expressions whose values are decided by the user as code is executed. The Watch Define CalculateDouble Function procedure.  Function
pane appears automatically if the watch expressions are defined in the project. At CalculateDouble(Number)
times we want to monitor the value of a variable for a certain state-for example to If IsNumeric(Number) ThenCalculateDouble = Number * 2 ' Return result.
determine weather a flag is set to True or False. Steps to add watch expression  Else  CalculateDouble = CVErr(2001)End If ' number. ' Return a user-
Add watch command is chosen from the Debug menu. The Expression is defined error End Function
entered in the Expression box. If necessary, the scope of the variables is set and Database: Using DAO, RDO, and ADO : You may wonder why there are three
an option button is selected. The OK button is clicked.  different sets of database object in visual basic, the reason is historical. At first, VB
Immediate Window : The immediate pane appears by default the first time the only support DAO, which connected to the Microsoft Jet database engine (the
debug window is opened. From break mode, the code is executed immediately by database engine in MS Access). Then, recognizing that there are other database
entering it in this pane. This window is the right place for the users to modify data types available, Microsoft created the Open database connectivity (ODBC)
or test functions during development. We can enter any valid expression in this standard and supported ODBC with Remote Data Objects in Visual Basic. Finally
window and VB will execute it. If a reference is made to an object outside the For Web to access data over network Microsoft create Active Data Object (ADO)
scope of the current code execution, Visual Basic will generate an error. that allows connections on the same computer, over networks and through the web,
Testing data and procedure in Immediate Pane : While debugging an and is intended to support ODBC. ADO is also called OLE DB, and in fact, it’s
application, Sometimes it may necessary to execute individual procedures, evaluate based on COM programming techniques.
expressions or assign new values to the variables or properties. The Immediate There are two ways to work with DAO, RDO and ADO object sets in VB. The
Pane can be used to accomplish new values to the variables or properties. The first way is working with the special controls that support them. The Data Control,
Immediate Pane can be used to accomplish such tasks. Expressions can be Remote Data Control and ADO data control. You use them to connect to and to
evaluated by printing in Immediate Pane. Some advantages of these facility. The move through database but they don’t display actual data, you bind them to other
data or message can be viewed at run time.  Feedback is displayed in separate Visual Basic controls, and those bound controls handle the display. The second
area, so that it does not interfere with the output that the user is seeing. Since the way is working with the three database object sets directly in code, without
coding is saved as part of the form, these statements needs not be redefined the controls like the data control or DAO data control, and that’s what we’ll do in the
next time we work on the application. e.g. Private sub Form_load( ) Dim a as next chapter.
integer Dim b, c as integer A = 10 B = 6 C = a – b Msgbox “Value of c is “ & C What are Databases? :Nearly all business applications need to store large
Debug.print “ Value of c is :” & c End sub On executing the above code the value volumes of data, organized in a format that simplifies retrieval. This is
14 14
accomplished with a database management system (DBMS), a mechanism for must physically reside either on the client or be implemented on the back-end
manipulating tabular with high-level commands. The database management system within the DBMS in the form of triggers and stored procedures. Both triggers and
hides low-level details, such as how data are store in a database, and frees the procedures are stored as precompiled collections of SQL statements and control-
programmers to concentrate on managing information, rather than on the specifics of-flow statements. In VB, using any of the data controls that provide a graphical
of manipulating files or maintaining links among them. Each individual data entry link to the back-end data source create a two tier client/server relationship.
in a table, such as a student’s name, goes into a field in the table. A collection of Merits of two-tier : The merits of this two-tier model are – data access is
fields together, such as the Name and Grade fields in our table, make up a record. simplified, allowing very rapid development of applications. The GUI is bound
Each record gets its own row in a table, and each column in that row represents a directly to the data source and all the details of data manipulation are handled
different field. A collection of records- that is, row of records where each column automatically. But there is a disadvantage in this, i.e. though the data access is
is a field-become a table. What’s then is a Database? A database is just a simplified, it is less flexible due to which the user will not have complete control
collection of one or more tables. of interactions with the data source.
Evolution of computing Architectures : Let’s us discuss about the evolution of Limitations of Two-Tier model : Not Scalable: Inability of two-tier approach to
client-server architecture for various computing models. In this chapter we discuss grow beyond the physical boundaries of a client and server machine.
about three architectures. Unmanageable: Business rules cannot be encapsulated and deployed centrally
Centralized System Architecture : Companies that needed real computing power because of which sharing common process and reusing work become difficult.
turned to the mainframe computer, which is centralized system architecture. The Poor Performance: The graphical interface binding to the data consumes major
salient most feature of a centralized system is that the only movement of resrces on the client machine, which reslts in poor perfrmance & dissatisfied
marshalling are keystrokes between the client and the host machine. Marshalling is clients.
the process of packing interface elements and sending them across process Three-Tier Client/Server Model: An improved model for client/server
boundaries. Thus in a centralized system, keystrokes are marshalling from the development resulted as an outcome of limited effectiveness of two-tiered
terminal (client) to the host. The centralized system architecture is illustrated in fig. client/server solutions. The three-tier client/server model is based on the ability to
Merits of Centralized System Architecture : Excellent Security Centralized build partitioned applications. Partitioning an application breaks our code into
administration as both application logic and data reside on the same machine De- logical components. The Service Model employed to design this architecture
Merits of Centralized System Architecture : Mainframe computers are very suggests that these components can be logically grouped into three tier. User
expensive to buy, lease, maintain and use. The limitation is that both the services, Business services and Data services. The service and its location are
application and the database live within the same machine process thereby offering given below. Service Location
no way to truly partition the application logic beyond the physical limitations of User Services Client
mainframe. In 1980 personal computers made an entry into the business world Business logic Server
along with which, came the resources like printers, modems and hard-disk storage. Data services Server
The introduction of the local area network(LAN) and the use of file server On developing an application using this model and technique, each component can
architectures soon following the introduction of personal computer. File Server then be placed on a suitable machine that will provide the best performance
Architecture depending on our situation and the current business need. The three-tier logic can
The file server system brought a complete change in implementation of the be extended to any number of tier/services called as Multi-Tier or n-Tier
computer architecture from the mainframe. In this system, the application logic architecture.
now executed on the client workstation instead of the server. These servers also Values of three-tier client/server development :Reuse: The time invested in
provided access to computing resources like printer and large hard disk. The designing and implementing components is not wasted as they can be shared
complete File Server architecture is illustrated in fig. The merit of the file server among applications. Performance: As components can be placed on machines
system is the low cost entry point with flexible arrangement. Computer resources other than the client workstation, load processing can be shifted from a client
can be added or reduced as and when necessary using this system. The drawback machine that may be underpowered to a server with extra horsepower. This offers
of the file server architecture is that all application logic is executed on the client us the best possible methods for each aspect of our application’s execution,
machine. The job of the server is to provide files only to store the data. Though the resulting in better performance. Manageability Encapsulation of applications
application’s file might be located on the server, the application runs in the client services into components allows us to break down large, complex applications into
machine’s memory space using the client’s processor. This results in the client more manageable pieces. Maintenance: centralizing components for reuse has an
machine’s need memory amount of power to run the application.  Taking into added benefit. They become easier to redeploy on making any amendments to keep
account the de-merits of the centralized and file server system architecture, the pace with business needs.
client server architecture made . Data Access Options : Visual Basic provides a variety of options to access remote
Client Server Model : Client server architecture is a process involving a Client/Server databases. They are: Data Access Object (DAO): It communicates
minimum of two independent entities, one is the client and the other is the server. with the data source through the JET database engine. Data Control: It binds data-
The client makes a request to the server and the server services the requests and the aware control to Microsoft Access and other ODBC data sources. ODBCDirect: It
resulting data is sent to the client. In this application, two separate applications allows accessing of ODBC data source through the RDO with ADO objects,
operating independently could work together to complete a task. A well brought bypassing JET database engine. Remote Data Objects (RDO): It provides a
out implementation of this concept is the SQL based Database Management framework for using code to create and manipulate components of a remote ODBC
System. The client server architecture is well illustrated in fig. here, unlike the file database system. Remote Data Control (RDC): It binds the controls to an ODBC
server system, the request that goes to server in not merely a request for file in the remote database. Open Database Connectivity (ODBC): this is an API call
form of disk input/output requested as series of disk blocks. Instead, instructions interface to the open Database Connectivity libraries and drivers to provide data
are communicated to an application running on the server, and the server executes access to Microsoft SQL server and other database that provide an ODBC driver.
those requests and sends a response to the client. The request may take the form of Visual Basic Library for SQL Server (VBSQL): it is an implementation of the
the SQL query submitted to a SQL database engine. The database engine in turn DB library API specifically designed to provide access to SQL Server through a
processes the request and a result set is send to the client. Thus the two visual basic application
independent process work together to accomplish a task and exemplifies the client- Active Data Object (ADO): This is a programming model that eliminates the
server relationship. need to choose from among DAO and RDO and all other data access methods. It is
The most popular client/server applications revolve round the use of DBMS such designed to provide a common bridge between different database, files systems
as Oracle and MS SQL server. These applications are referred to as backend and and e-mail servers.
offer support for storage manipulation and retrieval of business persistent data. Data Access Objects : A DAO is a collection of object classes that model the
They use structure query language (SQL). As a standard method for submitting structure of a relational database system. They provide properties and methods that
client requests. Thus a major advantage of Client/Server architecture is reducing allow to accomplish all the operations to manage such a system, including features
traffic and, in most cases, an incredibly quicker execution time. for creating databases, defining tables, navigating and querying a database. Visual
Two Tire and Three Tire Client Server Model : The various system Basic supports Data Access Object such as DBEngine, Workspace, Database,
architecture that has been in use have been discussed so far. Now let us move on to TableDef, Field, Index and Recordset Objects.
discuss the creation of in information system that can change with business needs, DBEngine: The DBEngine is the top level database object and corresponding to
needs that mandate tighter budget and higher quality in addition to simply the Jet database engine. This object is used to set database engine system
processing transactions generating report. To respond to the challenges being parameters and default workspace.
presented by the business environment a new three-tier or n-tier client/server Workspace: The Workspace object is used to support simultaneous transactions
approach has been introduced. and it acts as a container for open database. A default Workspace object
Two Tier Client/Server model : In two-tier model, a desktop machine operates Workspace (0) is created when the DAO are referenced in the language at run time.
as a client and network server function as a back-end database engine. The logic in The default workspace is always available and never be closed or removed from
two in two-tier model is split between the two physical location namely the server the collection. Database: The Database object corresponds to a Jet native or
and client. The client in a two-tier model is necessarily a 4GL like Visual Basic or external database or a direct ODBC connection. This is used to define the
Power Builder. The salient point for a two-tier application is that the business logic database’s table, relations and stored queries and to open Recordset object.
15 15
TableDef: The TableDef object corresponds to stored table definition. Each object provides two properties for the user to know when he has moved to the
TableDef in a collection represents the Definition of a current table in a database or beginning or end of the recordset The EOF (End of File) property is True when
an attached table in the external database. the user moves beyond the last record in the recordset. The BOF (Beginning of
QueryDef: The QueryDef is a stored query definition, which is a precompiled file) property is true when the user moved to a position before the first record in
SOL statement. the recordset.
RecordSet: The Recordset object corresponds to a cursored view into a database Modifying and Deleting Records : To manipulate a recordset, the following
table or the results of query. A cursored view is that stores rows of data in buffer methods are used.
and points to one row of data at a time called current record. The cursor may be Edit Method: The user can edit the current record using the edit method. The
positioned to any row of data using Move, Seek or find methods. Update method is used to save the necessary changes made to the records.
Field: The field object corresponds to a column of data type and set of properties. AddNew Method: AddNew method is used to add a blank record in the recordset.
TableDef, Recordset objects have collection of field objects. The collection of Delete Method: This method can be used to delete record in the dynaset-type
Field object associated with Recordset cursor describes a single row of data. recordset. The jet engine deletes the current record without any warning when the
Index: The index object is stored index allows to quickly reorder the rec. in table. Delete method used.
Parameter: A parameter object represents a parameter associated with a QueryDef Finding Records The Find methods can be used to locate a record in dynaset-type
object created from a parameter query. A parameter’s collection contains all the or snapshot-type Recordset. VB supports four Find methods.
parameter objects of a QueryDef object. FindFirst: method finds the first record satisfying the specified criteria.
User: The User object is used to define and enforce database security. The FindLast: method finds the Last record satisfying the specified criteria.
DBEngine object supports a set of user collection. The Users collection contains all FindNext: method finds the next record satisfying the specified criteria, searching
stored User objects supports a collection of system groups. Each user in the group backward from the current record.
inherits the permissions to access the objects that the group can access. FindPrevious: method finds the previous record satisfying the specified criteria,
Relation: A Relation object represents a relationship between fields in the tables searching backward from the current record.
or queries. A Relations collection contains stored Relation objects of Database Open Database Connectivity (ODBC)
object. The DBEngine enforces certain update and delete conditions on the data Open database connectivity (ODBC) is a windows technology that lets a database
associated with the fields of the Relation object, to maintain referential integrity. client application connect to external database. To use ODBC, database vendor
Property: A property object represents a built-in characteristic or user-define must provide an ODBC driver for data access. Once this driver is available, the
characteristic of a data access object. Properties collection contain all the property client machine should be configured with this driver.
object for a specific instance of an object. Accessing and Navigating Databases In Creating ODBC Data Source
order to work with data objects, a reference has to be set to the appropriate DAO Before any application can access an ODBC database, the ODBC driver must be
library. There are two DAO libraries supported by VB they are: installed and a Data source name (DSN) created using the control panel. The DSN
Microsoft DAO 3.51 Object library : Microsoft DAO 2.5/3.51 Compatibility is used whenever a reference is made to an ODBC database. Follow these steps to
Layer. : To set reference to DAO type library: Select References from the Project create ODBC for Access
Menu Select the DAO 3.51 (or 3.6) Object Library Click on OK button Double click on ODBC configuration option under control panel. A list of ODBC
Opening Database : To open an existing database, the OpenDatabase method of data source is displayed as shown in fig.
workspace object is used Syntax Opendatabase(dbname,[option],[readonly], 1 Select Add button to add new ODBC drivers that are currently installed in
[connect]) The following code opens the employee_detail database Dim db as system are displayed as shown in fig.2
Database Set db = opendatabase(“C:\Emp_detail.mdb”) In the above code, db is a 2 Select Microsoft Access Driver (*.mdb) from list and click on Finish button.
variable that represents the Database object. By default, a database that is opened 3 Type any Data source name and select database for which you want to create
can be shared and modified by any user. To specify that the database is to be DSN by clicking on Select button.
opened fro exclusive use, the following statement can be used: Set db = 4 Click on OK button to complete process.
opendatabase(“Emp_detail.mdb”,True) In the above code True value indicates that Using ODBC with DAO : The properties and methods of DAO can be used in
no users will be able to open the database. The default value is False To open conjunction with ODBC database. OpenDatabase The OpenDatabase method
emp_detail database in the readonly mode, the following statement is used: Set db creates a connection between the application and the ODBC database and assigns it
= Opendatabase(“Emp_dateil”,False,True) In the above statement, the True value to a database type object. Syntax Dim db as Database
specified as the third argument will provide only a read access on the database. Set db = opendatabase (“<Data Source Name>”, <dbdriverpromptinformation>,
Recordset: A recordset is an object that contains a set of records from the “<readonly>” ODBC; UID=<User ID>; PWD=<password>”)
database. There are mainly five types of Recordset object. The Active Data ObjectsVisual Basic supports several data access tools, with the
1 Table-Type Recordset: The table type recordset object is a set of records that Active Data Object (ADO) being the most recent
represents a single table can be used to add, change or delete records. They are addition. Whereas the first Visual Basic data access tools (the Data Access Object,
fastest type of Recordset. discussed before this)allowed programmers to access Access database only, ADO
2 Dynaset-Type Recordset: The dynaset-type recordset object is a set of can access all major databases and Microsoft’s foundation for a universal
records that represent a table, or attachment tables, or the results of queries technology for accessing all types of data in all environments.With ADO, your VB
containing fields from one or more tables. A dynaset enables us to update data application sees three objects: A connection object, which establishes a connection
from more than one table. to the database, be it a local file or remote SQL Server. A command object,
3 Snapshot-Type Recordset: the snapshot type recordset can refer any table, which executes commands against the database.  A Recordset Object, which
attached table or query. A snapshot cannot be updated and does not reflect holds the records retrieved from the database or the records to be updated on the
changes to data made by the users. database.
4 Dynamic type Recordset: This recordset type represent a query result set As we saw AtiveX Data Objects (ADO) access data from OLE DB providers. The
from one or more base tables in which we can add, change or delete records Connection object is used to specify a particular provider and any parameters. To
from a row returning query. Further, records that other users add, delete, or connect to a data source, you use a Connection object. Using that connection, you
edit in the base tables also appear in our recordset. This type is only available can create a new record set, and using the recordset object’s methods and
in ODBCDirect workspace, and corresponds to an ODBC dynamic cursor. properties, you can work with your data. An ADO transaction marks the beginning
5 Forward Only Type recordset: This recordset type is identical to a snapshot and end of series of data operations that are executed across a connection. You can
except that we can only scroll forward through its records. This improves cancel or allow changes.
performance in situations where only need to make a single pass through a ADO Example To explain ADO data handling in code, we’ll build an ADO
result set. In an ODBCDirect workspace, this type corresponds to an ODBC project. This application lets you open the db1.mdb file of access using ADO
forward-only cursor. objects to edit records, add, delete records. You can move through the database
Creating a Recordset: The OpenRecordset method is used to open a Recordset using arrow buttons you see in fig. To edit a record, just type the new value into
and create a recordset variable. To create a read-only recordset for the table emp, the text box and click on update button. To add new record, use add button and
the following code is used. Dim rs as Recordset  rs = insert new values, after it click on update button.
db.OpenRecordset(“emp”,dbopentable,dbReadOnly) In the above statement, db ADO: Opening a Connection The first step to start the ADO project is give
is the variable that represents the database object. Here dbOpenTable specifies the reference to Microsoft ActiveX Data Object library item, and click on OK to add
type of the Recordset to be created. object library to your project Then create object of Connection and Recordset
Navigating a Recordset: After creating a Recordset object, the various methods Dim Cn As New ADODB.Connection Dim Rs As New ADODB.Recordset
can be used to navigate through the recordset.  The MoveFirst :mehthod moves Now we are free to create a new ADO connection to object with the Connection
to the first row in the Recordset  The MoveLast :mehthod moves to the Last object’s Open method:
row in the Recordset  The MoveNext :mehthod moves to the Next row in the Connction.Open ConnectionString[, UserID [, Password [, OpenOption]]]
Recordset Here are the arguments for this method.
The MovePrevious :mehthod moves to the Previous row in the Recordset Connection String-String containing connection information.
Using BOF and EOF to navigate through Recordset  The Recordset UserID- String containing a username to use when establishing the connection
16 16
Password – String containing a password to use when establishing the connection. Delete method used.
OpenOptions - If set adConnectAsync, the connection will be opened Input Validation :What is Input Validation? Input validation is the process of
asynchronously. Code checking the data entered by the user before that data saved to the database. This is
Private sub form_load() dim cn as new ADODB.Connection some times referred to as Client-side validation. This is because the validation
cn.open “PROVIDER = Microsoft.Jet.OLEDB.3.51;Data source = action happens at client’s workstation.
“C:\db1.mdb;”….….End sub Common Input Validation Rules :Almost every field in your database required
Creating a Recordset from Connection : Now that’s you have created an ADO some type of input validation. Before you design form, put together a list of all
connection, you open a record set from that connection using the Recordset fields you need on the form and answer the following questions.
object’s Open method Recordset.Open [ Source, [ Active_connection , [Type, Must data be entered in the field? (Is it required field?).
[ LockType, [ options]]]] What characters are valid/invalid for this field (numeric input only, capital letters
Here the arguments for this method only, on space allowed, and so on)?
Source-A valid command object variable name, an SQL statement, a table name, a For numeric field is there high/low range limit?
stored procedure call, or the file name of Recordset. Solution :If possible, limit the keystrokes to valid values only. For example is the
ActiveConnection-A valid Connection object variable name or a string containing field must be numeric, don’t allowed the user to enter character values. If space are
ConnectionString parameter. not allowed, make sure spacebar is disabled.
Type- Sets the recordset type (see the following list) Limit input choices with lists. If there is a limited set of valid inputs for a field,
dbopenKeyset: Opens a dynaset-type recordset object, which is like an ODBC give the user a pick list or set of radio buttons to choose from.
keyset cursor. Input the user of range limits. If the field has the low and high limit, tell the user
dbOpenDynamic: Opens a dynamic-type Recordset object, which lets the what the limits are. Point out required fields on a form. Mark required fields with a
application see changes made by other leading asterisk (*) or some other appropriate character.
dbOpenStatic: Open a static type recordset object. Field level Validation : The first level of validation is at the field level. This is the
dbOpenForwardOnly: Opens a forward-only-type Recordset object, where you place where you can make sure the user is entering the right character in the field,
can only use MoveNext to move. entering the data into the field in proper format, and entering a valid value based
LockType: A value what determines what type of locking the provider should use on a list of possible choices.
when opening the record set. Discarding Unwanted Keystrokes :Limit data entry in the Key press events
Here are the possible values for the LockType: adLockReadOnly: the default; Private sub text1_KeyPress (Keyascii As Integer)  Dim str as string  Str =
readonly. adLockPessimistic: Pessimistic locking, record by record. “0123456789.”  If Instr(str,chr(keyascii) ) = 0 then  Keyascii = 0 End if
adLockOptimistic: Optimistic locking, record by record. -End sub
adLockBatchOptimistic: Optimistic batch updates. e.g. You declare a string that holds the list of valid keys. The next line loads the string
Private sub form_load()dim cn as new ADODB.Connection dim rs as new with the valid key fields, and the next line checks to see weather the key pressed is
ADODB.Recordset cn.open “PROVIDER = Microsoft.Jet.OLEDB.3.51;Data in the string of valid keys. It does this by converting the numeric value passed by
source = “C:\db1.mdb;”rs.Open “Select * from lib”, cn , Visual Basic in the keyascii parameter (the ASCII value of key Pressed) into
adOpenStatic,adLockOptimistic …. End sub readable character using function chr( ).
ADO: Binding Controls to Record sets :To bind a control to ADO Recordset To convert the input characters into uppercase
objects, you just set that controls DataSource property to that object, and then set Private Sub text1_Keypress(KeyAscii As Integer)KeyAscii =
whatever other data properties that control needs to have set e.g. Asc(Ucase(chr(KeyAscii))) ‘change to upper case End sub
Private sub Form_load()Dim cn as new ADODB.Connection Dim rs as new Input Masking :It is very common to have fields on your form that required
ADODB.Recordset cn.open “PROVIDER = Microsoft.Jet.OLEDB.3.51; Data special input formats. Examples of special formats are telephone numbers,
source = “C:\db1.mdb;”rs.Open “Select * from lib”, cn , government or employee identification numbers, hour / minute time entry, and so
adOpenStatic,adLockOptimisticset text1.datasource = adorecordset text1.Datafield on. VB 6 ships with a bound data control that handles special input and display
= “Title” set text2.datasource = adorecordset text2.Datafield = “cost” End sub formatting: the MaskedEdit control. The MaskedEdit control works like the
ADO: Adding a Record to a Recordset To add a new record to an ADO standard VB 6 textbox control, with few added properties that make it a powerful
recordset, you use the AddNew method, after you’ve updated the fields of the tool for your input validation. To add MaskedEdit control, first select the project,
current record, you save that record to the database with the update method. here’s components and then click on Browse button, scroll down the list to
how you use AddNew: Recordset.AddNew [ Fields [, Values]] MSMASK32.OCX select it and click on OK button.
Fields: a single name or an array of names or ordinal positions of the fields in the The Masked Edit control provides restricted data input as well as formatted data
new record. output. This control supplies visual cues about the type of data being entered or
Values: A single value or an array of values for the fields in the new record. If displayed. This is what the control looks like as an icon in the Toolbox:
Fields is an array, values must also be an array with the same number of members. File Name :MSMASK32.OCX  lass Name:MaskEdBox Properties
e.g. rs.AddNew Format: Specifies the format for displaying and printing numbers, dates, times,
ADO: Updating A Records in a Record Set. and text. Mask: Determines the input mask for the control.
After changing the data in a record’s in fields or adding a new record, you update Syntax [form.]MaskedEdit.Mask [ = string$]
the data source to record the changes, using the Update method: Remarks: You can define input masks at both design time and run time. However,
Recordset.Update fields,values the following are examples of standard input masks that you may want to use at
Here are the arguments for this method: design time. The control can distinguish between numeric and alphabetic
Fields - A single name or an array of names or ordinal positions of the fields in the characters for validation, but cannot check for valid content, such as the correct
new record. month or time of day.
Values -A single value or an array of values for the fields in the new record. If Mask Description
fields is an array, Values must also be an array with the same number of members. Null String (Default) No mask. Acts like a standard text box.
e.g. rs.Update ##-???-## Medium date (US). Example: 20-May-92
ADO: Navigating a Recordset: After creating a Recordset object, the various ##-##-## Short date (US). Example: 05-20-92
methods can be used to navigate through the recordset. ##:## ?? Medium time. Example: 05:36 AM
The MoveFirst : Method moves to the first row in the Recordset ##:## Short time. Example: 17:23
The MoveLast : Method moves to the Last row in the Recordset The input mask can consist of the following characters.
The MoveNext : Method moves to the Next row in the Recordset Mask Description character
The MovePrevious : Method moves to the Previous row in the Recordset # Digit placeholder.
Using BOF and EOF to navigate through Recordset . Decimal placeholder. The actual character used is the one specified as
The Recordset object provides two properties for the user to know when he has the decimal placeholder in your international settings. This character is treated as a
moved to the beginning or end of the recordset The EOF (End of File) property is literal for masking purposes. , Thousands separator. The actual character used is
True when the user moves beyond the last record in the recordset. The BOF the one specified as the thousands separator in your international settings. This
(Beginning of file) property is true when the user moved to a position before the character is treated as a literal for masking purposes. :
first record in the recordset. Time separator. The actual character used is the one specified as the time
Modifying and Deleting Records :To manipulate a recordset, the following separator in your international settings. This character is treated as a literal for
methods are used. masking purposes. Date separator. The actual character used is the one specified
Edit Method: The user can edit the current record using the edit method. The as the date separator in your international settings. This character is treated as a
Update method is used to save the necessary changes made to the records. literal for masking purposes. \ Treat the next character in the mask string as a
AddNew Method: AddNew method is used to add a blank record in the recordset. literal. This allows you to include the '#', '&', 'A', and '?' characters in the
Delete Method: This method can be used to delete record in the dynaset-type mask. This character is treated as a literal for masking purposes. & Character
recordset. The Jet-engine deletes the current record without any warning when the placeholder. Valid values for this placeholder are ANSI characters in the following
17 17
ranges: 32-126 and 128-255.
> Convert all the characters that follow to uppercase.
< Convert all the characters that follow to lowercase.
A Alphanumeric character placeholder (entry required). For example: a –
z, A – Z, or 0 – 9.
A Alphanumeric character placeholder (entry optional).
9 Digit placeholder (entry optional). For example: 0 – 9.
C Character or space placeholder (entry optional). This operates exactly
like the & placeholder, and ensures compatibility with Microsoft Access.
? Letter placeholder. For example: a – z or A – Z.
Literal All other symbols are displayed as literals; that is, as themselves.
Prompt: Sets or returns the character used to prompt a user for input. Syntax
[form.]MaskedEdit.PromptChar [ = char$] Remarks: The underscore character
"_" is the default character value for the property. The PromptChar property can
only be set to exactly one character. Note: To clear the Text property when you
have a mask defined, you first need to set the Mask property to an empty string,
and then the Text property to an empty string: MaskedEdit1.Mask = ""
MaskedEdit1.Text = "" Form Level Validation : Form level validation is an
essential part of designing a good validation scheme for your form. Although many
input errors can be caught and corrected at the field level, there are several
validation steps that can be performed well only at the form level. The form level
validation is performed at the time when the user presses Enter, or clicks the OK or
Save button. These are validations that are done after the user has entered all the
fields, but before any attempt is made to store the values to a table.

You might also like