Programming with Microsoft Visual C++.NET 6ed [Electronic resources] نسخه متنی

اینجــــا یک کتابخانه دیجیتالی است

با بیش از 100000 منبع الکترونیکی رایگان به زبان فارسی ، عربی و انگلیسی

Programming with Microsoft Visual C++.NET 6ed [Electronic resources] - نسخه متنی

George Shepherd, David Kruglinski

| نمايش فراداده ، افزودن یک نقد و بررسی
افزودن به کتابخانه شخصی
ارسال به دوستان
جستجو در متن کتاب
بیشتر
تنظیمات قلم

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

روز نیمروز شب
جستجو در لغت نامه
بیشتر
توضیحات
افزودن یادداشت جدید








The Ex16a Example: SDI with Serialization


The Ex16a example is similar to example Ex15b. The dialog template and the toolbar are the same, and the view class is the same. Serialization has been added, together with an update command user interface function for File Save. The header and implementation files for the view and document classes will be reused in example Ex16b.

All the new code (code that is different from Ex15b) is listed, with additions and changes to the wizard-generated code shown in boldface. The files and classes in the Ex16a example are listed in Table 16-2.

































Table 16-2: Files and Classes in Ex16a


Header File


Source Code File


Class


Description


Ex16a.h


Ex16a.cpp


CEx16aApp


Application class (from the MFC Application Wizard)


CAboutDlg


About dialog box


MainFrm.h


MainFrm.cpp


CMainFrame


SDI main frame


Ex16aDoc.h


Ex16aDoc.cpp


CEx16aDoc


Student document


Ex16aView.h


Ex16aView.cpp


CEx16aView


Student form view (borrowed from Ex15b)


Student.h


Student.cpp


CStudent


Student record


StdAfx.h


StdAfx.cpp


Precompiled headers (with afxtempl.h included)



CStudent


The Ex16a

Student.h file is almost the same as the file in the Ex15b project. The header contains the macro

DECLARE_SERIAL(CStudent)

instead of

DECLARE_DYNAMIC(CStudent)

and the implementation file contains the macro

IMPLEMENT_SERIAL(CStudent, CObject, 0)

instead of

IMPLEMENT_DYNAMIC(CStudent, CObject)

The virtual Serialize function (as shown on page 394) has also been added.



CEx16aApp


The application class files shown in the following example contain only code generated by the MFC Application Wizard. The application was generated with a default file extension and with the Windows Explorer launch and drag-and-drop capabilities. These features are described later in this chapter.

To generate additional code, when you first run the MFC Application Wizard you must enter the filename extension in the File Extension box of the wizard's Document Template Strings Page, as shown here:


This ensures that the document template resource string contains the correct default extension and that the correct Windows Explorer–related code is inserted into your application class InitInstance member function. You can change some of the other resource substrings if you want.

Ex16a.h






// Ex16a.h : main header file for the Ex16a application
#pragma once
#ifndef __AFXWIN_H__
#error include 'stdafx.h' before including this file for PCH
#endif
#include "resource.h" // main symbols
// CEx16aApp:
// See Ex16a.cpp for the implementation of this class
class CEx16aApp : public CWinApp
{
public:
CEx16aApp();
// Overrides
public:
virtual BOOL InitInstance();
// Implementation
afx_msg void OnAppAbout();
DECLARE_MESSAGE_MAP()
};
extern CEx16aApp theApp;












Ex16a.cpp






// Ex16a.cpp : Defines the class behaviors for the application.
#include "stdafx.h"
#include "Ex16a.h"
#include "MainFrm.h"
#include "Ex16aDoc.h"
#include "Ex16aView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CEx16aApp
BEGIN_MESSAGE_MAP(CEx16aApp, CWinApp)
ON_COMMAND(ID_APP_ABOUT, OnAppAbout)
// Standard file based document commands
ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew)
ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen)
END_MESSAGE_MAP()
// CEx16aApp construction
CEx16aApp::CEx16aApp()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}
// The one and only CEx16aApp object
CEx16aApp theApp;
// CEx16aApp initialization
BOOL CEx16aApp::InitInstance()
{
// InitCommonControls() is required on Windows XP if an application
// manifest specifies use of ComCtl32.dll version 6 or later to enable
// visual styles. Otherwise, any window creation will fail.
InitCommonControls();
CWinApp::InitInstance();
// Initialize OLE libraries
if (!AfxOleInit())
{
AfxMessageBox(IDP_OLE_INIT_FAILED);
return FALSE;
}
AfxEnableControlContainer();
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need
// Change the registry key under which our settings are stored
// TODO: You should modify this string to be something appropriate
// such as the name of your company or organization
SetRegistryKey(_T("Local AppWizard-Generated Applications"));
LoadStdProfileSettings(4); // Load standard INI file
// options (including MRU)
// Register the application's document templates. Document templates
// serve as the connection between documents, frame windows and views
CSingleDocTemplate* pDocTemplate;
pDocTemplate = new CSingleDocTemplate(
IDR_MAINFRAME,
RUNTIME_CLASS(CEx16aDoc),
RUNTIME_CLASS(CMainFrame), // main SDI frame window
RUNTIME_CLASS(CEx16aView));
AddDocTemplate(pDocTemplate);
// Enable DDE Execute open
EnableShellOpen();
RegisterShellFileTypes(TRUE);
// Parse command line for standard shell commands, DDE, file open
CCommandLineInfo cmdInfo;
ParseCommandLine(cmdInfo);
// Dispatch commands specified on the command line. Will return FALSE if
// app was launched with /RegServer, /Register, /Unregserver
// or /Unregister.
if (!ProcessShellCommand(cmdInfo))
return FALSE;
// The one and only window has been initialized, so show and update it
m_pMainWnd->ShowWindow(SW_SHOW);
m_pMainWnd->UpdateWindow();
// call DragAcceptFiles only if there's a suffix
// In an SDI app, this should occur after ProcessShellCommand
// Enable drag/drop open
m_pMainWnd->DragAcceptFiles();
return TRUE;
}
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// Dialog Data
enum { IDD = IDD_ABOUTBOX };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()
// App command to run the dialog
void CEx16aApp::OnAppAbout()
{
CAboutDlg aboutDlg;
aboutDlg.DoModal();
}
// CEx16aApp message handlers













CMainFrame


The main frame window class code, shown in the following example, is almost unchanged from the code that the MFC Application Wizard generated. The overridden ActivateFrame function and the WM_DROPfiles handler exist solely for trace purposes.

MainFrm.h






// MainFrm.h : interface of the CMainFrame class
#pragma once
class CMainFrame : public CFrameWnd
{
protected: // create from serialization only
CMainFrame();
DECLARE_DYNCREATE(CMainFrame)
// Attributes
public:
// Operations
public:
// Overrides
public:
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
// Implementation
public:
virtual ~CMainFrame();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected: // control bar embedded members
CStatusBar m_wndStatusBar;
CToolBar m_wndToolBar;
// Generated message map functions
protected:
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnDropFiles(HDROP hDropInfo);
virtual void ActivateFrame(int nCmdShow = -1);
};












MainFrm.cpp






// MainFrm.cpp : implementation of the CMainFrame class
#include "stdafx.h"
#include "Ex16a.h"
#include "MainFrm.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CMainFrame
IMPLEMENT_DYNCREATE(CMainFrame, CFrameWnd)
BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
ON_WM_CREATE()
ON_WM_DROPfiles()
END_MESSAGE_MAP()
static UINT indicators[] =
{
ID_SEPARATOR, // status line indicator
ID_INDICATOR_CAPS,
ID_INDICATOR_NUM,
ID_INDICATOR_SCRL
};
// CMainFrame construction/destruction
CMainFrame::CMainFrame()
{
// TODO: add member initialization code here
}
CMainFrame::~CMainFrame()
{
}
int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CFrameWnd::OnCreate(lpCreateStruct) == -1)
return -1;
if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT,
WS_CHILD | WS_VISIBLE | CBRS_TOP
| CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) ||
!m_wndToolBar.LoadToolBar(IDR_MAINFRAME))
{
TRACE0("Failed to create toolbar\n");
return -1; // fail to create
}
if (!m_wndStatusBar.Create(this) ||
!m_wndStatusBar.SetIndicators(indicators,
sizeof(indicators)/sizeof(UINT)))
{
TRACE0("Failed to create status bar\n");
return -1; // fail to create
}
m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY);
EnableDocking(CBRS_ALIGN_ANY);
DockControlBar(&m_wndToolBar);
return 0;
}
BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
if( !CFrameWnd::PreCreateWindow(cs) )
return FALSE;
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs
return TRUE;
}
// CMainFrame diagnostics
#ifdef _DEBUG
void CMainFrame::AssertValid() const
{
CFrameWnd::AssertValid();
}
void CMainFrame::Dump(CDumpContext& dc) const
{
CFrameWnd::Dump(dc);
}
#endif //_DEBUG
// CMainFrame message handlers
void CMainFrame::OnDropFiles(HDROP hDropInfo)
{
TRACE("Entering CMainFrame::OnDropFiles\n");
CFrameWnd::OnDropFiles(hDropInfo);
}
void CMainFrame::ActivateFrame(int nCmdShow)
{
TRACE("Entering CMainFrame::ActivateFrame\n");
CFrameWnd::ActivateFrame(nCmdShow);
}













The CEx16aDoc Class


previous chapter except for four functions: Serialize, DeleteContents, OnOpenDocument, and OnUpdateFileSave.


Serialize


One line has been added to the MFC Application Wizard–generated function to serialize the document's student list, as shown here:

///////////////////////////////////////////////////////////////////////
// CEx16aDoc serialization
void CEx16aDoc::Serialize(CArchive& ar)
{
TRACE("Entering CEx16aDoc::Serialize\n");
if (ar.IsStoring())
{
// TODO: add storing code here
}
else
{
// TODO: add loading code here
}
m_studentList.Serialize(ar);
}



DeleteContents


The Dump statement is replaced by a simple TRACE statement. Here is the modified code:

void CEx16aDoc::DeleteContents() 
{
TRACE("Entering CEx16aDoc::DeleteContents\n");
while (m_studentList.GetHeadPosition()) {
delete m_studentList.RemoveHead();
}
}



OnOpenDocument


This virtual function is overridden only for the purpose of displaying a TRACE message, as shown here:

BOOL CEx16aDoc::OnOpenDocument(LPCTSTR lpszPathName)
{
TRACE("Entering CEx16aDoc::OnOpenDocument\n");
if (!CDocument::OnOpenDocument(lpszPathName))
return FALSE;
// TODO: Add your specialized creation code here
return TRUE;
}



OnUpdateFileSave


This message map function grays out the File Save toolbar button when the document is in the unmodified state. The view controls this state by calling the document's SetModifiedFlag function, as shown here:

void CEx16aDoc::OnUpdateFileSave(CCmdUI* pCmdUI)
{
// Disable disk toolbar button if file is not modified
pCmdUI->Enable(IsModified());
}




The CEx16aView Class


The code for the CEx16aView class borrows code from the CEx15bView class in Chapter 15.



Testing the Ex16a Application


Build the program and start it from the debugger, and then test it by typing some data and saving it on disk with the filename Test.16a. (You don't need to type the .16a part.)

Exit the program, and then restart it and open the file you saved. Did the data you typed come back? Take a look at the Debug window and observe the sequence of function calls. You should see the trace messages showing the student document being read and written as you load and save the document.



/ 319