NOL - VISUAL C++ PROGRAMMING - MC9243.doc by lovemacromastia

VIEWS: 621 PAGES: 40

									               VISUAL C++ PROGRAMMING - 600417
UNIT I

Windows Programming

History of Windows:
    IBM PC – 1981
             OS      – MSDOS ( Microsoft Disk Operating System)
                     – MS DOS was minimal operating system.
                     – For the user, it provided a command- line interface to
                          commands such as DIR and TYPE and loaded
                          application programs into memory for execution.
                     – For the application programmer, MS-DOS offered little
                          more than a set of function calls for doing file
                          input/output (I/O).
                     – For other tasks—in particular, writing text and
                          sometimes graphics to the video display—applications
                          accessed the hardware of the PC directly.
                     –
    Apple Computer – Jan 1983
        •         OS - Lisa
        • set a standard for graphical environments with
            Macintosh in Jan 1984.
    Windows
        • announced by Microsoft corporation in Nov 1983 (post-Lisa but pre-
           Macintosh)

    Windows1.0
        • Nov 1985.
        • with several updates to support the international market.
        • with additional drivers for additional video displays and printers.

    Windows2.0
       • Nov 1987.
       • With several changes to the user interface. also enhancements to the
          keyboard and mouse interface, particularly for menus and dialog
          boxes.
       • requires only Intel 8086 or 8088 microprocessor running in "real
          mode" to access 1 megabyte (MB) of memory.
       • Windows /386
       • released shortly after Windows 2.0
       • used the "virtual 86" mode of the Intel 386 microprocessor to window
       • multitask many DOS programs that directly accessed hardware.
       • A window is a rectangular area on the screen that receives user input
          and displays output in the form of text and graphics.
       • The MessageBox function creates a window, but it is a special-purpose
          window of limited flexibility.
           • The message box window has a title bar with a close button, an
             optional icon, one or more lines of text, and up to four buttons.



An Architectural Ove rvie w

   •   This window procedure is a function that could be either in the program itself
       or in a dynamic- link library.
   •   Windows sends a message to a window by calling the window procedure.
   •   More precisely, a window is always created based on a "window class."
   •   The window class identifies the window procedure that processes messages to
       the window.
   •   The use of a window class allows multiple windows to be based on the same
       window class and hence use the same window procedure.

Creating the Window

    •           We can create a window by calling CreateWindowhwnd =
CreateWindow (szAppName,                      // window class name
               TEXT ("The Hello Program"),// window caption
WS_OVERLAPPEDWINDOW, // window style
CW_USEDEFAULT,                  // initial x position
CW_USEDEFAULT,                  // initial y position
CW_USEDEFAULT,                  // initial x size
CW_USEDEFAULT,                  // initial y size                  NULL,
        // parent window handle                             NULL,
// window menu handle                                hInstance,      // program
instance handle                              NULL) ;                // creation
parameters

Displaying the Window
   •   ShowWindow (hwnd, iCmdShow) ;
   •   The ShowWindow function puts the window on the display.
   •   The first argument is the handle to the window just created by CreateWindow.
   •   The second argument is the iCmdShow value passed as a parameter to
       WinMain. This determines how the window is to be initially displayed on the
       screen, whether it's normal, minimized, or maximized.
   • The value you receive from WinMain and pass to ShowWindow is
  SW_SHOWNORMAL if the window is displayed normally,
  SW_SHOWMAXIMIZED if the window is to be maximized,
  SW_SHOWMINNOACTIVE if the window is just to be displayed in the taskbar
   • UpdateWindow (hwnd) ;
       This function causes the client area to be painted. It accomplishes this by
sending the window procedure , a WM_PAINT message

Presentation Outline
   • Introduction
   • Painting and Repainting
   GDI(Graphical Device Interface)

   •   Client area is the part of the window on which a program is free to draw and
       deliver visual information to the user.
   •   When a program displays text or graphics in its client area, it is often said to
       be "painting" its client area
   •   Windows is a message-driven system.
   •   Windows informs applications of various events by posting messages in the
       application's message queue or sending messages to the appropriate window
       procedure.
   •   Windows informs a window procedure by posting a WM_PAINT message.
   •   The WM_PAINT Message
   •   A window procedure receives a WM_PAINT message whenever one of the
       following events occurs:
           – hidden area of the window is brought into view when a user moves a
               window or uncovers a window.
           – The user resizes the window (if the window class style has the
               CS_HREDRAW and CW_VREDRAW bits set).
           – The program uses the InvalidateRect or InvalidateRgn function to
               explicitly generate a WM_PAINT message.
           – Windows may sometimes post a WM_PAINT message when:
           – Windows removes a dialog box or message box that was overlaying
               part of the window.
           – A menu is pulled down and then released.

A tool tip is displayed. An Introduction to GDI

   •   To paint the client area of your window, we use Windows Graphics Device
       Interface (GDI) functions.
   •   Windows provides several GDI functions for writing text strings to the client
       area of the window
   •   TextOut (hdc, x, y, psText, iLength) ;
       TextOut writes a character string to the client area of the window.
           – The psText argument is a pointer to the character string, and
           – iLength is the length of the string in characters.
           – The x and y arguments define the starting position of the character
               string in the client area.
           – The hdc argument is a "handle to a device context"

The Device Context
   •   The device context is a data structure maintained internally by GDI.
   •   A device context is associated with a particular display device, such as a video
       display or a printer.
   •   Some of the values in the device context are graphics "attributes." These
       attributes define some particulars of how GDI drawing functions work.
   •   With TextOut,
            – the color of the text,
           – the color of the text background,
           – font for the text to be displayed
   •   The Device Context
           – Getting a Device context Handle
           – Getting Device Context Information
           – The Device Context Attributes
   •   For example, when you call TextOut, you need specify in the function only the
       device context handle, the starting coordinates, the text, and the length of the
       text.
   •   You don't need to specify the font, the color of the text, the color of the
       background behind the text, or the intercharacter spacing.
   •   These are all attributes that are part of the device context.
   •   When you want to change one of these attributes, you call a function that does
       so. Subsequent TextOut calls to that device context use the new attribute.


TEXT OUT

     int iLength ;
  TCHAR szBuffer [40] ;
  [ other program lines ]
  iLength = wsprintf (szBuffer, TEXT ("The         sum of %i and %i is %i"), iA, iB,
iA + iB) ;
  TextOut (hdc, x, y, szBuffer, iLength) ;
     Combine the two statements into one:
       TextOut (hdc, x, y, szBuffer, wsprintf (szBuffer, TEXT ("The sum of %i and
%i is %i"),iA, iB, iA + iB)) ;

UNIT II

Variables And Constants

A variable is a location in memory where a value can be stored during the execution
of a Visual Basic application. Visual Basic variables are assigned names by the
programmer when they are declared so that they can easily be referenced in other
places in the application code.

These values may either be declared as variable (in that once the value has been
assigned it can be changed later in the Visual Basic code) or as constant (in that once
the value has been assigned, it cannot be changed elsewhere in the code).

Char Variable

The Char variable type holds a single character (such as the letter 'B'). The value of a
Char can be any character. Internally, a number in the range 0 to 65,553 is used to
represent the character value as defined by the ASCII table. As an example when the
letter 'Z' is assigned to a Visual Basic Char variable, the number 90 is actually stored
in the variable location.

Byte Variable
A Byte variable holds a positive number in the range 0 to 255. Because of the limited
range, Byte variables should be used with caution. An attempt to assign a negative
value or a value greater than 255 to a Visual Basic Byte variable will result in an
error.

Date Variable

The Visual Basic Date variable type holds a date and time value. Dates are declared in
the form #mm/dd/yyyy#. For example, May 23, 2007 would be declared as
#5/23/2007#. Visual Basic provides a number of mechanisms for working with Date
variables (such as calculating a date six months from today's date).

Decimal Variable

The Decimal variable type can store either a whole number or a decimal number up to
29 decimal places. When working with whole numbers, however, it is recommended
that the Integer variable type be used as this is more memory efficient than the
Decimal variable type.

Double Variable

The Visual Basic Double variable is used to store either very large numbers, or small
numbers requiring more than 28 decimal places. To be precise Visual basic Double
variables can store positive numbers in the range 4.94065645841246544E-324 to
1.79769313486231570E+308          and       negative        numbers      from       -
1.79769313486231570E+30 to -4.94065645841246544E-324.

Double variables are typically used when developing scientific applications using
Visual Basic and, as such, are generally not used by the average developer.

Integer Variable

The Visual Basic Integer variable type is used to store whole numbers between -
2,147,483,648 and 2,147,483,648. The Integer variable cannot be used to store
numbers containing decimals.

Object Variable

The Object variable is a catch-all variable type which can be used to store a value of
any data type. Because of this flexibility, an Object variable will typically reserve
more memory than is needed for most variable types. For this reason, it is more
efficient to use the correct variable type for the value you need to store (such as Char
for a character or Integer for a whole number) rather than use the Object variable
type.

Long Variable

The Visual Basic Long variable type is used to store whole numbers ranging from -
9,233,372,036,854,775,808 to 9,233,372,036,854,775,807.
         Short Variable

     A Short variable in Visual Basic stores a whole number in the range -32,768 to
     32,767.

         String Variable

     The String variable type stores multiple characters that make up words or sentences.
     String variables are encapsulated in double-quotation marks ("). For example "Hello"
     is a string, as is "Hello, this is a test".

     Variant Data Types

     Variant variables are now supported by PowerBASIC, but their use is limited to that
     of a parameter assignment for conversion of data, for compatibility with other
     languages and applications, especially COM Objects.

     Although notoriously lacking in efficiency, Variants are commonly used as COM
     Object parameters due to their flexibility. You can think of a Variant as a kind of
     container, which can hold a variable of most any data type, numeric, string, or even an
     entire array. This simplifies the process of calling procedures in a COM Object
     Server, as there is little need to worry about the myriad of possible data types for each
     parameter.

     This flexibility comes at a great price in performance, so PowerBASIC limits their use
     to data storage and parameters only. You may assign a numeric value, a string value,
     or even an entire array to a Variant with the LET statement, or its implied equivalent.
     In the same way, you may assign one Variant value to another Variant variable, or
     even assign an array contained in a Variant to a compatible PowerBASIC array, or the
     reverse.

     You may extract a simple scalar value from a Varia nt with the VARIANT#
     function for numeric values (regardless of the internal numeric data type), or with the
     VARIANT$ function for string values. The following table summarizes the
     predefined (built- in) equates that can be used to examine a Variant:

Result               Equate                            Content Type
0                    %VT_EMPTY                         An Empty Variant
1                    %VT_NULL                          Null value
2                    %VT_I2                            Integer
3                    %VT_I4                            Long-Integer
4                    %VT_R4                            Single
5                    %VT_R8                            Double
6                    %VT_CY                            Currency
7                    %VT_DATE                          Date
8                    %VT_BSTR                          Dynamic String
9                    %VT_DISPATCH                      IDispatch
10                %VT_ERROR                           Error Code
11                %VT_BOOL                            Boolean
12                %VT_VARIANT                         Variant
13                %VT_UNKNOWN                         IUnknown
14                %VT_DECIMAL                         Decimal
16                %VT_I1                              Byte (signed)
17                %VT_UI1                             Byte (unsigned)
18                %VT_UI2                             Word
19                %VT_UI4                             DWORD
20                %VT_I8                              Quad (signed)
21                %VT_UI8                             Quad (unsigned)
22                %VT_INT                             Long-Integer
23                %VT_UINT                            DWord
24                %VT_VOID                            A C-style void type
25                %VT_HRESULT                         COM result code
26                %VT_PTR                             Pointer
27                %VT_SAFEARRAY                       VB Array
28                %VT_CARRAY                          A C-style array
29                %VT_USERDEFINED                     User Defined Type
30                %VT_LPSTR                           ANSI string
31                %VT_LPWSTR                          Unicode string
64                %VT_FILETIME                        A FILETIME value
65                %VT_BLOB                            An arbitrary block of memory
66                %VT_STREAM                          A stream of bytes
67                %VT_STORAGE                         Name of the storage




     Control Arrays

     A control array is a group of controls that share the same name type and t he same
     event procedures. Adding controls with control arrays uses fewer resources than
     adding multiple control of same type at design time.

     A control array can be created only at design time, and at the very minimum at least
     one control must belong to it. You create a control array following one of these three
     methods:
              You create a control and then assign a numeric, non- negative value to
       its Index property; you have thus created a control array with just one element.
              You create two controls of the same class and assign them an identical
       Name property. Visual Basic shows a dialog box warning you that there's
       already a control with that name and asks whether you want to create a control
       array. Click on the Yes button.
              You select a control on the form, press Ctrl+C to copy it to the
       clipboard, and then press Ctrl+V to paste a new instance of the control, which
       has the same Name property as the original one. Visual Basic shows the
       warning mentioned in the previous bullet.

Control arrays are one of the most interesting features of the Visual Basic
environment, and they add a lot of flexibility to your programs:

              Controls that belong to the same control array share the same set of
       event procedures; this often dramatically reduces the amount of code you have
       to write to respond to a user's actions.
              You can dynamically add new elements to a control array at run time;
       in other words, you can effectively create new controls that didn't exist at
       design time.
              Elements of control arrays consume fewer resources than regular
       controls and tend to produce smaller executables. Besides, Visual Basic forms
       can host up to 256 different control names, but a control array counts as one
       against this number. In other words, control arrays let you effectively
       overcome this limit.

The importance of using control arrays as a means of dynamically creating new
controls at run time is somewhat reduced in Visual Basic 6, which has introduced a
new and more powerful capability.

Don't let the term array lead you to think control array is related to VBA arrays;
they're completely different objects. Control arrays can only be one-dimensional.
They don't need to be dimensioned: Each control you add automatically extends the
array. The Index property identifies the position of each control in the control array it
belongs to, but it's possible for a control array to have holes in the index sequence.
The lowest possible value for the Index property is 0. You reference a control
belonging to a control array as you would reference a standard array item:

Text1(0).Text = ""

Working with Control Arrays

A control array is a group of controls that share the same name and type. They also
share the same event procedures. A control array has at least one element and can
grow to as many elements as your system reso urces and memory permit; its size also
depends on how much memory and Windows resources each control requires. The
maximum index you can use in a control array is 32767. Elements of the same control
array have their own property settings. Common uses for control arrays include menu
controls and option button groupings.
Note Visual Basic includes the ability to dynamically add unreferenced controls to
the Controls collection at run time. This topic refers only to referenced controls added
at design time by cutting and pasting a control onto the form. For more information
about adding controls at run time, see the reference topic "Add Method (Controls
Collection)" and "Add Method (Licenses Collection)."

Why Use Control Arrays?

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

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

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


Visual Basic responds to various mouse events, which are recognized by most of the
controls. The main events are MouseDown, MouseUp and MouseMove. MouseDown
occurs when the user presses any mouse button and MouseUp occurs when the user
releases any mouse button. These events use the arguments button, Shift, X, Y and
they contain information about the mouse's condition when the button is clicked.

The first argument is an integer called Button. The value of the ar gument indicates
whether the left, right or middle mouse button was clicked. The second argument in
an integer called shift. The value of this argumnet indicates whether the mouse button
was clicked simultaneously with the Shift key, Ctrl key or Alt key. The third and
fourth arguments X and Y are the coordinates of the mouse location at the time the
mouse button was clicked. As the Form_MouseDown( ) is executed automatically
whenever the mouse button is clicked inside the Form's area the X, Y co-ordinates are
referenced to the form.

Positioning a control

MouseDown     is the commonly used event and it is combined with the move method to
move an Image control to different locations in a Form. The following application
illustrates the movement of objects responding to move events. it makes use of two
OptionButton Controls, two image controls and a CommandButton. The application
is designed in such a way that when an OptionButton is selected, the corresponding
image control is placed anywhere in the form whenever it is clicked.

Open a new standard EXE project and save the Form as Move.frm and save the
project as Move.vbp Design the Form as shown below.
Object            Property          Setting

Form              Caption           MouseDown

                  Name              frmMouseDown

                                    Credit card        is
OptionButton Caption
                                    selected
                  Name
                                    optCredit
                  Value
                                    True

OptionButton Caption                Cash is selected

                  Name              optCash
Image             Name              imgCredit

                  Picture           c:/credit.jpg
Image             Name              imgCash

                  Picture           c:/cash.jpg

The following code is entered in the general declarations section of the Form.

Option Explicit

The following code is entered in the Form_MouseDown( ) event

Private Sub Form_MouseDown(Button As Integer, Shift As Integer, X As Single, Y
As Single)
IfoptCredit=TrueThen
    imgCredit.Move X, Y
  Else
    imgCash.Move X, Y
End If
End Sub

Run the application by keying in F5. You can notice that when the mouse is clicked
on the form somewhere, the selected image moves to that clicked location. This is
shown in the below figure

Onkeydown and Onkeyup

The onkeydown and onkeyup events are triggered when your visitors presses a key on
their keyboard and they acts on the object on your web page that currently has the
focus. As their name suggest the onkey down is triggered when a key is depressed and
onkeyup is triggered when it is released
FILE SYSTEM CONTROL

VB provides three native toolbox controls for working with the file system: the
DriveListBox, DirListBox, and FileListBox. You can use these controls
independently, or in concert with one another to navigate the file system.

The DriveListBox control is a specialized drop-down list that displays a list of all the
valid drives on the user's system. The most important property of the DriveListBox is
the Drive property, which is set when the user selects an entry from the drop-down
list or when you assign a drive string (such as "C:") to the Drive property in code.
You can also read the Drive property to see which drive has been selected.

To make a DirListBox display the directories of the currently selected drive, you
would set the Path property of the DirListBox control to the Drive property of the
DriveListBox control in the Change event of the DriveListBox, as in the following
statement:

Dir1.Path = Drive1.Drive

The DirListBox control displays a hierarchical list of the user's disk directories and
subdirectories and automatically reacts to mouse clicks to allow the user to navigate
among them. To synchronize the path selected in the DirListBox with a FileListBox,
assign the Path property of the DirListBox to the Path property of the FileListBox in
the Change event of the DirListBox, as in the following statement:

File1.Path = Dir1.Path

The FileListBox control lists files in the directory specified by its Path property. You
can display all the files in the current directory, or you can use the Pattern property to
show only certain types of files.

Similar to the standard ListBox and ComboBox controls, you can reference the List,
ListCount, and ListIndex properties to access items in a DriveListBox, DirListBox,
or FileListBox control. In addition, the FileListBox has a MultiSelect property which
may be set to allow multiple file selection.

Sample Program Ove rvie w

The sample program is a "Text File Viewer". The sample program uses the
DriveListBox, DirListBox, and FileListBox to allow the user to navigate his or her
file system. When the user selects a file that the program deems to be a "plain text"
file, and that file is not "too large", the contents of that file is displayed in a multi- line,
scrollable textbox.

In the screen-shot below, the user has navigated to the directory "C:\Program
Files\CesarFTP" and selected the file "tests.txt" from that directory. The content of
"tests.txt" is displayed in the multi- line textbox:

Sample Program Code
The heavily-commented code for the sample program is shown below.
Option Explicit
' Form-level variable to indicate last valid drive selected ...
Private mstrDrive As String

'-----------------------------------------------------------------------------
Private Sub Form_Load()
'-----------------------------------------------------------------------------
' Initialize the DriveListBox to point to the C: drive ...
drvSelDrive.Drive = "C:"
' Likewise for the "mstrDrive" variable ...
mstrDrive = "C:"
' Set the path of the DirListBox to point to the root of C:
dirSelDir.Path = "C:\"
 End Sub
 '-----------------------------------------------------------------------------
Private Sub drvSelDrive_Change()
'-----------------------------------------------------------------------------
' An error would occur if you attempted to change to a CD or floppy drive
' where the media was not ready ...
On Error Resume Next
' When the drive changes, set the Path of the DirListBox to point to the
' the newly selected drive ...
dirSelDir.Path = drvSelDrive.Drive
If Err.Number <> 0 Then
' There was a problem with the drive - most likely a CD or floppy drive was
' selected, but there was no CD or disk in the drive.
' Inform the user ...
MsgBox "Drive selected is unavailable.", vbInformation, "Drive Unavailable"
' Reset the Drive property of the DriveListBox to the last valid drive ...
drvSelDrive.Drive = mstrDrive
Else
' Drive change was OK, update the "mstrDrive" variable with the newly
' selected drive ...
mstrDrive = drvSelDrive.Drive
End If
End Sub

'-----------------------------------------------------------------------------
Private Sub dirSelDir_Change()
'-----------------------------------------------------------------------------
' The path of the DirListBox has changed, so set the path of the FileListBox
' to point to the new path of the DirListBox. This action alone will cause the
' contents FileListBox to refresh.

filTextFileViewer.Path = dirSelDir.Path
' Update the label caption to reflect the new directory path ...
lblCurrentDir.Caption = dirSelDir.Path
' Test the ListCount property of the FileListBox to see if there are any files
' in the current path ...
If filTextFileViewer.ListCount > 0 Then
' There is at least one file in the current path, so highlight (select) the
' first file by setting ListIndex to 0. This will invoke the filTextFileViewer_Click
' event ...
filTextFileViewer.ListIndex = 0
Else
' There are no files in the current path ...
lblSelectedFileName.Caption = "(None)"
txtFileContent.Text = ""
End If
End Sub

'-----------------------------------------------------------------------------
Private Sub dirSelDir_Click()
'-----------------------------------------------------------------------------

' Coding the Click event for the DirListBox with the code below will force
' the dirSelDir_Change event (by setting the Path property to the List property
' of the currently clicked item). Without doing this, the change event would
' only occur when user DOUBLE-CLICKS a new directory in the DirListBox.
' Invoking the Change on a single-click seems more natural.
' Note: Unlike other list controls, the List property of the DirListBox holds
' not just the text that is displayed in the control, but also the text of its
' of parent paths. For example, if the currently selected entry in a DirListBox
' was a directory called "CesarFTP" below the "Program Files" directory below the
' "C:" drive, the contents of that selected List entry would be
' "C:\Program Files\CesarFTP" - NOT JUST "CesarFTP".
With dirSelDir
.Path = .List(.ListIndex)
End With
 End Sub

'-----------------------------------------------------------------------------
Private Sub filTextFileViewer_Click()
'-----------------------------------------------------------------------------

Dim strFileExt As String
Dim strCurrFile As String
Dim strFileContent As String
Dim intFreeFile As Integer
Dim lngFileLen As Long
Dim lngX As Long
Dim blnIsTextFile As Boolean
' If no files are selected from the FileListBox (ListIndex = -1),
' then get out because there's nothing to do ...
If filTextFileViewer.ListIndex = -1 Then Exit Sub
' Form a fully-qualified file name by concatenating the Path property
' of the FileListBox with the text of the currently selected entry (which
' is the filename). If the path already has a backslash at the end of it
' (as it would for a root directory), fine, otherwise add a backslash to the
' end of it before concatenating it with the filename ...
With filTextFileViewer
strCurrFile = IIf(Right$(.Path, 1) = "\", .Path, .Path & "\") _
& .List(.ListIndex)
End With
' Update the label caption to reflect the new filename ...
lblSelectedFileName.Caption = strCurrFile
' Use the FileLen function to get the length of the current file ...
lngFileLen = FileLen(strCurrFile)
' Test the file length ...
If lngFileLen >= 65536 Then
' Too big for the textbox, so just display the message ...
txtFileContent.Text = "*** Selected file is too large to be displayed. ***"
Else
' Read the entire contents of the file into a string variable ("strFileContent") ...
intFreeFile = FreeFile
Open strCurrFile For Binary Access Read As #intFreeFile
strFileContent = Input(LOF(intFreeFile), intFreeFile)
Close #intFreeFile
' Loop thru the file content byte-by-byte to test for characters that would
' "disqualify" the file from being regarded as a "plain-text" file. For our
' purposes, the ASCII characters 0 thru 8, 11 thru 12, and 14 thru 31 would
' disqualify the file.
blnIsTextFile = True
For lngX = 1 To lngFileLen
Select Case Asc(Mid$(strFileContent, lngX, 1))
Case 0 To 8, 11 To 12, 14 To 31
blnIsTextFile = False


CommonDialog Control Property and Method Equivalencies

The following tables list Visual Basic 6.0 properties and methods and their Visual
Basic 2005 equivalents. Properties and methods with the same names and behaviors
are not listed. Where applicable, constants are indented beneath the property or
method. All Visual Basic 2005 enumerations map to the System Windows.Forms
namespace unless otherwise noted.

Links are provided as necessary to topics explaining differences in behavior. Where
there is no direct equivalent in Visual Basic 2005, links are provided to topics that
present alternatives.

Properties
Visual Basic 6.0       Visual Basic 2005 Equivalent
Action                 New implementation. The Visual Basic 6.0 Action property
                       determines which dialog to display; Visual Basic 2005 uses a
                    separate component for each dialog.

CancelError         Cancel

Copies              Copies

DialogTitle         Title (OpenFileDialog and SaveFileDialog components only)

                    New implementation for the other components. Standard
                    Windows titles (Color, Font, and Print) are displayed and
                    cannot be overridden.

FileName            FileNames

FileTitle           New implementation. The Visual Basic 6.0 FileTitle property
                    returns the FileName without the path; you can parse the
                    FileNames property to get the name without the path.

Flags               The Visual Basic 6.0 Flags property provides constants for
                    setting various attributes of the different common dialogs.
                    Rather than using constants, the dialog components provide
                    properties for setting the attributes.

Font                Font

FontBold

FontItalic

FontName

FontSize

FontStrikethrough

FontUnde rline

FromPage            FromPage

hDC                 New implementation. For more information see Graphics for
                    Visual Basic 6.0 Users.

HelpCommand         HelpNavigator
HelpFile              HelpNamespace

HelpKey               The parameter parameter of the ShowHelp method.

Index                 New implementation. For more information, see Control Arrays
                      for Visual Basic 6.0 Users.

InitDir               InitialDirectory

Left                  Left



Max                   MaxSize (FontDialog component)

                      MaximumPage (PrintDialog component)

Min                   MinSize (FontDialog component)

                      MinimumPage (PrintDialog component)

MaxFileSize           New implementation. This property Visual Basic 6.0 allocates
                      memory for extremely long file names; it is no longer necessary
                      in managed code.

Orientation           Landscape

Parent                FindForm method

PrinterDefault        New implementation. This Visual Basic 6.0 property is used in
                      conjunction with the hDC property to print using graphic
                      device interface methods; this is no longer supported.

Top                   P:System.Windows.Forms.Control



Methods
Visual Basic Visual Basic 2005 Equivalent
6.0
AboutBox         New implementation. The AboutBox property displayed an About
                 box for the CommonDialog control, which was created for Microsoft
                 by a third party.

ShowColor        ShowDialog (ColorDialog component)
ShowFont         ShowDialog (FontDialog component)

ShowHelp         ShowHelp

ShowOpen         ShowDialog (OpenFileDialog component)

ShowPrinter      ShowDialog (PrintDialog component)

ShowSave         ShowDialog (SaveFileDialog component)

Upgrade Notes

When upgrading an application from Visual Basic 6.0 to Visual Basic 2005, any
CommonDialog controls are upgraded to their equivalent dialog component
(OpenFileDialog, SaveFileDialog, ColorDialog, FontDialog or PrintDialog).

There is no direct equivalent for showing a Help dialog in Visual Basic 2005. If a
CommonDialog control is being used as a Help dialog, a warning will be issued and
it will not be upgraded. For more information, see Help Support for Visual Basic 6.0
Users.

A single CommonDialog control could be used to display different types of dialogs.
In this case it will be upgraded to a OpenFileDialog component; a warning will be
issued and you will need to add the other dialog components manually.

In addition, where a CommonDialog control was used as a variable you may need to
change it to refer to a specific dialog component after upgrade.

Processing Files In Visual Basic

Storing data
Data comes in many forms. It can be a list of DVDs you own and want to keep track
of, the description of all the online college courses you intend to take or even the
movie             stars            you            intend           to          date!

In the previous lessons, you have learned how to manipulate the VB environment to
produce forms, do calculations, edit text and so on. However, everything you've done
so far is a one-shot deal. Even if you did create the Payroll form, you can use it to
calculate the net pay for any number of employees but, you can't save any of that
information.

That's where data storage comes in. There are many ways to store data for future use.
The most popular and powerful method is to create a database. But that can get quite
involved and it does require a certain amount of analysis knowledge and skill. The
next two lessons will cover how to create and use databases in VB.

A much more accessible method and one which you have certainly used many times
before, is to create a data file. A file is a collection of data on a given subject, stored
on a storage medium, usually a disk or CD. There are executable files, usually with
the .EXE extension, library files (.DLL), Word document files (.DOC) and a hundred
other types. Many applications call for data to be stored and then read back later for
further processing. Think of a simple application: an Address book to store people's
names, addresses and phone numbers. You could create an Address book database
and indeed, it is often the first one you learn how to do in database courses. However,
the task is more suited to data file processing. You just want to create a form to input
names, addresses and phone numbers and then you want to store all the information
entered in a file so that you can print it or look-up numbers when needed. In this
lesson we will learn how to create our own files to store and retrieve data.

Defining new terms

      Record: one logical section of a file that holds a related set of data. If the file
       contains Student information, a record would hold the information on one
       student: name, address, studentID, etc. If there are 5,000 students registered,
       the file contains 5,000 records.

      Field: part of a record that defines a specific information. In the Student
       record, FirstName, LastName, StudentID, are fields. The field is the lowest
       element in the file. Even if the information consists of one character, Sex is M
       or F, it is still considered a separate field. The field is the equivalent of the
       variable - we call it a variable when it is used to store data in memory and call
       it a field when it stores in a file.

      I/O: stands for Input/Output. Whenever you work with a file you have to have
       ways of reading data from the file (that's Input) and ways of writing data to
       the file (that's Output). I/O operations consist of all those commands that let
       you read and write files.

Types of files
There are basically three types of files you can work with:

      Sequential file: this is a file where all the information is written in order from
       the beginning to the end. To access a given record you have to read all the
       records stored before it. It is in fact like listening to a tape - you can go
       forward or back but you can't jump directly to a specific song on the tape. I n
       fact, in the old days, magnetic tape was the most commonly used medium to
       store data and all files were organized this way. Now, it is still useful when
       there is a small amount of data to store, a file of application settings, for
       example. It can even be of use when there is a large amount of data to be
       stored, provided it all has to be processed at one time, eg: a file of invoices to
       produce a statement at month-end.

      Random file: a file where all records are accessible individually. It is like a
       CD where you can jump to any track. This is useful when there is a large
       quantity of data to store and it has to be available quickly: you have to know if
       a part is in stock for a customer who is on the phone; the program doesn't have
       time to search through 10,000 records individually to locate the correct one.
       This method of storage became popular when hard-disk drives were
       developed.
      Binary file : this is a special, compacted form of the random file. Data is stored
       at the byte level and you can read and write individual bytes to the file. This
       makes the file access very fast and efficient. We won't be covering this type of
       file in these exercises. If you need to find out more about it, go to the VB
       Reference Manual.

Opening and closing files
To begin our work on files we will look at some commands that are common to both
Sequential and Random files. After that we will look at the specific processing
commands for each type of file.

The first command to include in a program that needs to work with files is the Open
command. Open assigns the file to a numbered file handle, also called a channel, or
sometimes a buffer. The format of the command is:

Open "Filename" [For Mode] [AccessRestriction] [LockType] As #FileNumber

For example:
Open "MyFile.txt" For Random Read Lock Read As #1

      MyFile.txt is the name of the file in the disk directory.
      For Random means that access to the records can be random; if access is not
       specified, For random is the default value.
      Read restricts access to Read-only - the user cannot write or change the
       records.
      Lock Read means that only the person reading the record can have access to it
       at any given time; it is not shared among users.
      As #1 means the file is assigned file handle #1; for all processing in the
       program, it will always be refered to as #1, not its Filename.



AccessRestriction and LockType are parameters that are used mostly with files in a
network environment. You use them when you want the file to be shared or not, and
you want to prevent certain users from changing or deleting things that they shouldn't.
For the rest of this lesson we will not be using those parameters.

Access Mode
For Mode in the Open statement indicates how the file will be used. There are five
access modes:
   Input: open for sequential input; the file will be read sequentially starting at the
beginning.

      Output: open for sequential output; records will be written sequentially
       starting at the beginning; if the file does not exist, it is created; if it does exist,
       it is overwritten.

      Random: open for random read and write; any specific record can be
       accessed.
       Append: sequential output to the end of an existing file; if the file does not
        exist it is created; it does not overwrite the file.

       Binary: open for binary read and write; access is at byte level.

If access mode is not specified in the Open statement, For Random is used by
default.

Once processing is finished, you need to Close all the files that have been opened.
The format for the Close statement is:

Close #FileNumber1 [, #FileNumber2] ...

You can close any number of files with one Close statement. Eg:

Close #1, #2, #3

The following statement closes all open files:

Close


Writing and Reading a Sequential file
There are two commands that allow you to write data to a sequential file: Print and
Write. They work in almost the same way but, the Print command does not separate
the fields in the file in quite the same way which makes the data harder to read
afterwards. There is really no valid reason to use Print when creating a sequential file.
In the rest of this lesson we will use Write exclusively.

The format of the Write command is:

Write #FileNumbe r, OutputList

where FileNumber is the number the file was opened with and OutputList is one or
more variables you want to write to the file.
Address Book Example

In this exercise we will create a simple address book file to keep track of people's
names, addresses and phone numbers.

To handle the various forms that we have to use, we will develop a new technique for
these lessons: the use of a Menu of choices. Note that that is not the same as a Menu
bar used in a form. In this case we are just going to line-up a series of buttons for the
different forms that have to be called. There has also been a small change to the
display format - from now on all the forms are maximized (they occupy the full
screen) - this is often easier for the user to work with, rather than have a number of
different forms overlapping on the screen. To get the form to run maximized, change
the Form property WindowState -> 2 - Maximized.
Connecting to an Access Database Using the VB Data Control

STEPS:
1. Open a new Visual Basic project.

2. Put a data control (an intrinsic control, located in the VB toolbox) on the form and
       set the properties as follows:

Property                    Value

(Name)                      DatAuthors

Caption                     Use the arrows to view the data

Connect                     Access (default)

DatabaseName                ..\biblio.mdb

DefaultType                 UseJet (default)

RecordSource                Authors (choose from list)



       Notes: When you use the Data Control in a project, the properties that must be
       set are DatabaseName and RecordSource, in that order. DatabaseName is
       the name of the database you want to use, and the RecordSource is the name
       of the table in that database that you want to use.
           3. On your form, create a text box for each field in the Authors table, with
                labels. (If you were to open the database in Access, you would see that
                the three fields of the Authors table are Au_ID, Author, and Year
                Born.) Set the properties of the three textboxes as follows:

     Name                    DataSource               DataField

    TxtAuthID                DatAuthors               Au_ID

    TxtAuthor                DatAuthors               Author

    txtYearBorn              DatAuthors               Year Born



In addition, set the Enabled property of txtAuthID to False.
 When you want a control (such as a text box) to display data from a database, the
properties that must be set are DataSource and Datafield. The DataSource is the
name of the data control on the form (it should already be configured), and the
DataField is the name of the particular field in the database that should be displayed
in the control (this field will be in the table that was chosen for the RecordSource of
the data control).
4. Save and run the project. Use the arrows on the data control to scroll through the
data.
5. On any record, change the data in the author name or year born field. Move ahead,
        then move back to the record you changed. Note that your changes remain in
        effect. The data control automatically updates a record when you move off of
        the record.
Note that this exercise demonstrated that you can create a simple but functional
application that allows the user to browse through the rows of a database table (or
result set) and to update rows in that table without writing any code.




UNIT III

The Microsoft Foundation Class Library Application Frame work

       Application frame work

         ―An integrated collection of object-oriented software components that offers
all that's needed for a generic application.―

        An Application Frame work vs. a Class Library
        - An application framework is a superset of a class library.
         - An ordinary library is an isolated set of classes designed to be incorporated
into any program, but an application framework defines the structure of the program
itself

       MyApp.h heade r file for the MYAPP application:
       The MFC library is the C++ Microsoft Windows API.

       Application frame work applications use a standard structure.

       Application frame work applications are small and fast.

       The Visual C++ tools reduce coding drudgery

       The MFC library application frame work is feature rich


An Application Frame work Example
source code for the header and implementation files for our
MYAPPapplication.
// application class
class CMyApp : public CWinApp
 {
  public:
      virtual BOOL InitInstance();
 };
// frame window class
class CMyFrame : public CFrameWnd
{
 public:
    CMyFrame();
 protected:
    // "afx_msg" indicates that the next two functions are part
    // of the MFC library message dispatch system afx_msg void
OnLButtonDown(UINT nFlags, CPoint point);
     afx_msg void OnPaint();
     DECLARE_MESSAGE_MAP()
 };

MyApp.cpp - implementation file for the MYAPP application

#include <afxwin.h> // MFC library header file declares base classes
#include "myapp.h" CMyApp theApp; // the one and only CMyApp object
BOOL CMyApp::InitInstance()
{ m_pMainWnd = new CMyFrame();
 m_pMainWnd->ShowWindow(m_nCmdShow);
m_pMainWnd->UpdateWindow();
return TRUE;
 }
BEGIN_MESSAGE_MAP(CMyFrame, CFrameWnd)
ON_WM_LBUTTONDOWN()
    ON_WM_PAINT()
END_MESSAGE_MAP()

CMyFrame::CMyFrame()
{
Create(NULL, "MYAPP Application");
}
void CMyFrame::OnLButtonDown(UINT nFlags, CPoint point)
{ TRACE("Entering CMyFrame::OnLButtonDown - %lx, %d, %d\n", (long) nFlags,
point.x, point.y);
}
void CMyFrame::OnPaint()
{ CPaintDC dc(this);
dc.TextOut(0, 0, "Hello, world!");
}
The CMyApp::InitInstance me mber function
        When the WinMain function finds the application object, it calls the virtual
InitInstance member function, which makes the calls needed to construct and display
the application's main frame window. You must override InitInstance in your derived
application class because the CWinApp base class doesn't know what kind of main
frame window you want.
The CWinApp::Run membe r function
         The Run function is hidden in the base class, but it dispatches the application's
messages to its windows, thus keeping the application running. WinMain calls Run
after it calls InitInstance.
The CMyFrame class
         An object of class CMyFrame represents the application's main frame
window. When the constructor calls the Create member function of the base class
CFrameWnd, Windows creates the actual window structure and the application
framework links it to the C++ object. The ShowWindow and UpdateWindow
functions, also member functions of the base class, must be called in order to display
the window.

The CMyFrame::OnLButtonDown function                   MFC library's message- handling
capability.
        The function invokes the MFC library TRACE macro to display a message in
the debugging window.
The CMyFrame::OnPaint function - The application framework calls this important
mapped member function of
      class CMyFrame every time it's necessary to repaint the window: at the start of
      the program, when the user resizes the window, and when all or part of the
      window is newly exposed.
        - The CPaintDC statement relates to the Graphics Device Interface (GDI) and
is explained in later chapters. The TextOut function displays "Hello, world!"
Application shutdown
        - The user shuts down the application by closing the main frame window.
        - This action initiates a sequence of events, which ends with the destruction of
     the CMyFrame object, the exit from Run, the exit from WinMain, and the
     destruction of the CMyApp object.

Basic Event Handling, Mapping Modes, and a Scrolling Vie w- T8

   •  The Message Handler:
              void CMyView::OnLButtonDown(UINT nFlags, CPoint point)
       {
         // event processing code here
        }
  The Message Map:
              BEGIN_MESSAGE_MAP(CMyView, CView)
      ON_WM_LBUTTONDOWN()
                               // entry specifically for OnLButtonDown
                // other message map entries
       END_MESSAGE_MAP()
   • Finally, your class header file needs the statement
      DECLARE_MESSAGE_MAP()

Invalid Rectangle Theory

   •   InvalidateRect triggers a Windows WM_PAINT message, which is mapped
       in the CView class to call to the virtual OnDraw function.
   •   If necessary, OnDraw can access the "invalid rectangle" parameter that was
       passed to InvalidateRect.
   •   Your OnDraw function could call the CDC member function GetClipBox to
       determine the invalid rectangle, and then it could avoid drawing objects
       outside it.
   •   OnDraw is being called not only in response to your InvalidateRect call but
       also when the user resizes or exposes the window.
   •   Thus, OnDraw is responsible for all drawing in a window, and it has to adapt
       to whatever invalid rectangle it gets.


   The Window's Client Area

   The Window's Client Area
   • A window has a rectangular client area that excludes the border, caption bar,
      menu bar, and any toolbars.
   • The CWnd member function GetClientRect supplies you with the client-area
      dimensions.
   • Normally, you're not allowed to draw outside the client area, and most mouse
      messages are received only when the mouse cursor is in the client area.
   CRect, CPoint, and CSize Arithmetic
   • The CRect, CPoint, and CSize classes are derived from the Windows RECT,
      POINT, and SIZE structures, and thus they inherit public integer data members
      as follows:    CRect left, top, right, bottom
      CPoint x, y
      CSize cx, cy


   Bitmaps

   •   Windows bitmaps are arrays of bits mapped to display pixels.
   •   There are two kinds of Windows bitmaps: GDI bitmaps       and DIBs.
   •     GDI bitmap objects are represented by the Microsoft     Foundation Class
       (MFC) Library version 6.0

Color Bitmaps and Monochrome Bitmaps

   •   Many color bitmaps are 16-color. A standard VGA board has four contiguous
       color planes, with 1 corresponding bit from each plane combining to represent
       a pixel.
   •   The 4-bit color values are set when the bitmap is created. With a standard
       VGA board, bitmap colors are limited to the standard 16 colors. Windows
       does not use dithered colors in bitmaps.
   •   A monochrome bitmap has only one plane. Each pixel is represented by a
       single bit that is either off (0) or on (1). The CDC::SetTextColor function sets
       the "off" display color, and SetBkColor sets the "on" color.
   •   You can specify these pure colors individually with the Windows RGB macro.

Code to load a Bitmap

void OnPaint()
     {
  CBitmap mybm;
       CPaintDC d(this);
       mybm.LoadBitmap(IDB_BITMAP1);
       CBrush mybrush;
       mybrush.CreatePatternBrush(&mybm);
  d.SelectObject(&mybrush);
       d.Rectangle(100,100,300,300);
     }

GDI Bitmaps and Device-Independent Bitmaps

GDI Bitmaps
  •   There are two kinds of Windows bitmaps: GDI bitmaps and DIBs.
  •   GDI bitmap objects are represented by the Microsoft Foundation Class (MFC)
      Library version 6.0 CBitmap class.
  •    The GDI bitmap object has an associated Windows data structure, maintained
      inside the Windows GDI module, that is device-dependent.
  •   Your program can get a copy of the bitmap data, but the bit arrangement
      depends on the display hardware.
  •   GDI bitmaps can be freely transferred among programs on a single computer,
      but because of their device dependency, transferring bitmaps by disk or
      modem doesn't make sense.

  Device-Independent Bitmaps

  •   DIBs offer many programming advantages over GDI bitmaps.
  •   Since a DIB carries its own color information, color palette management is
      easier.
  •   DIBs also make it easy to control gray shades when printing. Any computer
      running Windows can process DIBs, which are usually stored in BMP disk
      files or as a resource in your program's EXE or DLL file.
  •   The wallpaper background on your monitor is read from a BMP file when you
      start Windows.
  •    The primary storage format for Microsoft Paint is the BMP file, and Visual
      C++ uses BMP files for toolbar buttons and other images.
  •    Other graphic interchange formats are available, such as TIFF, GIF, and
      JPEG, but only the DIB format is directly supported by the Win32 API.
  Frame Window - Definition
   An application or some parts of an application when framed by Windows are
    called Frame Windows
   Frame windows act as containers for other windows such as control bars or
    child controls

Basic types of Frame Windows

   Single Document Interface (SDI) frame windows
   Multiple Document Interface (MDI) frame windows.
    MDI frame windows can contain MDI child windows
 MFC supports two types of document/view applications. Single document
  interface (SDI) applications support just one open document at a time.
  Multiple document interface (MDI) applications permit two or more
  documents to be open concurrently and also support multiple views of a given
  document. The WordPad applet is an SDI application; Microsoft Word is an
  MDI application.
 SDI application frame windows are derived from the class CFrameWnd.
 The MFC library supports two distinct application types: Single Document
  Interface (SDI) and Multiple Document Interface (MDI). An SDI application
  has, only one window. If the application depends on disk-file "documents,"
  only one document can be loaded at a time. The original Windows Notepad is
  an example of an SDI application.

MDI

 MDI application frame windows are derived from the class CMDIFrameWnd.
 An MDI application has multiple child windows, each of which corresponds to
  an individual document. Microsoft Word is a good example of an MDI
  application. When you run AppWizard to create a new project, MDI is the
  default application type


 Windows Menus

A Microsoft Windows menu is a familiar application element tha t consists of a
top-level horizontal list of items with associated pop- up menus that appear when
the user selects a top- level item.
Menu items - grayed ,have check marks, separator bar.
 Multiple levels pop- up menus are possible.
Each Menu item – ID which is defined in resource.h
Entire resource definition - .rc file(resource script file)

For example, Menu item is Line (ID is
               ID_LINE )
For handle it in the view class,

In view.cpp

    BEGIN_MESSAGE_MAP(CMyView,CView)
    ON_COMMAND(ID_LINE, OnLine)
    END_MESSAGE_MAP()
    void CMyView::OnLine()
    { // command message processing code
     }
In MyView.h – Give the definition
            afx_msg void OnZoom();
before DECLARE_MESSAGE_MAP() macro


The Modal Dialog and Windows Common Controls
    The two kinds of dialogs are modal and modeless.
    The CDialog base class supports both modal and modeless dialogs
   Modal Dialog Box:
       The user cannot work elsewhere in the same application (more correctly, in
   the same user interface thread) until the dialog is c losed. Example: Open File
   dialog
   Modeless Dialog
       The user can work in another window in the application while the dialog
   remains on the screen
       Example: Microsoft Word's Find and Replace dialog is a good example of a
   modeless dialog; you can edit your document while the dialog is open.
   Controls.
       A dialog contains a number of elements called controls. Dialog controls
   include edit controls, buttons, list boxes, combo boxes, static text, tree views,
   progress indicators, sliders, and so forth.


   Programming a Modal Dialog

   Use the dialog editor to create a dialog resource that contains various controls.
   1.The dialog editor updates the project's resource script (RC) file to include your
   new dialog resource, and it updates the project's resource.h file with
   corresponding #define constants.
   2. Use ClassWizard to create a dialog class that is derived from CDialog and
   attached to the resource created in step 1.
       -ClassWizard adds the associated code and header file to the Microsoft Visual
   C++ project.
   3. Use ClassWizard to add data members, exchange functions, and validation
       functions to the dialog class.
   4. Use ClassWizard to add message handlers for the dialog's buttons and other
       event-generating controls.
   5. Write the code for special control initialization (in OnInitDialog) and for the
       message handlers. Be sure the CDialog virtual member function OnOK is
       called when the user closes the dialog (unless the user cancels the dialog).
       (Note: OnOK is called by default.)


the constructor implementation looks like this:
CMyDialog::CMyDialog(CWnd* pParent /*=NULL*/) : CDialog(CMyDialog::IDD,
pParent)
{
// initialization code here
}
The use of enum IDD decouples the CPP file from the resource IDs that are defined in
the project's resource.h


The Windows Common Dialogs
    Windows provides a group of standard user interface dialogs, and these are
      supported by the MFC library classes.
    All the common dialog classes are derived from a common base class,
      CCommonDialog.
Class                             Purpose
CColorDialog                Allows the user to select or create a color
CFileDialog                 Allows the user to open or save a file
CFindReplaceDialog         Allows the user to substitute one string for another
CPageSetupDialog            Allows the user to input page measurement
                          parameters
CFontDialog                 Allows the user to select a font from a list of
                         available fonts
CPrintDialog               Allows the user to set up the printer and print a
                           document

UNIT V

Domain Name Service

    is a hierarchical naming system for computers, services in the Internet is an
     IETF-standard name service.
    enables client computers on your network to register and resolve DNS domain
     names.
    names are used to find and access resources offered by other computers on
     your network or other networks, such as the Internet.

      three main components of DNS:
      Domain name space and associated resource records (RRs)
      DNS Name Servers
      DNS Resolvers




   Email

    Electronic mail abbreviated as e- mail or email
   is method of creating, transmitting, or storing primarily text-based human
    communications with digital communications systems
   based on a store-and- forward model in which e-mail computer server systems,
    accept, forward, or store messages on behalf of users


  Email Features

  Email is Fast
  Email is Inexpensive
  Email is Easy to Filter
  Transmission is Secure and Reliable

         1.Fast - Messages can be sent anywhere around the world in an instant
         2.cheap - Transmission usually costs nothing, or at the most, very little
         3.simple-Easyto            use,         after           initial    set-up
         4.efficient - Sending to a group can be done in one step
         5.versatile - Pictures, powerpoints or other files can be sent too

  HTTP

  is an application- level protocol for distributed, collaborative, hypermedia
  information systems.
   It is a generic, stateless, protocol which can be used for many tasks such as name
  servers and distributed object management systems, through extension of its
  request methods, error codes and headers
  typing and negotiation of data representation
   allows systems to be built independently of the data being transferred.




Splitter Windows
A splitter window is a window that can be divided into two or more panes
horizontally, vertically, or both horizontally and vertically using movable splitter bars.
Each pane contains one view of a document's data. The views are children of the
splitter window, and the splitter window itself is normally a child of a frame window.
Using splitter windows provided by MFC, a single document interface (SDI)
application can present two or more views of the same document in resizeable
"panes" that subdivide the frame window's client area
In an SDI application, the splitter window is a child of the top- level frame window.

Types of splitter windows

Static splitter window:

   The numbers of rows and columns in a static splitter window are set when the
splitter is created and can't be changed by the user. The user is, however, free to resize
individual rows and columns. A static splitter window can contain a maximum of 16
rows and 16 columns. For an example of an application that uses a static splitter, look
no further than the Windows Explorer. Explorer's ma in window is divided in half
vertically by a static splitter window.

Dynamic Splitter window

A dynamic splitter window is limited to at most two rows and two columns, but it can
be split and unsplit interactively. The views displayed in a dynamic splitte r window's
panes aren't entirely independent of each other: when a dynamic splitter window is
split horizontally, the two rows have independent vertical scroll bars but share a
horizontal scroll bar. Similarly, the two columns of a dynamic splitter window split
vertically contain horizontal scroll bars of their own but share a vertical scroll bar.
The maximum number of rows and columns a dynamic splitter window can be
divided into are specified when the splitter is created. Thus, it's a simple matt




Procedure for Creating and initializing a dynamic splitter window
Add a CSplitterWnd data member to the frame window class.
Override the frame window's virtual OnCreateClient function, and call
CSplitterWnd::Create to create a dynamic splitter window in the frame window's
client area.

Creating splitter window…

Assuming m_wndSplitter is a CSplitterWnd object that's a member of the frame
window class CMainFrame, the following OnCreateClient override creates a dynamic
splitter window inside the frame window:
BOOL CMainFrame::OnCreateClient
(LPCREATESTRUCT lpcs,
CCreateContext* pContext)
{
 return m_wndSplitter.Create (this, 2, 1, CSize (1, 1), pContext);
}

The first parameter to CSplitterWnd::Create identifies the splitter window's parent,
which is the frame window.
The second and third parameters specify the maximum number of rows and columns
that the window can be split into.
Because a dynamic splitter window supports a maximum of two rows and two
columns, these parameter values will always be 1 or 2.
The fourth parameter specifies each pane's minimum width and height in pixels. The
framework uses these values to determine when panes should be created and
destroyed as splitter bars are moved.
CSize values equal to (1,1) specify that panes can be as little as 1 pixel wide and 1
pixel tall.
The fifth parameter is a pointer to a CCreateContext structure provided by the
framework. The structure's m_pNewViewClass member identifies the view class used
to create views in the splitter's panes.
The framework creates the initial view for you and puts it into the first pane. Other
views of the same class are created automatically as additional panes are created.

Class CRichEditView
CObject
   |
   +--CCmdTarget
         |
         +--CWnd
               |
               +--CView
                     |
                     +--CCtrlView
                           |
                           +--CRichEditView




MFC

Class CObject

Direct Known Subclasses:
       CArray, CAsyncSocket, CByteArray, CCmdTarget, CCommandLineInfo,
       CDC, CDWordArray, CDaoDatabase, CDaoQueryDef, CDaoRecordset,
       CDaoTableDEf, CDaoWorkspace, CDatabase, CDocManager, CDockState,
       CException, CFile, CFileFind, CGdiObject, CGopherLocator, CImageList,
       CInternetConnection, CInternetSession, CList, CLongBinary, CMap,
      CMapPtrToPtr, CMapPtrToWord, CMapStringToOb, CMapStringToPtr,
      CMapStringToString,     CMapWordToOb,      CMapWordToPtr, CMenu,
      CObArray, CObList, CPtrArray, CPtrList, CRecordset, CStringArray,
      CStringList, CSyncObject, CUIntArray, CWordArray

MFC

Class CCmdTarget
CObject
   |
   +--CCmdTarget

 in AFXWIN.H
Direct Known Subclasses:
       CConnectionPoint,  CDocItem,    CDocObjectServer,    CDocTemplate,
       CDocument,    CDynLinkLibrary,   COleDataSource,   COleDropSource,
       COleDropTarget, COleMessageFilter, COleObjectFactory, CWinThread,
       CWnd

MFC

Class CWnd
CObject
   |
   +--CCmdTarget
         |
         +--CWnd



Direct Known Subclasses:
       CAnimateCtrl, CButton, CComboBox, CControlBar, CDateTimeCtrl,
       CDialog, CEdit, CFrameWnd, CHeaderCtrl, CHotKeyCtrl, CIPAddressCtrl,
       CListBox, CListCtrl, CMonthCalCtrl, COleControl, CProgressCtrl,
       CPropertySheet, CReBarCtrl, CRichEditCtrl, CScrollBar, CSliderCtrl,
       CSocketWnd, CSpinButtonCtrl, CSplitterWnd, CStatic, CStatusBarCtrl,
       CTabCtrl, CToolBarCtrl, CToolTipCtrl, CTreeCtrl, CView


MFC

Class CView
CObject
   |
   +--CCmdTarget
         |
         +--CWnd
               |
               +--CView

 in AFXWIN.H
Direct Known Subclasses:
       CCtrlView, CScrollView
MFC

Class CView
CObject
   |
   +--CCmdTarget
         |
         +--CWnd
               |
               +--CView



Direct Known Subclasses:
       CCtrlView, CScrollView


ActiveX Controls

ActiveX Controls vs Ordinary Windows Controls
Installing ActiveX Controls
The Calendar Control
ActiveX Control Container Programming
Create ActiveX Control at Runtime

ActiveX Controls vs. Ordinary Windows Controls

Ordinary controls send notification command messages (standard Windows
messages), such as BN_CLICKED, to the dialog.
An ActiveX control doesn't send WM_ notification messages to its container the way
ordinary controls do; instead, it "fires events."
Events don't return a value to the ActiveX control.
Examples of events are Click, KeyDown, and NewMonth.
All the MFC control classes are derived from CWnd, so if you want to get the text
from an edit control, you call CWnd::GetWindowText. But even that function works
by sending a message to the control.
How ActiveX Controls Are Different from Ordinary Controls—Properties and
Methods
The most prominent ActiveX Controls features are properties and methods.
Properties have symbolic names that are matched to integer indexes.

An event has a symbolic name and can have an arbitrary sequence of parameters
The generated Dialog Data Exchange (DDX) code exchanges data between the
control properties and the client class data members.

Installing ActiveX Controls
ActiveX controls are small programs, sometimes called add-ons, that are used on the
Internet. They can enhance your browsing experience by allowing animation or they
can help with tasks such as installing security updates at Microsoft Update.
ActiveX is a framework for defining reusable software components in a programming
language independent way. Software applications can then be composed from one or
more of these components in order to provide their functionality

It was introduced in 1996 by Microsoft as a development of its Component Object
Model (COM) and Object Linking and Embedding (OLE) technologies and is
commonly used in its Windows operating system, although the technology itself is not
tied to it.

Many Microsoft Windows applications — including many of those from Microsoft
itself, such as Internet Explorer, Microsoft Office, Microsoft Visual Studio, and
Windows Media Player — use ActiveX controls to build their feature-set and also
encapsulate their own functionality as ActiveX controls which can then be embedded
into other applications. Internet Explorer also allows embedding ActiveX controls
onto web pages

ActiveX controls — small program building blocks — can serve to create distributed
applications that work over the Internet through web browsers. Examples include
customized applications for gathering data, viewing certain kinds of files, and
displaying animation.

One can compare ActiveX controls in some sense to Java applets programmers
designed both of these mechanisms so that web browsers could download and execute
them. However, they also differ:

      Java applets can run on nearly any platform, while ActiveX compone nts
       officially operate only with Microsoft's Internet Explorer web browser and the
       Microsoft Windows operating system. Malware, such as computer viruses and
       spyware, can be accidentally installed from malicious websites using ActiveX
       controls (drive-by downloads).

Programmers can write ActiveX controls in any language that supports COM
component development, including the following languages/environments:

      C++ either directly or with the help of libraries such as ATL or MFC
      Borland Delphi
      Visual Basic


Copy the ActiveX control's DLL to \Winnt\System32
Copy associated files such as help (HLP) or license (LIC) files to the same directory.
Register the control in the Windows Registry. Actually, the ActiveX control registers
itself when a client program calls a special exported function.
The Windows utility Regsvr32 is a client that accepts the control name on the
command line.

Install the ActiveX control in each project that uses it.

ClassWizard's C++ Wrapper Classes for ActiveX Controls
When you insert an ActiveX control into a project, ClassWizard generates a C++
wrapper class, derived from CWnd, that is tailored to your control's methods and
properties.
The class has member functions for all properties and methods, and it has constructors
that you can use to dynamically create an instance of the control.

Database Management System ODBC
Database is used to store data and
Provide access to manipulate the data.
Use of standard file formats
Provides multiple user interaction

In VC++ the database connectivity is implemented by using
Open DataBase Connectivity (ODBC)
DataAccessObject (DAO)
Active Data Object (ADO)
OLE DB

  Database Architecture of VC++
                        Application

                       MFC Database Classes

             ODBC / Database
                                        DAO / Microsoft
              Specific Driver
                                          Jet Engine




                                Database
                                Manager

                                 Data                     Form
                                 base
    Table1
                   Index                        Query




ODBC Architecture

use the ODBC API to access data from a variety of different data sources
Contains Driver Manager for performing the database activities.
Supports various database drivers
Microsoft SQL Server
Oracle
Microsoft Access
Microsoft FoxPro
Implemented by C native API

MFC classes for ODBC
There are 3 different Built in classes provided by MFC
CDatabase
Manages a Connection to a data source.
Work as a Database Manager
CRecordSet
Manages a set of rows returned from the database.
CRecordView
Simplifies the display of data from CRecordSet Object.

ODBC classes overview

CRecordSet
MFC Appwizard generates a CRecordSet derived class and return a pointer named
m_pSet to our application program.
How to Map database values to Recordset
Using Record Field Exchange
we can move the data back and forth from recordset to data base.
The exchange is set up by implementing the CRecordset:: DoFieldExchange()
function, and it maps the member variables of Recordset and Database.
void CChap21Set::DoFieldExchange(CFieldExchange* pFX)
 { //{{AFX_FIELD_MAP(CChap21Set)
    pFX->SetFieldType(CFieldExchange:: outputColumn); RFX_Long(pFX,
_T("[EmpId]"), m_EmpId);
    RFX_Text(pFX, _T("[EmpName]"), m_EmpName);
    RFX_Text(pFX, _T("[Salary]"), m_Salary);
//}}AFX_FIELD_MAP}

CRecordset::GetFieldValue()
Is a alternative for RecordFieldExchange
Which enables you to retrieve the value of any field in a current View.
Even if we not defined member variable OR set up of RFX.
Using the column name or index to retrieve the data
retrieve values as a CString or a CDBVariant object


CRecordset functions

Provides various built in functions
Table and ODBC related
To Navigating data in the recordset
To Manipulating the data's in record set
Bookmark the records in a recordset
Tabl and ODBC related Functions
CRecordSet:: GetSQL()
Returns the Entire SQL String.
GetTableName()
Returns the table name used.
GetODBCFieldCount()
Returns the total no of columns returned by the query
Close()
Close the database connection
Open()
Reconnect / connect the data base to the program

Navigating the data in recordset
MoveNext()
MovePrev()
MoveLast()
MoveFirst()
CanScroll()
Check the recordset having only forward only cursor
SetAbsolutePosition()
Move to specific rows in Record set
Which takes Zero based index into the record

To Manipulating the data's in record set
Delete()
Delete the current row & set the member variables NULL
AddNew()
Create a new row with field values are empty.
CanAppend()
Used to check whether record set provides adding of records
Edit()
To edit or modify the current record details
Update()
Used to update the record set when a new record is added / existing record is edited

Winsock

In computing, the Windows Sockets API, which was later shortened to Winsock, is a
technical specification that defines how Windows network software should access
network services, especially TCP/IP. It defines a standard interface between a
Windows TCP/IP client application (such as an FTP client or a web browser) and the
underlying TCP/IP protocol stack. The nomenclature is based on the Berkeley sockets
API model used in BSD for communications between programs. Initially, all the
participating developers resisted the shortening of the name to Winsock for a long
time, since there was much confusion among users between the API and the DLL
library file (winsock.dll) which only exposed the common WSA interfaces to
applications above it. Users would commonly believe that only making sure the DLL
file was present on a system would provide full TCP/IP protocol support.

Technology
The Windows Sockets API specification defines two interfaces: the API used by
application developers, and the SPI, which provides a means for network software
developers to add new protocol modules to the system. Each interface represents a
contract. The API guarantees that a conforming application will function correctly
with a conformant protocol implementation from any network software vendor. The
SPI contract guarantees that a conforming protocol module may be added to Windows
and will thereby be usable by an API-conformant application. Although these
contracts were important when Windows Sockets was first released, as network
environments required multi-protocol support (see above) they are now of only
academic interest. Included in the Windows Sockets API version 2.0 are functions to
use IPX/SPX, but no commercial application is known to exist which utilizes this
transport, since the protocol was all but obsolete already at the time WSA 2.0 shipped.
Microsoft has shipped the TCP/IP protocol stack with all recent versions of Windows,
and there are no significant independent alternatives. Nor has there been significant
interest in implementing protocols other than TCP/IP.

Windows Sockets code and design are based on BSD sockets, but provides additional
functionality to allow the API to comply with the standard Windows programming
model. The Windows Sockets API covered almost all the features of the BSD sockets
API, but there were some unavoidable obstacles which mostly arose out of
fundamental differences between Windows and Unix (though to be fair Windows
Sockets differed less from BSD sockets than the latter did from STREAMS). All
function calls in the API begin with the moniker WSA, e.g. WSASend() for sending data
on a connected socket.

However it was a design goal of Windows Sockets that it should be relatively easy for
developers to port socket-based applications from Unix to Windows. It was not
considered sufficient to create an API which was only useful for newly-written
Windows programs. For this reason, Windows Sockets included a number of elements
which were designed to facilitate porting. For example, Unix applications were able to
use the same variable to record both networking errors and errors detected within
standard C library functions. Since this was not possible in Windows, Windows
Sockets introduced a dedicated function, WSAGetLastError(), to retrieve error
information.

Such mechanisms were helpful, but application porting remained extremely complex.
Many original TCP/IP applications had been implemented by using system features
specific to Unix, such as pseudo terminals and the fork system call, and reproducing
such functionality in Windows was problematic. Within a relatively short time,
porting gave way to the development of dedicated Windows applications.




Specifications
      Version 1.0 (June 1992) defined the basic operation o f Winsock. It was kept
       very close to the existing interface of Berkeley sockets to simplify porting of
       existing applications. A few Windows-specific extensions were added, mainly
       for asynchronous operations with message-based notifications.

       Although the document didn't limit support to TCP/IP, TCP and UDP were the
       only protocols explicitly mentioned. Most vendors only delivered TCP/IP
       support, although Winsock from DEC included DECNet support as well.

      Version 1.1 (January 1993) made many minor corrections a nd clarifications of
       the specification. The most significant change was the inclusion of the
       gethostname() function.
   Winsock 2 was a backwards-compatible extension of Winsock 1.1. It added
    support for protocol- independent name resolution, asynchronous operations
    with event-based notifications and completion routines, layered protocol
    implementations, multicasting, and quality of service. It also formalized
    support for multiple protocols, including IPX/SPX and DECnet. The new
    specification allowed sockets to be optionally shared between processes,
    incoming connection requests to be conditionally accepted, and certain
    operations to be performed on socket groups rather than individual sockets.
    Although the new specification differed substantially from Winsock 1, it
    provided source- and binary- level compatibility with the Winsock 1.1 API.
    One of the lesser known additions was the Service Provider Interface (SPI)
    API and Layered Service Providers.
   Versions 2.0.x (May 1994 onwards) had internal draft status, and we re not
    announced as public standards.
   Version 2.1.0 (January 1996) was the first public release of the Winsock 2
    specification.
   Version 2.2.0 (May 1996) included many minor corrections, clarifications, and
    usage recommendations. It was also the first version to remove support for 16-
    bit Windows applications.
   Version 2.2.1 (May 1997) and Version 2.2.2 (August 1997) introduced minor
    functionality enhancements. Mechanisms were added for querying and
    receiving notification of changes in network and system configuration.

   The IPv6 Technical Preview for Windows 2000 (December 2000) saw the first
    implementation of RFC 2553 (March 1999, later obsoleted by RFC 3493), a
    protocol- independent API for name resolution, which would become part of
    Winsock in Windows XP.

								
To top