vc++ unit 3+ unit 3.pdf · unit iii toolbars: toolbars displays a collection of easy –to –use...
TRANSCRIPT
Edited by EDUTECH
UNIT III
TOOLBARS:
Toolbars displays a collection of easy –to –use buttons that represent commands.
Steps to create a tool bar:
• Create a toolbar resource using insert and resourcemenu.
• Call the Create member function of the CtoolBar class that creates a CtoolBra object.
• Call the LoadToolbar member function of the CtoolBar class-this displays the toolbr on the
screen.
The following code creates and displays toolbar:
class tool: public CFrameWnd
{
CToolBar *tb;
int OnCreate(LPCREATESTRUCT)
{
tb = new CToolBar;
tb->Create(this);
tb->LoadToolBar(IDR_TOOLBAR1);
// the following code is to make a toolbar dockable
Edited by EDUTECH
EnableDocking(CBRS_ALIGN_ANY);
tb->EnableDocking(CBRS_ALIGN_ANY);
DockControlBar(tb);
return 1;
}
STATUS BARS:
A status bar is a control bar with a row of text output panes, or indicators. Like toolbar , the
status bar is embedded in its parent frame windows and is constructed automatically as well.
The CstatusBar class of MFC deals with the status bar. A CstatusBar object is a control with a
row of text output panes or indicators.The following code craets a status bar with four panes
UINT indicators[]={0, ID_INDICATOR_NUM, ID_INDICATOR_CAPS, ID_INDICATOR_SCRL};
class tool : public CFrameWnd
{
CToolBar *tb;
CStatusBar *sb;
int OnCreate(LPCREATESTRUCT)
{
Edited by EDUTECH
tb = new CToolBar;
tb->Create(this);
tb->LoadToolBar(IDR_TOOLBAR1);
// the following code is to make a toolbar dockable
EnableDocking(CBRS_ALIGN_ANY);
tb->EnableDocking(CBRS_ALIGN_ANY);
DockControlBar(tb);
sb = new CStatusBar;
sb->Create(this);
sb->SetIndicators(indicators,sizeof(indicators)/sizeof(int));
return 1;
}
}
CToolBar:
A tool bar is a control bar with a row of bitmap buttons that may include separators. Two styles of
buttons are supported : push buttons and check box buttons. Radio group functionality can be built with
check box buttons and ON_UPDATE_COMMAND_UI.
All the bitmap buttons in the toolbar are taken from the bitmap. This bitmap must contain one image or
glyph for each button typically the order of the images/glyphs in the bitmap is the same order they will
be drawn on the screen.
Each button must be the same size. The default size is the standard 24x22 pixels. Each image/glyphs
must be the same size and must be side-by-side in the bitmap. The default image/glyph size is 16x15
Edited by EDUTECH
pixels. Therefore, for a toolbar with 10 buttons (using standard sizes), you need a bitmap that is 160
pixels wide and 15 pixels high.
Each button has one and only one image/glyph. The different button states and styles (for example,
pressed, up, down, disabled, disabled down, indetermine ) are algorithmically generated from that one
image/glyph.
CCmdUI Support for CToolBar:
The way toolbar buttons are always updated is through the ON_UPDATE_COMMAND_UI mechanism.
On idle time, the toolbar will call the ON_UPDATE_COMMAND_UI handler with the command ID of that
button. ON_UPDATE_COMMAND_UI is not called for separators, but it is called for pushbuttons and
check box buttons.
The ON_UPDATED_UI handler can call:
Enable: To enable or disable the button. This works equally for pushbuttons and check box buttons.
SetCheck: To set the check state of a button. Calling this for a toolbar button will turn it into a checkbox
button. StetCheck takes a parameter which can be 0 (not checked), 1 (checked) or 2 (indeterminate)
SetRadio: shorthand for SetCheck.
Checkbox buttons are “AUTO” checkbox buttons that is, when the user presses them they will
immediately change state. Checked is the down or depressed state. There is no built-in user interface
way o change a button into the “indeterminate” state; that must be one through the code.
The customization APIs will permit you to change the state of a given toolbar button preferably you
should change the state of a given toolbar button, preferably you should change these states in the
ON_UPDATE_COMMAND_UI handler for the command the toolbar button represents. Remember, the
idle processing will change the state of toolbar buttons with the ON_UPDATE_COMMAND_UI handler
so any changes to these states made through SetButtonStyle may get lost after the next idle.
tToolBar button will send WM_COMMAND messages like normal buttons or menu items are normally
handled by an ON_COMMAND handler in the same class that provides the ON_UPDTAE_COMMAND_UI
handler.
CToolBar::Create
BOOL Create(CWnd* pParentWnd, DWORD DWStyle=WS_CHILD | WS_VISIBLE | CBRS_TOP, UINT
nlD=AFX_IDW_TOOLBAR);
Return value NonZero if successful; otherwise 0
Parameters nParentWnd pointer to the window that is the toolbar’s parent.
Edited by EDUTECH
dwStyle The toolbar style. Additional toolbar styles supported are:
CBRS_TOP control bar is at the top of the frame window.
CBRS_BOTTOM control bar is at the bottom of the frame window
CBRS_NOALIGN control bar is not repositioned when the parent is resized.
CBRS_TOOLTIPS control bar displays tool tips.
CBRS_SIZE_DYNAMIC control bar is dynamic.
CBRS_SIZE_FIXED control bar is fixed
CBRS_FLOATING control bar is floating.
CBRS_FLYBY status bar displays information about the button
CBRS_HIDE_INPLACE control bar is not displayed to the user
nID The toolbar’s child-window ID
objects of the class CToolBar are control bars that have a row of bitmapped buttons and optional
separators. The buttons can act like pushbuttons, check-box buttons, or radio buttons. CToolBar objects
are usually embedded members of frame-window objects derived from the class CFrameWnd or
CMDIFrameWnd.
CToolbar Class Member:
Construction
CToolBar Constructs a CToolBar object
Create Create the Windows toolbar and attaches it to the CToolBar object.
CreateEx Creates a CToolBar object with additional styles for the embedded CToolBarCtrl
object
SetSizes Sets the sizes of the buttons and their bitmaps.
SetHeight Sets the height of the ToolBar
LoadToolBar Loads a toolbar resource created with the resource editor
LoadBitmap Loads the bitmap containing bitmap-buttton images
SetBitmap Sets a bitmapped image.
SetButtons Sets button styles and an index of button images within the bitmap
Edited by EDUTECH
Attributes
CommandToIndex Returns the index of a button with the given command ID.
GetIemID Return the command ID of a button or separator at the given Index
GetItemRect retrieves the display rectangle for the item at the given index
GetButtonStyle Sets the style for a button
SetButtonInfo Sets the ID, style, and image number of a button
GetButtonText Retrieves the text that will appear on a button
SetButtonText Sets the text that will appear on a button
GetToolBarCtrl Allows direct access to the underlying common control
Q. Write a program which can show and hide a toolbar.
#include<afxwin.h>
#include “resource.h”
#include<afxext.h>
Class myframe : public CframeWnd
{
Public:
CtoolBar t1;
Int visible;
Myframe()
{
Create(0,”Title”,WS_OVERLAPPEDWINDOW,rectDefault,0,MAKEINTRESOURCE(IDR_MENU1));
Visile=0;
}
Edited by EDUTECH
}
Int OnCreate(LPCREATESTRUCT l)
{
t1.Create(this,WS_CHILD | CBRS_TOP | CBRS_RIGHT | CBRS_LEFT | CBRS_BORDER_BOTTOM |
CBRS_BORDER_TOP | CBRS_BORDER_RIGHT | CBRS_BORDER_LEFT);
t2.LoadToolBar(IDR_TOOLBAR1);
return 0;
)
Void showtooolbar()
{
If(visible==1)
{
MessageBox(“Tool Bar Visible”);
Else
{
ShowControlBar(&t1,TRUE,FALSE);
Visible=1;
}
}
}
void hidetoolbar()
{
if(visible==0)
MessageBox(“Tool Bar is hidden”);
else
{
Edited by EDUTECH
ShowControlBar(&t1,FALSE,FALSE);
visible=0;
}
}
DECLARE_MESSAGE_MAP()
};
BEGIN _MESSAGE_MAP(myframe,CFrameWnd)
ON_WM_CREATE()
ON_COMMAND(101,showtoolbar)
ON_COMMAND(102,hidetoolbar)
END_MESSAGE_MAP()
class myapp: CWinApp
{
public:
int InitInstance()
{
myframe *f;
f=new myframe;
f->ShowWindow(1);
m_pMain Wnd=f;
return 1;
}
};
myapp a;
Edited by EDUTECH
The toolbar attached to a window can be hidden or shown by calling the CFrameWnd::ShowToolBar()
function. The first parameter is passed to this function is a pointer to the toolbar to be shown or hidden.
The second parameter passed, if TRUE displays the toolbar, whereas, if FALSE, hides it. The third
parameter is set to TRUE if you want some delay in showing the toolbar and FALSE if you want it to be
shown immediately.
Q. Demonstrate two toolbars with RadioButton and CheckBox features. One of the toolbars is
Dockable too. It also demonstrates how to add/remove toolbuttons dynamically.
#include<afxwin.h>
#include “resource.h”
#include<afxext.h>
#include<afxcmn.h>
TBBUTTON extrabuttonsarray[2]=
{
{4,104,TBSTATE_ENABLED,TBSTYLE_BUTTON},
{5,105, TBSTATE_ENABLED,TBSTYLE_BUTTON},
};
class myframe : public CFrameWnd
{
public :
CToolBar t1,t2;
int flag;
myframe()
Edited by EDUTECH
{
C=Create(0,”title”,WS_OVERLAPPEDWINDOW,rectDefault,0,MAKEINTRESOURCE(IDR_MENU1));
flag=0;
}
int OnCreate(LPCREATESTRUCT 1)
{
CFrameWnd :: OnCreate(1);
unsigned int barray[2];
t1.Create(this,WS_CHILD | CBRS_TOP | CBRS_RIGHT | CBRS_LEFT | CBRS_BORDER_BOTTOM |
CBRS_BORDER_TOP | CBRS_BORDER_RIGHT | CBRS_BORDER_LEFT);
t2.Create(this,WS_CHILD | WS_VISIBLE);
t2.LoadToolBar(IDR_TOOLBAR 1); //created using Resource editor….
t2.EnableDocking(CBRS_ALIGN_LEFT | CBRS_ALIGN_RIGHT);
EnableDocking(CBRS_ALIGN_ANY);
DockControlBar(&t2,AFX_IDW_DOCKBAR_LEFT);
barray[0]=101;
barray[1]=102;
t1.SetButtons(barray,2);
t1.SetButtonText(0,”One”);
t1.SetButtonText(1,”Two”);
t1.SetButtonStyle(0,TBBS_CHECKGROUP);
t1.SetButtonStyle(1,TBBS_CHECKGROUP);
t2.SetButtonStyle(0,TBBS_CHECKBOX);
t2.SetButtonStyle(1,TBBS_CHECKBOX);
return 1;
Edited by EDUTECH
}
void one()
{
MessageBox(“One”);
}
void add_remove_buttons()
{
if(flag==0)
{
CToolBarCtrl &t=t1.GetToolBarCtrl();
t.AddButtons(2,extrabuttonsarray);
flag=1;
}
else
{
CToolBarCtrl &t=t1.GetToolBarCtrl();
t.DeleteButton(2);
flag=0;
}
}
DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(myframe,CFrameWnd)
ON_WM_CREATE()
ON_COMMAND(101,one);
Edited by EDUTECH
ON_COMMAND(102,two);
ON_COMMAND(101,add_remove_buttons);
END_MESSAGE_MAP()
class myapp : public CWinApp
{
public:
int InitInstance()
{
myframe *f;
f=new myframe;
f->ShowWindow();
m_pMainWnd=f;
return 1;
}
};
myapp a;
On-Idle Processing
Before multithreaded programming concept, Windows developers used on-idle processing for
“Background” tasks such as pagination. On-idle processing is longer as important, but it’s still useful. The
application framework calls a virtual member function OnIdle of the class CWinApp, and you can
override this function to do background processing. OnIdle is called from the framework’s message
processing loop, which is actually a little more complicated than the simple
GetMessage/TranslateMessage/DispatchMessage sequence. Generally, once the OnIdle function
completes its work, it is not called until the next time the applications message queue has been
emptied. If you override this function, your code will be called, but it wont be called continuously unless
Edited by EDUTECH
there is a constant stream of messages. The base class OnIdle updates the toolbar buttons and status
indicators, and it cleans up various temporary object pointers. It makes sense to override OnIdle to
update the user Interface shouldn’t be changing.
If you do override CwinApp::OnIdle, also call the base class OnIdle. Otherwise, your toolbar buttons
won’t be updated and temporary objects won’t be deleted.
OnIdle isn’t called at all if the user is working in a modal dialog or is using a menu. If you need to use
background processing for modal dialogs and menus you’ll have to add a message handler function for
the WM_ENTERIDLE message, but you must add it to the frame class rather than the view class. That’s
because pop-up dialogs are always “owned” by the application’s main frame window, not by the view
window.
The update command UI message handlers for a op-up menu are called only when the menu os painted.
The toolbar is displayed all the time, so when are its update command UI message handlers called?
They’re called during the applications idle processing, so the buttons can be updated continuously. If the
same handler covers a menu item and a toolbar button, it is called both during idle processing nad when
the pop-up menu is displayed.
Tool Tips
i. The CToolTipCtrl class encapsulates the functionality of a ‘’tool tip control” a small pop-up
window that displays a single line of text describing the purpose of a tool in an application.
ii. A “tool” is either a window, such as a child window or control, or an application- defined
rectangular area within a window’s client area.
iii. A tool tip is hidden most of the time, appearing only when the user puts the cursor and
disappears when the user clicks a mouse button or moves the cursor off the tool.
iv. CToolTipCtrl provides the functionality to control the initial time and duration of the tool tip,
the margin widths surrounding the tool tip text, the width of the tool tip window itself, and
the background and the text color of the tool tip.
v. A single tool tip control can provide information for more than one tool
CToolTipCtrl class member
CToolTipCtrl Constructs a CToolTipCtrl object.
Create Creates a tool tip control and attaches it to a CToolTipCtrl object
Attributes
GetText Retrieves the text that a tool tip control maintains for a tool
GetToolInfo Retrieves the information that a tool tip control maintains about a tool.
SetToolInfo Sets the information that a tool tip maintains for a tool.
Edited by EDUTECH
GetToolCount Retrieves a count of the tools maintained by a tool tip control.
GetDelayTime Retrieves the initial, pop-up, and reshow durations currently set for a tool tip
control .
SetDelayTime Sets the initial, pop-up, reshow duration for a tool tip control.
GetMargin Retrieves the top left, bottom, and right margins set for a tool tip window.
SetMargin Sets the top left, bottom, and right margins set for a tool tip window.
GetMaxTipWidth Retrieves the maximum width for a tool tip window.
SetMaxTipWidth Sets the maximum width for a tool tip window.
GetTipBkColor Retrieves the background color in a tool tip window.
SetTipBkColor Sets the background color in a tool tip window.
GetTipTextColor Retrieves the text color in a tool tip window.
SetTipTextColor Sets the text color in a tool tip window.
Operations
Activate Activates and deactivates the tool tip control.
AddTool Register a tool with the tool tip control.
DelTool Removes a tool from the tool tip control.
HitTest Tests a point to determine whether it is within the bounding rectangle of
the given tool and, if so, retrieves information about the tool.
RelayEvent Passes a mouse message to a tool tip control for processing.
SetToolRect Sets a new bounding rectangle for a tool.
UpdateTipText Sets the tool tip text for a tool.
Update Forces the current tool to be redrawn.
Pop Removes a displayed tool tip window from view.
CDOCUMENT CLASS:
The CDocument class is derived from the CCmdTarget class, which is derived from the CObject
class. It represents the basic functionality of a user defined document classes. It represents the
unit of data that has to be opened when the user chooses the File Open and File Save option.
MFC’s Document View architecture is based on two assumptions – data comes from the
document and the user views and edits it through the view.
Edited by EDUTECH
The source of the data is separated from the user interface of the data.
The responsibility of reading and writing data, to and from the disk, is assigned to the
CDocument class. This class provides functions for creating, loading and saving documents.
An application can support more than one type of document ex: a spreadsheet and a text
document. To differentiate between the various documents, each document has an associated
document template. The document template specifies the resources used by the document,
depending on its type. When the user opens a document, the framework creates a view and
attaches it to the document. The framework manipulates documents using the interface
defined by CDocument, which specifies the resources used, by the document. Each document
has a pointer to its associated CDocTemplate object.
*When the user chooses a command that creates a document, the framework class upon the
document template to create the document object, its view, and the frame window that will
display the view. The document template is responsible for the coordination and creation of
the document, view and frame for the application.
The four tasks that are performed in a document’s life cycle. They are:
• Creating a new document
• Modifying the document
• Storing or Serializing the document
• Closing the document
To implement the document in the program you have to:
• Derive a class from CDocument for each type of document.
• Add member variables to store the data of each element.
• Implement member function for reading and modifying the data of the document.
Edited by EDUTECH
• Override the CObject member function Serialize to read and write data to and from the
disk.
CREATING THE NEW DOCUMENT:
In a Document –View application, the first step is to create the document. SDI applications
make use of the OnNewDocument function to create and initialize a document object. As the
document object is reusable, the default implementation of the function calls the
DeleteContents function to reset any data that might be contained in the document. The code
segment that follows illustrate the steps involved in creating a new document.
class MyCDocument:public CDocument
{
public:
DECLARE_DYNCREATE(MyCDocument)
virtual BOOL OnNewDocument()
{
if(!CDocument::OnNewDocument())
return FALSE;
return TRUE;
}
};
IMPLEMENT_DYNCREATE(MyCDocument,CDocument)
Edited by EDUTECH
OnNewDocument FUNCTION:
In the sample code, the OnNewDocument member function of the CDocument class has been
overridden. This function is invoked by the File New command of the framework. The default
implementation of this function calls the DeleteContents member function to make sure that the
document is empty. Once the document object is created, if the user chooses the File New command,
the framework makes use of this function to reinitialize the existing object instead of creating a new
one. The return value of this function specifies whether the document was opened successfully or not.
To ensure that that the framework handles the FileNew command automatically, the name of
the File New option in the menu resource should be ID_FILE_NEW.
DECLARE_DYNCREATE:
The are two ways of creating objects dynamically. One way is busy using the C++ operator to
dynamically create an object from free storage. The other way is using CRuntimeClass structure and
RUNTIME_CLASS macro.
Dynamic object creation using the second method requires the use of the
DECLARE_DYNCREATE macro in the class declaration and the IMPLEMENT_DYNCREATE macro
in the class definition. The framework makes use this feature to create objects dynamically.
Documents, views and frame window classes should support dynamic creation, as the
framework needs to create them dynamically.
Edited by EDUTECH
MODIFYING THE DOCUMENT:
Accepting data into a document is done in the CView derived class. However, the Document has to keep
track of whether the document has been modified before it is closed. To determine if a document can
be closed, the MFC framework calls the IsModified function that is a part of the CDocument class. This
function is invoked to determine whether the document has been modified since it was last saved. The
following code segment illustrates how this is done.
if(IsModified() ==TRUE)
{
AfxMessageBox (“Save changes now”, MB_YESNO);
}
The IsModified function tests the value of a modification flag, which is set when changes are
made to the document. This flag is cleared when the document is saved or a new document is
loaded. You can set the value of this flag by invoking the SetModifiedFlag as shown below:
SetModifiedFlag(TRUE);
The function takes either TRUE or FALSE as a parameter.
The Document-View framework takes care of resetting the flag after the document has been
saved.
STORING A DOCUMENT:
As mentioned earlier, The CDocument class takes care of file-related issues. The user can save a
document by either choosing the Save option or the Save As option from the File menu. When the user
Edited by EDUTECH
chooses the File Save option, the OnFileSave member function of the CWinApp class is invoked, which in
turn calls the OnSaveDocument of the CDocument class to save the data in the document.
MFC has a different approach to saving and retrieving operations. In this process the
application saves the various data structures, variables and objects used by the CDocument
object as data members into an archive.
The archive is a binary stream from where objects can be either be read from or written to. An
archive can be opened for read or write not both read and write. Archive is a replacement for a
file object, with added features. The default working OnOpenDocument function is to create
an archive object and pass it to the Serialize member function of the CDocument class . After
the document has been saved , the modification flag is reset to mark the document as
unmodified. When the user chooses the File Save AS option, a common dialog box is displayed
which attempts the name of the file in which the document is to be saved. Once the name of
the file is obtained, the same CDocument functions as with the File Save option are invoked.
CArchive CLASS:
The CArchive class encapsulates the archive object. The CArchive class allows you to save
complex objects in simple binary format on the disk. An archive object is a binary stream that is
associated with a file, and allows reading and writing data to and from the file.
The extraction (>>) and insertion (<<) operators are overloaded by the CArchive class to support
loading and strong of CObject derived classes. When a CArchive object is created, it is defined
as used either for input or for output, but never for both.
The IsStoring and IsLoading functions are used to determine whether the CArchive read and
write member functions are portable, these data types are standard across all hardware
platforms on which NT is implemented.
SERIALIZE FUNCTION :
Edited by EDUTECH
Serialization is the means by which classes that are derived from CDocument store and retrieve
data from an archive – usually a file. This ability to read and write to and from a data stream
such as a disk file is called persistence and the technique of reading and writing is called
serialization.
Actual implementation is done using the Serialize function. This function takes the address of
CArchive as a parameter. The advantage of serialization is that a persistent object can be stored
and retrieved using similar syntax, irrespective of the complexity of the internal structure of the
object. The following code illustrates this:
class MyDocument : public CDocument
{
void Serialize(CArchive& ar)
{
………………..
……………….
……………….
if(ar.IsStoring())
{
………..
………..
ar<<data;
Edited by EDUTECH
}
else
{
…………
…………
ar>>data;
}
}
};
The following code is from a word processing application, which uses arrays to store the data
keyed in by the user.
void Serialize(CArchive& ar)
{
int i,j;
if(ar.IsStoring())
{
ar.Write(&xPos,sizeof(int));
for(i=0;i<xPos;i++)
{
j=lstrlen(storage[i]);
Edited by EDUTECH
ar.Write(&j,sizeof(int));
ar.WriteString(storage[i]);
AfxMessageBox(storage[i]);
}
}
else
{
ar.Read(&xPos,sizeof(int));
for(i=0;i<=xPos;i++)
{
ar.Read(&j,sizeof(int));
ar.Read(storage[i],j);
AfxMessageBox(storage[i]);
}
yPos=j;
UpdateAllViews(NULL);
}
}
The above code stores the array of characters storage into the archive ar. The storage is a two-
dimension character array declared in the CDocument derived class. The application also writes
the number of characters keyed in by the user, into the archive. This reduces the disk space
utilized by the saved file and speeds up the saving and retrieval process.
Edited by EDUTECH
xPos stores the total number of rows stored in the file and yPos stores the number of
characters in a line of text entered by the user. The data stored in the archive includes the total
number of lines, number of characters in a line of text and the line of text. The following
functions of CArchive class can be used for reading and writing:
• Read : Reads a specified number of bytes from the archive. If the return value is less than
the number requested, the end of file has been reached.
• Write: Writes a specified number of bytes to the archive. You can use the Write member
function within your Serialize function to write ordinary structures that are contained in
your objects.
• WriteString: Use this member function to write data from a buffer to the file associated
with the CArchive object. The terminating null character (‘\0’) is not written to the file; nor
is a new line automatically written.
• ReadString: call this member function to read text data into a buffer from the file associated
with the CArchive object.
CLOSING A DOCUMENT:
When the user chooses the Close option (ID_FILE_CLOSE) from the file menu, the Document-View
framework calls the OnCloseDocument member function of the CDocument class. This function check
for unsaved changes by calling the IsModified member function. If the document object has not been
modified it was last saved, the DeleteContents function is called and the view to the document is closed.
LOADING A DOCUMENT:
Edited by EDUTECH
Loading a document that has been previously saved is also known as serialization.
This process is incorporated in the Serialize member function. To determine whether the
CArchive object is to be stored or loaded, the functions IsStoring and IsLoading are used.
CView CLASS:
The CView class provides the functionality of a user-defined view. A view attached to a document and is
the interface between the document and the user. The CDocTemplate object establishes the
relationship between the view and the document classes. When the user opens a new window, the
framework creates a new view and attaches it to the document, A view is always associated with a
document object.
Also, the view maintains a pointer to the associated document. The view is responsible only for the
display and modification of the data in the document, but not for its storage. The document supplies the
view with the necessary data. When the view needs to communicate with the document that it is
associated with, it makes use of a printer to the document. This is done by GetDocument function.
Like the document class, the view also supports dynamic creation. The application framework requires
the views be created dynamically. Therefore, the DECLARE_DYNCREATE and IMPLEMENT_DYNCREATE
macros are implemented in the code that follows:
class MyCView: public CView
{
DECLARE_DYNCREATE(MyCView)
public:
MyDocument* GetDocument()
{
return (MyDocument*)m_pDocument;
}
Edited by EDUTECH
};
IMPLEMENT_DYNCREATE(MyCView,Cview)
To create a view, you need to derive your own class from the CView class and override the OnDraw
member function. The OnDraw function is used for re-displaying all the output on the view, it is called
when the view needs to be redrawn. The OnDraw function is passed a parameter, the pointer to the
device context on which the output needs to be drawn. The application framework calls the OnDraw
function when the view needs to be displayed on any device context. Thus, if same function is reused to
display output on the screen, printer or the print preview device context.
The view class also has the function OnActivateView () which does the framework call when a view is
activated or deactivated.
The OnDraw( ) member function displays the contents of the linked list or array. The linked list is
populated by the characters that the user keys in from the keyboard. The data that is entered by the
user is stored in the linked list in the OnChar function.
OnChar is invoked by the message map entry, WM_CHAR.
The following is the code segment for displaying and accepting data.
MyCDocument* GetDocument()
{
return (MyCDocument*)m_pDocument;
}
void OnDraw(CDC *pDC)
{
MyCDocument* pDoc = GetDocument();
int xLoc, yScreenLoc;
TEXTMETRIC tm;
pDC->GetTextMetrics(&tm);
Edited by EDUTECH
xLoc=yScreenLoc=0;
for(xLoc=0;xLoc<=xPos;xLoc++)
{
if((xPos ==0)&&(yPos ==0))
return;
pDC->TextOut(0,yScreenLoc,pDoc->storage[xLoc]);
yScreenLoc+=tm.tmHeight;
}
}
void OnChar(UINT nChar,UINT nRepCnt, UINT nFlags)
{
CClientDC d(this);
MyCDocument *pDoc;
CString str;
int width;
pDoc = GetDocument();
if(nChar == 13)
{
TEXTMETRIC tm;
d.GetTextMetrics(&tm);
col+=tm.tmHeight;
row=0;
xPos++;
yPos=0;
pDoc->storage[xPos][yPos]='\0';
}
else
Edited by EDUTECH
{
str=(TCHAR)nChar;
d.TextOut(row,col,str);
d.GetCharWidth(nChar,nChar,&width);
row+=width;
pDoc->storage[xPos][yPos]=(char)nChar;
yPos++;
pDoc->storage[xPos][yPos]='\0';
}
CView::OnChar(nChar,nRepCnt,nFlags);
}
void OnInitialUpdate()
{
CView::OnInitialUpdate();
row=col=0;
xPos=yPos=0;
}
DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(MyCView,CView)
ON_WM_CHAR()
END_MESSAGE_MAP()
IMPLEMENT_DYNCREATE(MyCView,CView)
GetDocument Function:
Edited by EDUTECH
Every view is associated with only one document. When a view needs to communicate with the
document with which it is associated, it needs to use the GetDocument function. This function is used to
get a pointer to the view’s document, which allows you to call the member functions of the CDocument
derived class.
OnDraw FUNCTION:
The OnDraw function is called by the framework to render an image of the document on the screen.
There is no default implementation for this function. This function, therefore, has to be overridden in
the CView derived to display the data of the document in the view associated with the document. In our
example, we have displayed the contents that have been stored in the document object in the array
named storage. The above program displays one line from the array, increments the Y coordinate by the
average height of the characters, this process continues for all the rows in the array.
OnChar FUNCTION:
The OnChar function in the example takes care of accepting a value entered by the user stores it in the
array storage of the CMyDocument class and simultaneously displays it on the screen. In order to
achieve this, a message map entry for the message WM_CHAR is made. The function also uses the
TEXTMETRIC structure to determine the width and height of the character entered, this is required for
positioning the characters at the appropriate distance from each other. The X and Y coordinate positions
are also calculated using the width and height of characters in the current font. This function also places
the NULL terminator at the end of the string.
OnInitialUpdate FUNCTION:
This function is called by the framework after the view is first attached to the document. You can
override this function to perform initialization. This function is overridden to initialize the variables.
Edited by EDUTECH
UpdatallViews FUNCTION:
After the file has been serialized for reading it has to be displayed in the view, this can be done by
forcing the OnUpdate function of the CView class. The OnUpdate function of the view is invoked
automatically by the framework when the associated document object is modified. The default
implementation of the OnUpdate function in the CView classes invalidates the view and forces an
OnDraw member function to be executed. The OnDraw function will re-display the contents of the
document.
In case of an MDI application, the user can open the same document in multiple view windows. Also,
The user can view different portions of the document. Thus the user can modify the document in one
view notifying the other view, the program should take care of such situations and call the
UpdateAllViews function to refresh the display of all views to this document.
CWinAPP Class:
The CWinApp class is the base class from which a Windows application object is derived. Each
application can only contain one class derived from the CWinApp class. When you derive a class from
CWinApp , The InitInstance member function needs to be overidden. The code segment that follows
illustrates the implementation of this class with respect to a SDI application:
class MyCWinApp:public CWinApp
{
public:
int InitInstance()
{
Edited by EDUTECH
CSingleDocTemplate *DocTemplate;
CRuntimeClass *Docptr,*Frameptr,*Viewptr;
Docptr=RUNTIME_CLASS(MyCDocument);
Frameptr=RUNTIME_CLASS(CFrame);
Viewptr=RUNTIME_CLASS(MyCView);
DocTemplate= new CSingleDocTemplate(IDR_MENU1,Docptr,Frameptr,Viewptr);
AddDocTemplate(DocTemplate);
CCommandLineInfo cmdInfo;
ParseCommandLine(cmdInfo);
if(!ProcessShellCommand(cmdInfo))
return FALSE;
return TRUE;
}
DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(MyCWinApp , CWinApp)
ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew)
ON_COMMAND(ID_FILE_OPEN,CWinApp::OnFileOpen)
END_MESSAGE_MAP()
Edited by EDUTECH
MyCWinApp a;
The InitInstance function registers a Document Template, creates a blank document from the
registered template and creates a blank view for the document.
CSingleDocTemplate:
The Document-View architecture is held together by document templates. The CSingleDocTemplate
class is derived from the CDocTemplate class and is used to define a document template that
implements the SDI. A SDI application uses the main frame window to display the view for a document.
In order to register a document template, you need to create an instance of CSingleDocTemplate and
call the AddDocTemplate function.
AddDocTemplate FUNCTION:
This member function of the CWinApp class is invoked to add a document template to the list of
document templates that the application maintains. The application a double linked list of registered
document templates.
CRuntimeClass STRUCTURE:
Edited by EDUTECH
The classes that are derived from the Object class and use dynamic runtime information make use of
this structure to hold the runtime type information. Each class in the MFC hierarchy is associated with a
CRuntimeClass structure that you use to obtain information about an object or its base class at run
time. The ability to determine the class of an object at run time is useful when extra type checking of
function arguments is needed, or when you write special purpose code based on the class of an object.
RUNTIME_CLASS Macro:
The RUNTIME_CLASS macro is used to get the runtime class structure. This macro returns a pointer to a
CRuntimeClass structure for the specified class. Classes derived using DECLARE_DYNCREATE macro
pointers to the CRuntimeClass structure.
Edited by EDUTECH
MULTIPLE DOCUMENT INTERFACE:
The MDI is a design specification of the Windows operating system that defines a user interface for
applications that enable the user to work with more than one document at the same time.
MFC provides classes that make programming MDI application easy and simple. MDI
applications allow multiple document frame windows to be open in the same instance of an
application. An MDI application has a window within which multiple MDI child windows can be
opened, each containing a separate document. In some applications , the child windows can be
different types, such as a chart windows and spreadsheet windows.
Windows in an MDI Application:
An MDI application has three kinds of windows:
• A frame window.
• A MDI client window.
• Number of child windows.
The frame window is like the main window of the application. It has a sizing border, a title bar , a
Window menu , a minimize button, and a maximize button. The application must register a window class
for the frame window and provide a class or a window procedure to support it.
An MDI client window is a child window of the frame window. It serves as the background for
child windows. It also provides support for creating and manipulating child windows. The MDI
client window is referred to as Document Frame window.
The Child window displays a view to a document . It is always restricted to the frame window. A
child window cannot be dragged outside the frame window. Child windows have the frame
window as their parent.
Edited by EDUTECH
USING APP WIZARD TO CREATE MDI APPLICATIONS:
The AppWizard can be used to generate MDI applications:
The AppWizard generates code for the following classes.
• CMFC5App – Encapsulates the application object, template creation, derived
from CWinApp
• CMainFrame—Acts as the container for the toolbar, status bar & the child
window, derived from CMDIFrameWnd.
• CChildFrame-Frames the view of a document.
• CMFC5Document-The only difference in the code generated by AppWizard for
SDI and MDI applications is, the new class derived from CMDIChildWnd class that
is generated for framing the view. Also registration of the template in AppWizard
for SDI and MDI applications is as follows:
CMultiDocTemplate* pDocTemplate;
pDocTemplate = new CMultiDocTemplate(
IDR_MAINFRAME,
RUNTIME_CLASS(CMFC5Doc),
RUNTIME_CLASS(ChildFrame), // main SDI frame
window
RUNTIME_CLASS(CMFC5View));
AddDocTemplate(pDocTemplate);
RELATIONSHIP BETWEEN MFC OBJECTS:
Edited by EDUTECH
To understand the relationship between the various MFC objects in an MDI Document-View architecture
based application, consider a running MDI application with an open document, a view to the document
and a frame window with the menu, toolbar and status bar. In this application.
• A document keeps a list of the views of that document and a pointer to the
document template that created the document.
• A view keeps a pointer to its document and is a child of its parent frame window.
• A document frame window keeps a pointer to its current active view.
• A document template keeps a list of its open documents.
• The application keeps a list of its document templates.
• Window keeps track of all open windows so it can send messages to them
These relationships are established during document/view creation. The table below list the
methods by which on object can gain access to another:
Form Object How to access other objects
Document GetFirstViewPostion and GetNextView to
access the document’s view list, stored in
the m_viewList member variable.
View GetDocument to access the associated
document.
GetParentFrame to access the frame
window
Document Frame Window Call GetActiveView t get the current view.
Call GetActiveDocument to get the
document attached to the current view.
Edited by EDUTECH
Serialization
1) Serialization is a process by which the object writes a record of itself to a persistent storage
medium such as disk file and reloads itself by reading the record back. 2) Serialization lets your data objects persist from one program run to another by storing the
content of the objects in a file. 3) The basic idea of serialization is that an object should be able to write its current state, usually
indicated by the value of its member variables, to persistent storage. 4) Serialization handles all the details of object pointer and circular references to objects to object
that are used when you serialize an object. 5) A key point is that the object itself is responsible for reading and writing its own state. 6) Thus for a class to be serializable, it must implement the basic serialization operations. 7) Serialization is an important concept in MFC programming because it is the basic for the
framework’s ability to open and save documents in document/view application. 8) MFC supplies built-in support for serialization in the class CObject. 9) Thus all classes derived fro CObject can take advantage of CObject’s serialization protocol. 10) MFC uses an object of CArchive class as an intermediary between the object to be serialized and
the storage medium. 11) This object is always associated with a CFile object, from which it obtains the necessary
information for serialization, including the file name and whether the requested operation is a
read or write. 12) The object that performs the serialization operation can use the CArchive object without regard
to the nature of the storage medium. 13) As data is serialized to an archive, the archive accumulates the data until its buffer is full. 14) It reads data from the buffer to your deserialized object.
Serialization: Making A Serializable class
For an object to support serialization, it must be created from a serializable class. The five steps required
to make a class serializable are as follow:
a) Derive your class from CObject (or from some class derived from CObject). The basic
serialization protocol and functionality are defined in the CObject class. By deriving your class
from CObject (or from a class derived from CObject) you gain access to the serialization protocol
and functionality of CObject.
b) Override the base class’s serialize () member function with one that serializes the derived class’s
data member.
c) In the class declaration, call MFC’s DECLARE_SERIAL macro. This macro accepts just one
parameter: the name of the class for which it is being invoked.
Edited by EDUTECH
d) Add a zero-argument constructor to the class. MFC requires this constructor when it re-creates
your objects as they are deserialized (loaded from disk) The deserialization process will fill in all
member variables with the values required to re-create the object.
e) In the class implementation, call the IMPLEMENT_SERIAL macro. The first two argument to the
macro are the name of the class and the name of its immediate base class. The third argument
to this macro is a schema number. The schema number is essentially a version number for
objects of the class. The MFC serialization code checks the schema number when reading
objects into memory. If the schema number of the object on disk does not match the schema
number of the class in memory, MFC a throws CArchiveException, preventing your program
from reading an incorrect version of the object.
Serialization: Serializing An object
Once we have built a serializable class, we can serialize objects of that class to and from a file via a
CArchive object. A CArchive object provides a type-safe buffering mechanism for writing or reading
serializable objects to or from a CFile object. A given CArchive object either stores(writes serializes) data
or loads (reads, deserializes) data, but never both. Serializing on object is a three step process:
(a) Construct a CFile object and open the file the serializable object will be read from or written to.
(b) Create a CArchive object, passing its constructor a pointer to the CFile object created in (a) and a
CArchive::load parameter if data is being read and CArchive::store if data is being written.
(c) Call the object’s Serialize() function and pass it a reference to the CArchive object.
Document View Architecture
The Document – View architecture as implemented in MFC acts as a
framework for developers, doing the most of the work in the
background, like message processing, displaying common dialog boxes
for menu item processing. MFC’s Document View architecture provides the skeleton framework for developing applications, such as editors, file
viewers and database query front ends, that manage disk based data. The Document View architecture
allows a single type of data to be made available in multiple formats to the user. As the name suggests,
the Document View architecture adds two new objects to MFC programs – the document and view.
In fact, the Document-View architecture separates programs into four main classes:
Edited by EDUTECH
• A document class derived from CDocument. • A view class derived from CView.
• A frame window class derived from CFrameWnd
• A application class derived from CWinApp.
Each class plays a specific role in a Document –View application.
The document and the view together form the basis of the application framework. The
document is a data object. All user interactions during an editing session, like in a word
processor, are with the document. The document is responsible for the application’s data. It is
the data source and there is no limitation to the amount of data that the document can handle.
Irrespective of the source, data management encapsulated within the document object. The
view, on the other hand, provides a visual display in a window or a printed page – of the data to
the user. It handles the interaction between the document and the user. The frame class
contains the view and other menu bars and tool bars. The application class is responsible for
starting the application and interacting with Windows.
The frame and view are visual components and application and document are non-visual
components. Non visual components cannot receive messages but can respond to the
WM_COMMAND messages
FEATURES OF DOCUMENT VIEW ARCHITECTURE:
The most important feature of the document view architecture is the manner in which it handles and
displays data. Both these activities are handled separately. Both the operations are encapsulated in two
different types of objects. Separating the data from the user interface allows each of these classes to
concentrate on performing one job. Interface is defined for interaction with other classes in the
application.
Edited by EDUTECH
The common Document View actions for handling file operations like selecting, opening and
closing are handled entirely by the framework.
Therefore, less time is spent on writing code for these functions and more time can be spent on
application. Print Preview is another important feature of this architecture. MFC’s built in
support saves time and effort required to code the print preview feature of a program.
One of the advantages of the Document View architecture is that it divides the work of a
Window’s program into well-defined categories. Most classes fall into one of the four
categories:
• Controls and other user interface elements related to a specific view.
• Data and data handling classes belonging to a document.
• Toolbar, status bar and menu bar handling interaction between the application and
Windows.
• Classes derived from CWinApp which handle interaction between the application and
Windows.
There are two basic types of Document View applications – Single Document Interface (SDI) and
Multiple Document Interface (MDI) applications. SDI applications support a single type of
document and a single view. Only one document can be opened at any point of time. Views are
normally displayed inside a frame window. In as SDI application, the frame window is also the
main frame on the other window for the application. A MDI application, on the other hand,
supports multiple documents.
CDOCUMENT CLASS:
Edited by EDUTECH
The CDocument class is derived from the CCmdTarget class, which is derived from the CObject
class. It represents the basic functionality of a user defined document classes. It represents the
unit of data that has to be opened when the user chooses the File Open and File Save option.
MFC’s Document View architecture is based on two assumptions – data comes from the
document and the user views and edits it through the view.
The source of the data is separated from the user interface of the data.
The responsibility of reading and writing data, to and from the disk, is assigned to the
CDocument class. This class provides functions for creating, loading and saving documents.
An application can support more than one type of document ex: a spreadsheet and a text
document. To differentiate between the various documents, each document has an associated
document template. The document template specifies the resources used by the document,
depending on its type. When the user opens a document, the framework creates a view and
attaches it to the document. The framework manipulates documents using the interface
defined by CDocument, which specifies the resources used, by the document. Each document
has a pointer to its associated CDocTemplate object.
*When the user chooses a command that creates a document, the framework class upon the
document template to create the document object, its view, and the frame window that will
display the view. The document template is responsible for the coordination and creation of
the document, view and frame for the application.
The four tasks that are performed in a document’s life cycle. They are:
• Creating a new document
• Modifying the document
• Storing or Serializing the document
• Closing the document
To implement the document in the program you have to:
Edited by EDUTECH
• Derive a class from CDocument for each type of document.
• Add member variables to store the data of each element.
• Implement member function for reading and modifying the data of the document.
• Override the CObject member function Serialize to read and write data to and from the
disk.
MFC ODBC Classes:
Visual c++ contains all the components you will need to write vc++ database applications for Microsoft
Windows. Indeed, the product contains two separate client-side database access systems: open
Database Connectivity (ODBC) and Data Access objects (DAO). In addition vc++ now contains wrapper
templates for interacting with data directly through OLE DB.
‘’The Advantages of Database Management
(1) The serialization process ties a document object to disk file. All the documents data must be
read into memory when the document is opened, and all data must be written back to disk
when an updated document is closed.
(2) We can’t serialize a document that’s bigger than the available virtual memory.
(3) Even if the document is small enough to fit in memory, you might not need to read and write all
the data every time the program runs.
(4) You could program your own random access disk file, thus inventing your own DBMS but you
probably have enough work to do already, Besides using a real DBMS gives you many
advantages including the following:
• Use of standard file format : Many people think of dBASE/Xbase DBF files when they
think of database formats. This is only one file format, but its popular one. A lot of data
is distributed in DBF files, and many program’s can read and write in this format. Lately
the Microsoft Access MDB format has become popular too. With the MDB format, all of
a database’s tables and indexes can be contained in a single disk file.
• Indexed file access: If you need quick access to records by key (a customer name, for
example), you need indexed file access. You could always write your own B-tree file
access routines, but that’s a tedious job that’s has been already. All DBMS’s contains
efficient indexed access routines.
• Data integrity safeguard: Many professional DBMS products have procedures for
protecting their data. One example is transaction processing. A transaction
encompasses a series of related changes. If the entire transaction can’t be processed, it
is rolled back so that the database reverts to its original state before the transaction.
• Multiuser access control: If your application doesn’t need multiuser access now, it
might in the future. Most DBMS’s provide record locking to prevent interference among
Edited by EDUTECH
simultaneous users. Some multiuser DBMS’s use the client server model, which means
that most processing is handled on a single database server computer; the workstation
handle the user interface. Other multiuser DBMS’s handle database processing on the
workstations, and they control each workstation’s access to shared files.
The MFC ODBC classes- CRecordset and CDatabase
1. With the MFC classes for windows, you use c++ objects instead of window handles and device
context handles with the MFC ODBC classes, you use objects instead of connection handles and
statement handles.
2. The environment handle is stored in a global variable and is not represented by a c++ object.
3. Two principle of ODBC classes are CDatabase and CRecordset .
4. Object of class CDatabase represents ODBC connections to data sources, and object of class
CRecordset represent scrollable rowsets.
5. The visual c++ documentation uses the term “Recordset” instead of “Rowset” to be consistent
with Microsoft Visual Basic and Microsoft Access.
The important CRecordset member functions are as follow.
Function Description Open Opens the recordset
AddNew Prepares to add a new record to the table.
Update Completes an AddNew or Edit operations by saving the new or edited
data in the data source.
Delete Deletes the current record from the recordset.
Edit Prepares to implement changes on the current record.
IsBOF Determines whether the recordset has been positioned before the first
record.
IsEOF Determines whether the recordset has been positioned after the last
record.
MoveNext Sets the current record to the next record or the next rowdset.
Edited by EDUTECH
MoveFirst Sets the current record to the first record in the recordset.
MoveLast Sets the current record to the last record or to the rowset.
Movepre Sets the current record to the previous record or to the previous
rowset.
GetDefaultConnect Gets the default connects string for the data source on which the
recordset is based.
GetDefaultSQL Gets the default SQL string.
DoFieldExchange Exchanges data between the recordset data fields and the
corresponding record on the data source.
GetStatus Gets the index of the current record in the recordset and the final count
status.
GetRecordCount Determines the highest-numbered record yet encountered as the user
moves through the records.
GetODBCFieldCount Gets the number of fields in the recordset object.
GetODBCFieldInfo Gets information about the fields in the recordset.
The MFC CRecordView class.
1) The RecordView class is a form view class that attached to a recordset.
2) The toolbar buttons enable the user to step forward and backward through a database table.
3) Like the CFormView class, the CRecordView class depends on a dialog template resource.
4) The CFormView class has data members that correspond to the controls in the dialog box, but
the CRecordView class accesses data members in a foreign object, namely the attached
CRecordset object.
5) When the user enters data in the controls , the record view’s DDX (Dialog Data Exchange) code
moves the data into the recordset’s data members, which are bound to database columns by
the recordset’s RFX (Record Field Exchange) code.
6) When you specify a database view application, AppWizard generates a class derived from
CRecordView together with an empty dialog template.
7) AppWizard also generates a class derived from CRecordset, so it must ask you for a database
table name.
8) At runtime, the record view object and the recordset objects are connected.
9) AppWizard generates a read-only, view based database application.