Vous êtes sur la page 1sur 28

Unit III Visual Programming

UNIT III

Visual C++ Programming: Visual C++ Components – Developing Applications –


Microsoft Foundation Class (MFC) – Controls – Message handling – Document View
Architecture – Dialog Based Applications – Mouse and Keyboard Events – Reading and
Writing Documents – SDI and MDI Environments.

1.VISUAL C++ COMPONENTS TO CREATE A MFC APPLICATION

The description of the above illustration, which illustrates the components, involved in
creation of an application using MFC is elucidated in the following section. The
developer studio is the interface used in source code and creates sources. The Resource.h
file stores the information about the sources.

Windows Source files Developer Resource script


header Studio file (RC)

Bitmaps, icons &


Runtime Resource.h
other
header

MFC Headers
Resource complier

Compiler Executable files

OBJ files linker

Windows, Runtime and Executable file


MFC Libraries (EXE)

The file is included in the source code using an #include statement. When the source code
is compiled, in addition to the Resource.h, the following headers are also included:

Windows Header Files: Header files containing prototypes for functions called by
windows.

Run-time Header Files: Header files containing prototypes for DLLs to be linked at run-
time.
MFC Header Files: Files containing prototypes for MFC classes. These header files are
included using the #include statement. The Compiler converts the source file int an object
(OBJ) file. The Compiler generates the code in binary format for the OBJ files. A

1
Unit III Visual Programming

Resource script file is generated whenever a resource is created. The Graphics editor
creates and maintains this file for information about the resources created by the user.

Project Workspace: It is for creating a new project, select New from the File menu and
the Project window appears as shown in fig7.2. Assume that a MFC Win 32 project is
selected and a project name is entered. Then OK button is clicked. A series of windows
follows in case of application wizards, which are discussed in detail in the forth-coming
chapters and after the entire steps have been completed, all the files associated with that
project are generated.

To view the various files on a project, select Workspace from the Project menu, which
opens into the Project Workspace. The Project workspace offers a provision of looking
at a project in three views. They are the class view. Resource View and File view.

The Class View window provides a hierarchical representation of classes when


embedded in other classes. The private, public and protected class members are identified
using different symbols. Any appropriate class file can be edited by double clicking an
item the class file.

The Resource View window will list the various resources that have been added in any
application and their properties can be edited by right clicking on any item and then
selecting the properties option.

The File View lists the entire project source files and dependencies. Double clicking on
any files opens the file for editing.
1.1 PROJECT TYPES

2
Unit III Visual Programming

On Clicking the New Command in the Developer Studio’s File menu, a New Project
wizard opens. This includes different project types from which a relevant application can
be chosen. The types of project that can be developed using MFC are as given below.

Win32 Application – This wizard can be used while setting up DS project.

MFC ActiveX Control Wizard - It is used to create a project that consists of one or
more Activex Controls based on MFC control implementation.

Win32Console Application – Its runs from the command line in Windows OS

Win32Static Library - To Create a Static Library file, which can be linked with other
object modules

Win32 DLL – To create a project file for Dynamic Link Library project.

ATL COM AppWizard - To create a new Template Library file as a project.

Custom AppWizard - To create a Custom AppWizard can be using types of Wizard.

DevStudio Add-in Wizard – This Wizard enables Creation of extentions to Visual


Studio.

ISAPI Extension Wizard - The ISAP (Internet Server Application Extension Wizard.)

Makefile - This type of wizard can be used to create a makefile-based project when an
external make file or some executable program is to be specified to rebuild a project.

1.2 THE MFC CLASS HIERARCHY

The Foundation Class Library’s classes are broken into two main categories: those
derived from the Cobject Class and those that are not.

The CObject derived classes are the subsystems categorized as given below

• The Root class: Cobject


• Array, List and Map classes
• Debugging and Exception classes
• Drawing and Printing classes
• File and Database Classes
• Internet and Networking Classes
• MFC application and Architecture Classes
• Window, Dialog and Control Classes

The classes that are not derived from CObject are broken into the following application
framework subsystems.

3
Unit III Visual Programming

• Simple Data type classes


• Support classes
• Type Template Classes
• OLE classes
• Structure Classes
• Synchronization Classes

1.3 DOCUMENTS AND VIEWS

Documents and Views are classes where the code for a document/View application is
stored. A Document contains the data for an application archived to retrieve from a file.
MFC provides a Cdocument class that allows to us to design our own document classes.
A view is a window attached to a document. The View serves two purposes.

It acts as a window to a document’s data. The view renders the documents data on the
display and also renders the image for printing and prints preview operations.

Accepts user input for an application and translates it into changes within a document’s
data.

1.4 WINDOW, DIALOG AND CONTROL CLASSES

The Win32 API identifies a window object by its window handle (HWND). Win32 uses
many predefined structure and macros to define the attributes of a window. MFC
encapsulates the win32 API functions common to all window objects in class CWnd.
These Classes derived from CWnd inherit HWND. A CWnd object wraps and owns a
windows window.

The Main types of windows in the framework derived from CWnd are listed here

• Frame window classes


• View classes
• Dialog Box classes
• Control Classes
• Control Bar Classes

4
Unit III Visual Programming

1.5 MFC CONTROLS

The controls are objects that users can interact with, to enter or manipulate data. They
commonly appear in dialog boxes or on toolbars. Controls in a dialog box are often
represented by member variables in the corresponding dialog class. To facilitate the
exchange of data between controls in the dialog box object and member variables in the
dialog class, the Dialog Data Exchange mechanism can be used. The major three classes
are considered as very common controls for windows applications. These controls make
the task of getting information form the user directly.

The control classes that are

CEdit
CListBox
CComboBox

Edit Box and ListBox Controls

When the user needs to get text information from another user, or when the user wants to
enter or edit text for some other purpose, an edit controls is used. When several data
items exist to that can be chosen and used in an application, a convenient means of letting
a user make a selection is by using a list box control. The forthcoming sections of this
session explain the styles, messages and messages relevant to these controls and offer a
look at how to use them in an application context. These standard controls are inherited
from 16 bit windows, but still play a valuable role in the windows user interface.

The Edit Control

The edit control is a rectangular control window typically used in a dialog box to permit
the user to enter and edit text from the keyboard. There are two styles of edit controls.

i) Single Line Edit control


ii) Multiple-Line Edit control.

A Single line edit control displays all text on a single line, regardless of hard return
characters. Multiple line edit controls display text on multiple line separately by hard-
return characters. The MFC provides the services of a standard Windows edit control in
the class CEdit.

The following figure gives the position of class CEdit in the MFC hierarchy of windows
class:

5
Unit III Visual Programming

CObject

CCmdTarget

CWnd

CEdit

Edit Control Styles

Like all windows, edit controls can use the styles available to CWnd, in addition to the
edit styles shown in the following table. There are two general styles of CEdit controls:
Single line and multiple lines.

Edit Messages

As MFC wraps the standard edit Messages into CEdit class method a MFC program
usually handles only notification messages. An edit control sends notification messages
to its owner, which is usually a Cdialog- derived class. These messages can be trapped
and handled by writing message map entries and methods are implemented in the edit
control’s owner’s class. In a MFC program, the users map messages that a CEdit object
deals with to class methods. This is done by creating message map entries in the
control’s parent class.

ON_EN_CHANGE - Sent when a user has changed text in an edit control.

ON_EN_KILLFOCUS - Sent when an edit control loses the input focus.

ON_EN_SETFOCUS - Sent when an edit control receives the input focus.

The CEdit Class methods

The CEdit class offers a well-rounded set of methods for manipulating text in an
edit window. These methods are broken into the following categories.

i) General Purpose
ii) Multiple Specific Purpose

The single line edit control methods are Getsel ( ), ReplaceSel( ) , Setsel ( ) , Clear( ) ,
Copy ( ), Cut( ) , and Paste( ).

6
Unit III Visual Programming

The Multiple line edit control methods are Getline(), SetTabStops( ) , GetHandle( ) ,
SetHandle( ).

List Box Control

List Boxes are common user interface controls that allow the selection of one or more
items from a list. List box maintain their own scroll bars to allw the user to scroll among
the data in the list. There are two general styles of list box available in the VC++ MFC.

i) Single Selection list Box


ii) Multiple-Selection List Box

A single selection list Box allows the user to select only one item at a time, where as a
multiple selection list box allows the user to select any number of items. The CListBox
class provides the functionality of a windows list box. This class is derived from CWnd.
Which means that it is window and inherits all the capabilities of a CWnd Object. The
following figure illustrates the position of Clist Box class in the MFC hierarchy of
window classes.

CObject

CCmdTarget

CWnd

CListBox

ListBox Styles

Like all windows, list boxes can have a combination of windows styles. This is because
they are windows, list boxes can use any combination of CWnd styles in addition to the
list box styles shown in the following. These styles allow a lot of flexibility in the
activities of the list Box.

LBS_DISABLENOSCROLL - Disable the list box’s vertical scroll bar


LBS_EXTENDEDSEL - Allows the selection of Multiple item in a list box
LBS_HASSTRINGS - Specifies an owner-drawn list box that contain string
items.
LBS_MULTICOLUMN - Specifies a multicolumn list box with a horizontal scroll
bar.
LBS_MULTIPLESEL - Selects or deselects a string item each time a user clicks

The Clist Box class methods

7
Unit III Visual Programming

The CListBox class provides many methods for dealing with and manipulating list boxes
and list box data. These methods are broken into the following categories.

 General Purpose methods


 Single Selection list box methods
 Multiple Selection list Box methods
 String specific methods
 Virtual methods.

An overview of each method is provided so that the users know what to look for when
they need help on the relevant topic.

General Purpose Methods

Getcount ( ) , GetItemData( ) , GetItemDataPtr( ) SetItemData( ) GetText( )

Single Selection list box methods

GetCurSel( ) and SetCurSel( )

Multiple Selection list Box methods

GetAnchorIndex( ) , GetCareIndex ( ) , GetSelCount ( ) , SetSel( )

String specific methods

Addstring () , DeleteString ( ) , FindString( ) and SelectString( )

ComboBox Control

Windows supports the combo box control, which combines an edit box with a list box.
Thus a combo box allows one to select either an item in the list box component or the
user can type in their own input. There are three kinds of combo boxes

 Simple Combo Box


 Dropdown combo Box
 Dropdown list Combo box

The drop down combo box differ from the simple type by the fact that the list box
appears only when the user clicks the down scroll arrow. The drop-down list combo box
proves a drop down list that appears when the user clicks on the down scroll arrow.
There is no edit in this kind of combo box.

8
Unit III Visual Programming

The CComboBox class

The CComboBox class provides the functionality of a windows combo box. The
CComboBox class is derived directly from CWnd. This class provides a set of methods
that make working with the list box items relatively easy. The figure given below
illustrates the position of class CComboBox in the MF hierarchy of window classes.

CObject

CCmdTarget

CWnd

CComboBox

Combo Box Styles

Like all windows Combo boxes can have a combination of window styles. Because they
are windows, combo boxes can use any combination of CWnd styles in addition to the
combo box styles shown in the following. These styles allow a lot of flexibility in what
the combo box can do.

CBS_AUTOHSCROLL - Automatically scrolls the text


CBS_DISABLENOSCROLL - Disables the list box
CBS_DROPDOWN - The list box portion is not displayed
CBS_DROPDOWNLIST - The list box portion is not displayed
CBS_SIMPLE - The list box portion is always visible

Ccombo Box Methods

The CComboBox class provides a full set of methods for manipulating lists in a combo
box. The methods are broken into the following categories.

General Purpose Methods

SetCurSel( ) - Selects a string in the list box of a combo box


SetItemData( ) - Sets the 32 Bit value associated with the specified items in a combo
box.
GetItemData( ) - Retrieves the application supplied 32 bit.
String Specific Methods

AddString( ) - Adds a string to the end of the list in the list Box of Combo Box
DeleteString ( ) - Deletes a string from the list box of a combo box.
InsertString( ) - Inserts a string into the list box of a combo box

9
Unit III Visual Programming

FindString ( ) - Finds the first string that contains the specified prefix in the list box

MFC Other Controls

The MFC provides many controls other than the major three controls such as CEdit
CListBox and CComboBox. These are Buttons, Spins Scrollbar and slider Controls are
commonly used windows controls that can lend luster to the user interface.

Button Controls

Buttons are rectangular windows that usually contain a caption describing the user of the
control . Buttons are among the most prevalent controls in windows application. There
are four major categories namely

 Checkboxes
 PushButtons
 RadioButtons
 GroupBoxes

To receive a command or to collect a response from a user, a pushbutton is often a good


control choice. When several mutually exclusive data items exist, a set of radio buttons
is a convenient means of letting the user make a selection. If several option are not
exclusive, a set of checkboxes is the likely control choice. To create a frame around
other controls and to create visual groupings a group box control in often used.

Buttons can be created as child controls of any window by writing a code, but it is more
appropriate to define them in a dialog resource template- because buttons appear most
frequently in dialog boxes, either in groups or single. MFC provides all the functionality
of the standard windows buttons in the class CButton. The following figure shows the
position of Cbutton in the class hierarchy.

CObject

CCmdTarget

CWnd

Cbutton

Button Styles

10
Unit III Visual Programming

Like all windows, buttons can have a combination of window styles, because buttons are
windows, they can use any combination of CWnd Styles. In addition to the general
window styles, buttons can also make use of the special button styles.

BS_CHECKBOX - This style creates a checkbox


BS_DEFPUSHBUTTON – The style creates a default pushbutton
BS_GROUPBOX - The style creates a captioned framing rectangle for grouping control
BS_LEFTTEXT - The style causes the button text to appear on the left side
BS_PUSHBUTTON - The style creates a pushbutton
BS_RADIOBUTTON - The style creates a Radiobutton

Cbutton Messages

A MFC message map usually has to handle only button notification messages

ON_BN_CLICKED - Sent by a button control when a user clicks the button


ON_BN_dblCLICKED - Sent by a button control when a user double clicks the button
ON_COMMAND - Sent by a button control when a user clicks the button

CButton Class Methods

The CButton constructor allocates a CButton object that is initialized with the
Button::Create( ) method to set attributes and ownership.

GetButtonStyle( ) – Gets the information about the button control object


GetCheck( ) - Gets the check state of a button control
GetState( ) - Gets the cheek state, selection state, and focus state of a button control
SetButtonStyle ( ) – Changes the style of a button
Setcheck( ) – Sets the check state of a button control
SetState( ) – Sets the selection state of a button control

Spin Controls

A “Spin Button Control” (Known as Up and Down control) is a pair of arrow buttons that
the user can click to increment or decrement a value, such as scroll position or a number
displayed in a combination control. The value associated with a spin button control is
called its current position. A Spin Control is most often used with a companion control
known as a “Buddy Windows”.

A spin-button control without a buddy window functions as a sort of simplified scroll bar.
For Example, a Tab control sometimes displays a spin button control to enable the user to
scroll additional tabs into view. In order to manipulate the spin button, a member
variable of type CspinButtonCtrl should be created in the dialog class.

CObject

11
Unit III Visual Programming

CCmdTarget

CWnd

CspinButtonCtrl

SpinButton Styles

Like all windows, spin controls can use the general window styles to CWnd. In addtion
they use the spin styles shown in the table below. The Spin control’s styles determine its
appearance and operations. Style bits are typically set when the control is initialized with
the CspinButtonCtrl::Create( ) method.

UDS_ALIGNLEFT – Aligns a spin control to the left of the buddy windows


UDS_ALIGNRIGHT - Aligns a spin control to the right of the buddy windows
UDS_HORZ – Makes the controls arrow point left and right instead of up and down
UDS_RAP – Allow the current position to wrap around

CspinButtonCtrl Methods

The CpinButtonCtrl class offers a concise set of methods for manipulating the control
and its data. The CpinButtonCtrl constructor allocates a spin control object that is
initialized with the CpinButtonCtrl::Create( ) method to set attributes and ownership.
The methods list in the following table describe the methods used to get and set control
attributes:

GetBase( ) - Retrieves the current base for the spin control


GetBuddy( ) - Retrieves the ponter to the current buddy windows
GetPos( ) - Retrieves the current position of a spin control.
And
GetRange() , SetBase( ) , SetBuddy() and SetRange( )

Scroll Bar and Slider Controls

A Scroll bar is an interactive control that responds to user input in several ways. It
consists of a Scroll Box that runs along the length of a bar, with arrow buttons on either
end of the bar. A scroll bar control is different from the scroll bar that belongs to a
window. A “Slider control” is a window containing a slider and optional ticks marks.
When the user moves the slider, using either the mouse or the direction keys, the control
sends notification message to indicate the change. The sections that follow discuss the
methods, styles and message of these controls.

12
Unit III Visual Programming

Scroll Bar Control

A scroll bar control is created, managed and destroyed by the application


developer. A Scroll bar can be oriented horizontally or vertically in a window. The
arrow buttons increment or decrement an internal value, called the scroll position, when
clicked. The minimum and maximum scroll position values are set by an application at
run time and can change as the needs of the application change.

Like other MFC controls CscrollBar is derived directly from CWnd and inherits
all the functionality of CWnd

CObject

CCmdTarget

CWnd

CscrollBar

CscrollBar Class Methods

The CscrollBar offers a small set of methods for manipulating the control and its data.
Some of the important methods are discussed below. The ScrollBar Constructor,
CscrollBar::CscrollBar( ) allocates a scroll bar object that is initialized with the
CscrollBar::Create( ) allocates a scroll bar object that is initialized with the
CscrollBar::Create() method to set attributes and ownership.

EnableScrollBar( ) - Enables or Disables one or both arrow of a scroll bar.


GetScrollimit () - Get the limit of the scroll bar
GetScrollPost( ) - Get the current position of a thump
SetScrollpost – Set the current of the thump.

The Slider Control

The CsliderCtrl class provides the functionality of the window common slider control. A
Slider control can be created as windows’s child control by writing a code. Alternately it
can be defined for use in a dialog resource template. A Slider control sends windows
motification messages to its owner and these messages can be trapped and handled by
writing message map entries and message handler methods for each message. These
message map entries and methods are implemented in the slider control’s parent class.

CObject

13
Unit III Visual Programming

CCmdTarget

CWnd

CscrollBar

Slider Control Styles

Like all windows slider controls can use the general window styles available to CWnd.
In addition, they use the controls styles show in the forthcoming listing.

TBS_AUTOTICKS – Gives a slider tick marks for each increment in its range of values.

TBS_ENABLESELRANGE – Gives a slider ticks marks in the shape of triangles.


TBS_HORZ – Orients a slider horizontally
TBS_LEFT – Place tick marks on the left side of a vertical slider control
TBS_RIGHT –Place tick marks on the right side of a vertical slider control
TBS_VERT – Orients a slider vertically

CsliderCtrl Class Methods

An application can all the slider control’s member functions to retrieve information about
the slider control and to change its characteristics

The methods are

GetPos( ) - Retrieve the position of the slider


SetPos( ) – Set the position of the slider
VerifyPos( ) – Helps in making sure that the slider is between the maximum and
minimum
SetRange( ) - Sets the range of a slider control at the time of its creation
SetTicFreq – Allows an application to set tick marks that appears at rectangular intervals.

2. MESSAGE HANDLING

Messages are the heart of windows programming, Absolutely nothing happens in a


program unless a message comes along. Of course, the message only initiates the action.
The message map “Maps” the messages to a specific function where some action is
performed- This action “Handles” the message.

Up to now we have explain how to send our own messages by using the MFC function
SendMessage( ) and PostMessage( ). Win32 programmers use the SendMessage( ) and
PostMessages( ) functions all the time. In fact, calls to many Win32 “functions are
actually macros that call a SendMessage( ) or PostMessage( ) functions. Handling event

14
Unit III Visual Programming

messages is a bit more involved than what we lead you to believe in section 4.1 and
subsequent sections.

Modeless Dialogs: A common Use - Most MFC books discuss the SendMessage( )
function because it is necessary for programming modeless dialog boxes. However the
SendMessage( ) and PostMessage ( ) function have other uses. Consequently, we
consider them in a more general setting.

Notification Messages From Object We illustrate how an object can generate a


notification message. In effect the notification message” will notify a window that a
particular event occurred within the object.

Messages: We have been dealing with messages using MessageBox( ) functions and Up
to this point we have needed only a limited understanding of what messages specifically,
a Message describes some events. A message gets routed to a message map associated
with a window. From there the messages causes a function to be executed. Some
message handling functions have parameters that describe the details of the message.

2.1 THE STRUCTURE OF MESSAGE

A windows message is actually a structure that looks like this

Typedef struct tagMSG


{
HWND hwnd;
UINT message;
WPARAM wParam;
L PARAM lParam;
DWORD time;
POINT pt;
} MSG;

Meaning of Each field

hwnd - This handle field identifies the window to which the message is directed
message - This is a number that merely identifies the message.
wParam - This is a Win 32 message Parameter.
lParam - This is another win 32 bit message parameter
time - This is the time when the message was put in the message “queue”
2.2 PROCESSING A MESSAGE

When a “windows Procedure” receives a message the first thing it has to do is decide
what type of message it is. So the processing in a win 32 Program begins like this

Switch( MSG )
{

15
Unit III Visual Programming

case Wh_CREATE:
// process the create msg
break;
case WM_PAINT
// process the paint msg
break;
case WM_LBUTTONNDOWN;
// process this message
break;
......
......
One of the major annoyances with Win32 Programming is that important information
describing the message is encoded in the wParam and lParam parameters for many
messages. These parameters have be “broken apart” to get at the information.

The PostMessage( ) Function

When too many customers want to check out their groceries at the same time, some
customers will have to stand around waiting in line. The line of waiting people is often
called a “queue”.
There are two facts about “posted” messages:
1. Posted messages get put into a queue if the window is busy processing a previous
message.
2. Posted messages are processed only when there are no “Sent messges waiting to
be processed. In effect, “Sent messages are a priority”.

Messages that are put in the queue are those that result from user input such as
WM_KEY-DOWN, WM_CHAR and WM_LBUTTONDOWN messages. Other
message like WM_TIMER and WM_PAINT are also “posted” to the queue.

For our own messages, we can either Send them or Post them.

Menu Item Send / Post

Notice that when you select menu item Test Send/Post” It invokes the OnTest ( )
function. The interesting part of this function is the sequence of the statements:

this->SendMessage ( WM_SAY_SOMETHING,4,(LPARAM)ps1);
this->PostMessage ( WM_SAY_SOMETHING,2,(LPARAM)ps2);
this->SendMessage ( WM_SAY_SOMETHING,3,(LPARAM)ps3);

I have chosen the strings S1,S2 and S3 in such a way that the output clearly shows
the Posted message is after the second Sent Message

3. DOCUMENT – VIEW ARCHITECTURE

16
Unit III Visual Programming

VC++ introduced another graphical application that is used to illustrate methods to


handle a more involved document objects. Our simple application data has been located
in either CmainFrame object or the CchildView Object. Therefore one class contained
application data and corresponding functions and user input or output data a related
functions.

Logically speaking two very different kinds of member data and different member
function should be separated. For Larger demonstration programs we have incorporated
our application data into a class object. This is precisely the purpose of the MFC
Document / View architecture. This was first introduced in MFC 2.0 in 1993.

The Following diagram illustrates the major classes involved in the Document / View
architecture. As you read on I think you will find it helpful to refer back to this diagram
as a quick way to put the various relationships into perspective. Below we describe some
of these objects

Title
CFrameWnd Frame Work
M_wndStatusBa Menu
ToolBar
CFrameWnd
CViewObject
Messages
Status Bar
CxxxDocObject
CxxxViewObject KeyBoard
Member vars
MP_mStr OnDraw( )
Member function
ChangeTo( ) OnChar( )
DisplayDoc( )
Onl_ButtonDown( )
Virtual Fucntion
Virtual Fucntion
CDocument
CView

Classes in the Document / View Architecture

CmainFrame is a container Object

The CmainFrame Object acts as a container for the menu, toolbar, status bar,
and Cview Object. As the mainframe windows is resized, the CmainFrame object adjusts
the sizes of the windows it contrains and we will make modification to the CmainFrame
Object.

The Doc and View classes are derived classess

17
Unit III Visual Programming

Since our document and view classes are derived from Cdocument and Cview,
respectively, We inherit functions from these two classes. Some functions we use as
they are defined in he base class. Other functions – the virtual functions – exist so that
we can provide our own implementation for these functions. As you see, the MFC
Frame work makes frequent call to virtual functions.

Cview is the interface Between the User and the Document

User input is sent via event messages to the Cview object. The Cview object will
then invoke the appropriate document object member functions to perform the
appropriate actions the Cview object accesses the document object with a pointer the
named Pdoc.

Saving a Document

This topic explain that, How the program is being saved as document. We have a
program to do the above process. This program is similar to the general document
program. It has a few small but important changes. Before you read about these
changes, you should run the program .

Notice that you can now save and retrieve the document data. All the file menu
items – New, Open, Save , Save As – Work!. In the open dialog Box , You can see the
files I have created and saved with this program: First,STr, Second.Str. Try it for
yourself. When we use the Document / View Architecture we inherit much functionality.
This is clearly evident when you run this program .

Important Cdocument Function

Serializing the Document Object

The key to saving your application data is to serialize your document object. To
serialize our simple document, we add the two statements illustrated in the
Doc::Serialize( ) functions.

The AppWizard automatically includes the Serialize ( ) function in the Document


class. It assumes that every program will want to save its document. So there it is; just
add your code. Of Course, there are other virtual functions which not so commonly used.
If you want to one of these user the ClassWizard to find the function and make the
insertion.

Cmodified ( TRUE or FALSE)

This is an inherited function from Cdocument. We do not redefined it; we just


invoke it. Here is how help describes the functions. Call this function after you have
made any modifications to the document. By calling this function consistently you

18
Unit III Visual Programming

ensure that the framework prompts the user save changes before closing a document. To
mark a document as clean call this function with a value of FALSE.
OnNewDocument

The AppWizard also expects every program to redefine this virtual function, so it
adds it to the document class, Here is how help describes this function: “Called by the
framework as part of the Fie New command. The default implement of this function calls
the Deletecontents( ) member function to ensure that the document is empty and then
marks the new document is empty and then marks the new document as clean. Override
this function to initialize the data structure for a new document. You should call the base
class version of this function from your override. For our document, what does it mean
to begin with an empty document? Probably an empty string, at some point.

Notice that my Doc::OnNewDocument( ) does call the base class


OnNewDocument( )

DeleteContent( )

DeleteContents ( ) is not usefull in this program. But in programs with a


dynamic data structure, it is absolutely necessary, Here is how help describe the function.
Called by the framework to delete the document’s data without destroying the
Cdocument object itself. It is called just before the document is to be destroyed. It is
also called to ensure that a document is empty before it is reused. Call this function to
implement an “Edit Clear All” or similar command that deletes all of the document’s
data.

On Open Document( )

“Called by the framework as part of the File Open Command. The default
implementation of this function opens the specified files; calls the Delete Contents( )
member function to ensure that the document is empty; calls Cobject::Serialize( ) to read
the content of the file and then marks the document as clean. Override this function if
you want to use something other than the archive mechanism or the file mechanism.

Other Useful Cdocument Functions

Here are some other CDocument Functions you might find useful:

IsModified( ) , SaveModified( ), GetTitle ( ) , GetPathName ( )

4. MOUSE AND KEY BOARD EVENTS

It is no surprise that the mouse icon moves when we move the mouse. However,
we can also move the mouse to a specific position with code. The mouse quite a familiar
device is a pointing device with one or more buttons. It is always possible to add a

19
Unit III Visual Programming

keyboard interface to duplicate mouse functions, but it is not possible to substitute the
latter’s functions. In windows programming environment, mouse has become an
indispensable input device. All windows based applications must provide support for
handling mouse. Physically mouse cursor is a small bitmap image that is displayed and
erased at various position to give the illusion of movement. Windows header file uses
LBUTTON, MBUTTON and RBUTTON for the left, middle and right buttons of the
mouse. The function, which determines whether the mouse is installed, is
GetSystemMetrics function.

GetSystemMetrics(SM_MOUSEPRESENT);

The function returns TRUE if the mouse is installed and FALSE otherwise. To
determine the number of buttons the function GetSystemMetrics is used with
SM_CMOUSEBUTTONS:

GetSystemMetrics(SM_CMOUSEBUTTONS);

Mouse Messages

A window procedure receives mouse messages whenever the mouse passes over the
window even if the window is inactive. On moving the mouse, the window procedure
receives WM_MOUSEMOVE message.

Message Description
WM_LBUTTONDOWN Left Button Pressed
WM_RBUTTONDOWN Right Button Pressed
WM_MBUTTONDOWN Middle Button Pressed
WM_LBUTTONUP Left Button Released
WM_RBUTTONUP Right Button Released
WM_MBUTTONUP Middle Button Released
WM_LBUTTONDBLCLK Left Button double Clicked
WM_RBUTTONDBLCLK Right Button double Clicked
WM_MBUTTONDBLCLK Middle Button double Clicked

The above table gives the meaning of the mouse messages received.

Tracking a Mouse

Tracking allows the user to move the mouse cursor in a window. All mouse messages
are processed in the WndProc function. Some of the functions associated with the mouse
movement are:

1. Line to
2. MoveToEx

20
Unit III Visual Programming

3. ClientToScreen
4. SetCapture
5. ReleaseCapture

Moving the Mouse Icon

There is a function called SetCursoPos(x,y) that lets us set the position of the cursor.
However, there is a catch. If we want to position the cursor to point in our client
window. We cannot just substitute the 5 and 8 for the x and y in the SetCursoPos
function. We must use screen coordinates, not client window coordincates.

The following figure illustrates client coordinates a screen coordinates. Notice that the
client window coordinates(5,8) correspond to the screen coordinates(22,20) because of
the way the client window is positioned on the desktop.

Screen - Desktop
Screen Coordinates
Of Points(17,12) Client Window Coordinate
(5,8)

(22,20) Client Window

Fortunately, there is a function that converts from client coordinates to screen co-
ordinates. Here is how we position the cursor to the point we have found to be the closest
to mouse point.

Other Program functions

Right Mouse Button Up event provides us with a new point. Since the index position
was held in a global variable called ldxPos, we now make the replacement.

Capturing the Mouse: SetCapture()

Suppose we’ve selected a point with our right mouse button down.” Then we move
outside the window and release the button. The window will never get the “right mouse
button up message” because the message will be sent to another window, perhaps the
desktop and the selected point will not be changed.

We can have our window receive the “RbuttonUp” message no matter where the event
occurs. All we have to do is add the SetCapture and :: ReleaseCapture function in our

21
Unit III Visual Programming

mouse event handlers as we have done in our code. To appreciate this, run the program
and try pulling one of the ShapePts ourtside the window.

5. INTRODUCTION MDI ENVIRONMENTS

The Multiple Document Interface is an user interface specification. To be


precise, it describes how to implement an user interface that permits the user to work on
multiple objects within a single application. The objects can all be of the same type like
multiple documents being opened in a word processor application or of different types
like spreadsheets, charts, and macro sheets opened in Excel. The objects can also be of
different types like a desktop application, which allows the opening of a word processor
and a spreadsheet application. The application the MDI specification behaves very much
like windows managing the application windows on the screen. MDI supported by
windows makes the task of building a MDI application easier without which a large
amount of code has to be written to follow the MDI specification.

Basic steps in the creation of MDI Application

It is imperative for the user to comprehend the behaviour of MDI application


before dealing with the sequence of actions involved in its creation

Behaviour of MDI application : The MDI application conforms to the following


requirements:

Minimizing an object or document results in an icon of the document being


displayed at the lower part of the screen. When the application itself is minimized it hides
the document windows and displayed as an icon in the task bar or at the lower part of the
screen.

MDI applications mostly use accelerator keys. The main application window
whereas the Alt key applies to the application window. For example, Ctrl+F4 closes the
document application and Alt+F4 closes the application window.

The document window does not have a menu bar. Instead, the menu bar on the
main application window contains the menu for the currently active document. While
switching between documents the application menu bar must be changed. Items that do
not apply to the current document must not be included in the menu. When no documents
are open, the menu should contain those items that always apply.

All menu bars should contain the window pop-up menu. The pop-up contains Tile
and Cascade selections and other items. The Tile option rearranges all the non-
minimized documents one over the other. The cascade option rearranges the non-
minimized documents by displaying them starting from the left corner like stacked index
cards. In both cases the active document is placed on the top.

22
Unit III Visual Programming

When a document is maximized, the title of that document is appended to the text
in the application window’s title bar. The document window’s system icon is inserted at
the beginning of the application window menu bar. Windows also appends an icon at the
right of the menu bar to restore the document window.

The active document window is highlighted to indicate that it is active. The


highlighting is removed when the user changes to a different document window.

When creating a new document window there is no need to close the existing
document windows. The new document window coexists with the previously opened
document windows.

Basic Steps in the Creation of a MDI Application

The MDI application requires a window to interact with the user. The main
application window for an MDI application called the frame window. Normally, nothing
is displayed within the client area of the frame window. Instead, a child window called
the MDI client window or client window is created using the predefined
“MDICLIENT” window class. The client window resizes itself to fit the client area of the
frame window and provides MDI support.

The client area of the MDI client window is called the application workspace.
Finally, a document window is created whenever necessary. The document windows are
called MDI child windows or just child windows. The document windows are displayed
within the application workspace and are clipped to its boundaries.

Creating Frame Window

The frame window for a MDI application is similar to the main application
window of a conventional windows application. Calling the Create window function
creates the frame window. The window has a caption with a system menu icon, a
minimize icon and a maximize icon. It also has a menu bar and a sizing border. The
caption area and the menu area are not part of the client area.

For processing messages, a window class of the frame window has to be


registered and provided with a window function. The frame window function calls the
DefFrameProc function to process messages that are not handled by the windows
function. The DefFrameProc function processes the following messages in addition to
those normally processed by a default window function.

Message Default Action


WM_COMMAND If the control ID is one of the child window Ids, it brings that
window to the top and makes that window checked in the menu.
WM_MENUCHAR If the user presses Alt & - (minus) combination, activates the
system menu of the current MDI child window.
WM_SETFOCUS Passes the focus message to the client window that is in turn passed

23
Unit III Visual Programming

to the active MDI child.


WM_SIZE Resizes the MDI client window to fit within the client area of the
frame. This must be overridden if toolbars or status bars are
present.

Creating the client window

Calling the Create window function creates a MDI client window. A pointer can
be passed as the last parameter to a CLIENTCREATESTRUCT structure in the
Createwindow function call. The structure of CLIENTCREATESTRUCT is as given
below.

typedef struct tag CLIENTCREATSTRUCT {


HMENU hwindowMenu;
UNIT idFirstchild;
} CLIENTCTREATESTRUCT;

The hwindowMenufield contains the handle for menu item in the window pop-up
menu. The MDICLIENT class adds the title of each child window to the end of pop-up
menu. The idFirstChild field contains the child window Id that is assigned to the first
child window created. The child window Ids range from idFirstChild to idFirstchild +n-
1,where n is the current number of MDI child windows.

When the user selects one of the child window titles from the windows pop-up
menu, windows sends a wm_command message to the frame window function. The
menu ID accompanying this message indicates as to which child window needs to be
activated. The frame window function passes the WM_COMMAND message to the
active child window,which then passes the message to its default message-handling
function, the DefMDIChildproc funtion. This activates the chosen child window.

The MDICLIENT window typically fills the client area that is left over after
displaying the toolbars, status bar etc. the parent/child hierarchy for and MDI application
is given in the following figure.

Frame window

Toolbar window MDICLIENT status line


window window

document document document

Creating a child window

24
Unit III Visual Programming

A child window can be created by the following two methods. In the first method a
WM_MDICREATE message is sent to the MDI client window, ordering it to
createda child window. The MDICREATESTRUCT structure is initialized and a
pointer is passed to it. this structure contains information about the appearance of the
child window. The structure is given below.

Typedef struct tagMDICREATESTRUCT


{
LPCSTR szClass;
LPCSTR szTitle;
HINSTANCE hOwner;
int x;
int y;
int cx;
int cy;
DWORD style;
LPARAM lparam;
}MDICREATESTRUCT;

the following code segment creates a MDI child window for the hwndClient window.

mdicreate.szclass=firstchile;
mdicreate.szTitle=”I” am the first”;
mdicreate.x=CW_USEDEFAULT;
mdicreate.y=CW_USEDEFAULT;
mdicreate.cx=CW_USEDEFAULT;
mdicreate.cy=CW_USEDEFAULT;
mdicreate.style=0;
mdicreate.lParam=0;
hwndChild=(HWND)
SendMessage(hwndclient,WM_MDICREATE,0,
(LPMDICREATESTRUCT)&mdicreate);

Each distinct child window must have a registered window class with a window
function. The sxClass field of the structure specifies the child window class. The MDI
client window uses these fields while calling the createwindow function.this method is
for compatibility with Win16.
In the second method the createMDIWindow is used

HWND CreateMDIWindow
(
LPCSTR szClass,
LPCSTR szTitlle,
DWORD style,
int x,
int y,

25
Unit III Visual Programming

int cx,
int cy,
HWND hOwner,
HINSTANCE hOwner,
LPARAM lparam);

An interesting aspect of MDI child windows is that thwy do bot ghave their own
menus.All MDI windows share the same menu of the frame window.All cheld windows
stay within the boundary of the frame window. The child windows can be minimized to
an icon within the bounds of the frame. They can also be maximized to fill the entire
frame hiding all the other child windows.

A frame window function never communicates directly with the MDI child
window. Instead, the child window messages are sent to the client window. These
messages request maximizing, minimizing, creating and destroying of the child window
is actually done by the client window. Similarly, a child window does not typically
communicated directly with the frame window. For example, if the cheld window is
activated the menu on the frame eindow needs to be changed. The cheld lwindow sends a
message to the client window informing it to chage the menu on the frame window.

MDI Client window messages

If the child window needs to be affected in some way or if the stauts of the child
window needs to be inquired, the message must be sent to the client window. For
example,sending the message WM_MDUACTUVATE to the client window means that
the specific window needs to be activated. The newly activated child window receives the
WM_MDIACTIVATE message with hwnd==lParam,indicating that it is being activated.
The currently active child window receives a WM_DEACTIVATE message with
hwnd==lParam, indicating that it is being deactivated.

The MDI application message loop

The message loop for a MDI application looks different from a normal message
loop.

While(getMessage(&msg,0,0,0))
{
if(!TranslatedMDISysAceel (hwndMDIClient,&msg)&&
!TranslateAccelerator(hwndFrame,haccel,&msg))
{
translateMessage(&msg);
dispatchmessage(&msg);
}
}

26
Unit III Visual Programming

The MDI application after retriving the message from the message queue passes it
to the TranslateMDIsusAccel function.This function translates the WM_KEYDOWN
and WM_KEYUP messages, for keys corresponding to the MDI system menu
accelerators, to WM_SYSCOMMAND messages. The translated messages are sent to the
MDI client window. This window handle will be specified while calling
TranslatteMDIsusAccel function. It returns TRUE if the message was translated and
processed.

When it returns FALSE, the message loop calls the TranslateAccelerator function.

Introduction to MFC Libraries

The Microsoft Foundation Class Library 5.0 is an application framework for


writing applications for Microsoft windows and other platforms that support the Win32
Application Programming Interface. The Microsoft Foundation Class Library is an
encapsulation of a large portion of the windows API in C++ form. Library classes
represent windows, dialog boxes device contexts, common GDI objects such as brushes
and pens, controls, and other standard windows items. These classes provide a convenient
C++ member function interface to the structures in windows that are encapsulated.

A layer of additional application functionality built on the C++ encapsulation of


the windows API is supplied by the Microsoft Foundation Class Library. This layer is a
working application framework for windows that provides most of the common juser
interface expected of programs for windows, including toolbars tool bars, status bars,
printing, print preview and database support. The application framework is an integrated
collection of object-oriented software components that offer all that is required for a
generic application.

Managing Memory in MFC

One of the main features of memory management offered by MFC is the


extensive usage of Dynamic Linking Libraries. In the MS-DOS environment, an
application’s object modules are statically linked during the build program.

Microsoft Developer Studio Interface

Some of the components of the Microsoft Developer Studio, are the Graphic
Editor, the C/C++ compiler, the Resources Compiler, the Linker and the On-line Help.
To perform other operations such as programming, debugging, testing and readability of
code,a few other MDS components are offered.

Debugger : The debugger is still in the development stage and does not fix bugs.The
debugger works closely with the developer studio to save breakpoints on the disk.
Breakpoints are stops in a program where the execution of the program is halted to allow

27
Unit III Visual Programming

the programmer to debug program code. Toolbar buttons are available to toggle
breakpoints and control single-step execution.

Source Browser : In a project, when one individual takes over from another, there is
always the tedious task of reading and understanding another person’s code and classes.
The Source Browser helps us to examine an application from application from the class
or the function point of view.

Application wizard : The Application Wizard, is a code generator that creates the
working skeleton of a windows application.

Class wizard : The class wizard is a program that is accessible from the Developer
studio’s view menu. When we are in need of a new class, a new message , a new virtual
function or a message handler, the classwizard can be used to create prototypes, function
bodies and the code to link to the windows message function.

Component Gallery : This is a new feature that lets the user share large software
components among projects.

28

Vous aimerez peut-être aussi