172
Document –View Architecture Need: Given set of data can have multiple representation- best to separate display from data. Three Objects: Document - Store the data (responsible for reading and writing data) View - To display data Window - The canvas on which all display take place

Document –View Architecture

  • Upload
    hong

  • View
    31

  • Download
    0

Embed Size (px)

DESCRIPTION

Document –View Architecture. Need: Given set of data can have multiple representation- best to separate display from data. Three Objects: Document - Store the data (responsible for reading and writing data) View - To display data - PowerPoint PPT Presentation

Citation preview

Page 1: Document –View Architecture

Document –View Architecture

Need: Given set of data can have multiple representation- best to separate display from data.Three Objects:

Document - Store the data (responsible for

reading and writing data)View - To display dataWindow - The canvas on which all

display take place

Page 2: Document –View Architecture

Menu , Keyboard AcceleratorsThe Main Frame Window and Document Classes

Page 3: Document –View Architecture

Application framework- controls interaction

between frame and view

MainFrm.h and MainFrm.cpp -application's

main frame window class

ex13aDoc.h and ex13aDoc.cpp-application's

document class

ex13aView.h and ex13aView.cpp-application’s

view class

Page 4: Document –View Architecture

Windows Menus

A Microsoft Windows menu is a familiar application element that consists of a top-level horizontal list of items with associated pop-up menus that appear when the user selects a top-level

item. Menu items - grayed ,have check marks,

separator bar. Multiple levels pop-up menus are possible.Each Menu item – ID which is defined in

resource.hEntire resource definition - .rc file(resource script file)

Page 5: Document –View Architecture

Command ProcessingWM_COMMAND message – menu

selection, keyboard accelerators,toolbar and dialog button clicks by windows.

Message Map Entry:

ON_COMMAND( ID, command handler)

Id of menu clicked item corresponding

message handler

Page 6: Document –View Architecture

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

BEGIN_MESSAGE_MAP(CMyView, CView) ON_COMMAND(ID_LINE, OnLine)END_MESSAGE_MAP() void CMyView::OnLine() { // command message processing code }

In MyView.h – Give the definition afx_msg void OnZoom();

before DECLARE_MESSAGE_MAP() macro

Page 7: Document –View Architecture

Command update handler function. Whenever a pop-up menu is first displayed or menu

item is clicked ,MFC calls this function. The handler function's argument is a CCmdUI object,

which contains a pointer to the corresponding menu item.

this pointer to modify the menu item's appearance by its operations such as enable , setcheck etc.

In view.cppBEGIN_MESSAGE_MAP(CMyView, CView) ON_UPDATE_COMMAND_UI(ID_LINE, OnUpdateLine) END_MESSAGE_MAP()

void CMyView::OnUpdateLine() { // command message processing code }

In MyView.h – Give the definition afx_msg void OnUpdateLine();

Page 8: Document –View Architecture

MFC Text Editing featuresEdit Control and Rich Edit Control: CEditView and

CRichEditView

CEditView Class: Maximum size is 64 KB, work in View and Edit classes can’t mix font and cut copy paste is possible.

CRichEditView- Supports mixed format and large quantities of text.- can include embedded OLE objects- CRichEditView maintains the text and formatting characteristic

of text.- CRichEditDoc maintains the list of OLE client items which are

in the view.- CRichEditCntrItem provides container-side access to the OLE

client item

Page 9: Document –View Architecture

Example

Page 10: Document –View Architecture

1. Add a CString data member to the CEx13aDoc class. In ex13aDoc.h

public: CString m_strText;

2. Add a CRichEditCtrl data member to the CEx13aView class. In file ex13aView.h

public: CRichEditCtrl m_rich;

In ex13aDoc.cpp

1. void CEx13aDoc::OnEditClearDocument() { m_strText.Empty(); }2. void CEx13aDoc::OnUpdateEditClearDocument (CCmdUI* pCmdUI) { pCmdUI->Enable(!m_strText.IsEmpty()); }

Page 11: Document –View Architecture

In CEx13View.cpp : Creation RichEdit Control int CEx13aView::OnCreate(LPCREATESTRUCT

lpCreateStruct)

{ CRect rect(0, 0, 0, 0);

if (CView::OnCreate(lpCreateStruct) == -1) return -1;

m_rich.Create(ES_AUTOVSCROLL | ES_MULTILINE | ES_WANTRETURN | WS_CHILD | WS_VISIBLE | WS_VSCROLL, rect, this, 1);

return 0;

}

Page 12: Document –View Architecture

2. void CEx13aView::OnSize(UINT nType, int cx, int

cy) {

CRect rect; CView::OnSize(nType, cx, cy); GetClientRect(rect); m_rich.SetWindowPos(&wndTop, 0, 0, rect.right - rect.left, rect.bottom - rect.top, SWP_SHOWWINDOW);

} position &structure

Page 13: Document –View Architecture

3.void CEx13aView::OnTransferGetData() { CEx13aDoc* pDoc = GetDocument(); m_rich.SetWindowText(pDoc- >m_strText);

m_rich.SetModify(FALSE); } 4.void CEx13aView::OnTransferStoreData() { CEx13aDoc* pDoc = GetDocument();

m_rich.GetWindowText(pDoc->m_strText); m_rich.SetModify(FALSE);

}

Page 14: Document –View Architecture

5.void CEx13aView::OnUpdateTransferStoreData

(CCmdUI* pCmdUI) { pCmdUI-

>Enable(m_rich.GetModify()); }

6. Build and Run the application

Page 15: Document –View Architecture

Creating Floating Pop-Up Menus

void CMyView::OnContextMenu(CWnd *pWnd,

CPoint point)

{

CMenu menu; menu.LoadMenu(IDR_MYFLOATINGMENU); menu.GetSubMenu(0) ->TrackPopupMenu

(TPM_LEFTALIGN | TPM_RIGHTBUTTON,

point.x, point.y, this);

}

Page 16: Document –View Architecture

Extended Command Processing

BEGIN_MESSAGE_MAP(CMyView, CView) ON_COMMAND_EX_RANGE(IDM_ZOOM_1,

IDM_ZOOM_2, OnZoom)

END_MESSAGE_MAP()ON_COMMAND_RANGE( id1, id2, Fxn )

ON_COMMAND_EX_RANGE

ON_UPDATE_COMMAND_UI_RANGE

Page 17: Document –View Architecture

ToolBar & StatusBar

Page 18: Document –View Architecture

ToolBarA toolbar consists of a number of horizontally (or vertically)

arranged graphical buttons that might be clustered in groupsPressing a toolbar button is equivalent to choosing a menu

item(WM_COMMAND messages).An update command UI message handler is used to update

the button's stateMFC toolbar can “dock” to any side of its parent window or

float in its own mini-frame window. you can change its size and drag it. A toolbar can also display tool tips as the user moves the

mouse over the toolbar’s buttons.

Page 19: Document –View Architecture

ToolBar Bitmap: -Each button on a toolbar appears to have its own bitmap, but actually a single bitmap serves the entire toolbar. -has tile, 15 pixels high and 16 pixels wide -The toolbar bitmap is stored in the file Toolbar.bmp Button State: 0: Normal, unpressed state.TBSTATE_CHECKED Checked (down) state.TBSTATE_ENABLED Available for use. Button is grayed and unavailable if

this state is not set.TBSTATE_HIDDEN Not visible.TBSTATE_INDETERMINATE Grayed.TBSTATE_PRESSED Currently selected (pressed) with the mouse.TBSTATE_WRAP Line break follows the button

Page 20: Document –View Architecture

Locating the Main FrameWindow

The toolbar and status bar objects you'll be working with are attached to the application's main frame window, not to the view window

find the main frame window through the application object.

CMainFrame* pFrame = (CMainFrame*)

AfxGetApp()->m_pMainWnd;

CToolBar* pToolBar = &pFrame->m_wndToolBar;

Page 21: Document –View Architecture

Example

Page 22: Document –View Architecture

StatusBar

neither accepts user input nor generates command messages

to display text in panes under program control

supports two types of text paneso message line panes

o status indicator panes

Page 23: Document –View Architecture

The Status Bar Definition

The static indicators array that AppWizard generates in the MainFrm.cpp file defines the panes for the application's status bar.

The constant ID_SEPARATOR identifies a message line pane;

the other constants are string resource IDs that identify indicator panes

Page 24: Document –View Architecture

The Status Bar Definition

Page 25: Document –View Architecture

Get access to the status bar objectCMainFrame* pFrame = (CMainFrame*) AfxGetApp()-> m_pMainWnd; CStatusBar* pStatus = &pFrame->m_wndStatusBar;

Display String in Massage Line-SetPaneText

pStatus->SetPaneText(0, "message line for first pane");

Pane No.: 0-leftmost pane 1-next pane to the right and so forth.

Page 26: Document –View Architecture

Example

Page 27: Document –View Architecture
Page 28: Document –View Architecture

A Reusable Frame Window Base Class

CString class.

Build your own reusable base class .

Access to the Windows Registry.

PreCreateWindow & ActiveFrame function.

Page 29: Document –View Architecture

CString classdynamic memory allocation-const char*. CString strFirstName("Elvis"); CString strLastName("Presley");CString strTruth = strFirstName + " " + strLastName; strTruth += " is alive";

int nError = 23; CString strMessageText; strMessageText.Format("Error number %d",

nError); AfxMessageBox(strMessageText);

Page 30: Document –View Architecture

CString strTest("test"); strncpy(strTest, "T", 1);CString::GetBuffer - "locks down" the buffer with

a specified size and returns a char*.

ReleaseBuffer - to make the string dynamic again.

CString strTest("test");

strncpy(strTest.GetBuffer(5), "T", 1); strTest.ReleaseBuffer();

Page 31: Document –View Architecture

Build your own reusable base class

CPersistentFrame - derived from the CFrameWnd - supports a persistent SDI (Single Document

Interface) frame window that remembers the following characteristics. Window size ,Window position Maximized status ,Minimized status Toolbar and Status bar enablement and position

When you terminate an application that's built with the CPersistentFrame class, the above information is saved on disk in the Windows Registry.

When the application starts again, it reads the Registry and restores the frame to its state at the previous exit.

Page 32: Document –View Architecture

The Windows Registryis a set of system files, managed by

Windows, in which Windows and individual applications can store and access permanent information.

is organized as a kind of hierarchical database in which string and integer data is accessed by a multipart key.

TEXTPROC      Text formatting

      Font = Times Roman Points = 10

Page 33: Document –View Architecture

The SetRegistryKey function's string parameter establishes the top of the hierarchy,

SetRegistryKey(" TEXTPROC ");

Following Registry functions(CWinApp) define the bottom two levels: called heading name and entry name.

GetProfileInt WriteProfileInt GetProfileString WriteProfileString

AfxGetApp()->WriteProfileString("Text formatting", "Font", "Times Roman"); AfxGetApp()->WriteProfileInt("Text formatting", "Points",

10);

Page 34: Document –View Architecture

ActivateFrame Member Function CFrameWnd

The key to controlling the frame's size The application framework calls this virtual function (declared in

CFrameWnd) during the SDI main frame window creation process (and in response to the File New and File Open commands).

The framework's job is to call the CWnd::ShowWindow function with the parameter nCmdShow. The nCmdShow parameter determines whether the window is maximized or minimized or both.

Override ActivateFrame in your derived frame class, to change the value of nCmdShow before passing to it .

CWnd::SetWindowPlacement function, which sets the size and position of the frame window, and you can set the visible status of the control bars.

First time call ie CPersistentFrame::ActivateFrame function operates only when the application starts.

Page 35: Document –View Architecture

The PreCreateWindow Member Function-CWnd

to change the characteristics of your window before it is displayed

calls this function before it calls ActivateFrame.

a CREATESTRUCT structure as a parameter, and two of the data members in this structure are style and dwExStyle.

CREATESTRUCT member lpszClass is also useful to change the window's background brush, cursor, or icon.

Page 36: Document –View Architecture

BOOL MyView::PreCreateWindow(CREATESTRUCT& c)

{ ….. ….

c.lpszClass =AfxRegisterWndClass(CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW, AfxGetApp()-> LoadCursor(IDC_MYCURSOR), ::CreateSolidBrush (RGB(255, 0, 0)));

if (cs.lpszClass != NULL) { return TRUE; } else { return FALSE; } }Style flag -determines whether the window has a border, scroll bars, a minimize box, and so on.Extended style – double border, left aligned border etc

Page 37: Document –View Architecture

DLL- Introduction

Dynamic Linking Librariesi.e., Link a Library files at Run time.It is a File on Disk.It consists of Global data, Compiled Functions

and Resources.It is compiled to load at preferred base address.It has various exported functions.Use those function in our process at run time.

Page 38: Document –View Architecture

How Imports are Matched to Exports

DLL contains table of exported functions.These tables contains address of functions

with in the DLL.Functions are identified by Symbolic Name

or Integers called Ordinal Numbers.

Page 39: Document –View Architecture

E.g.,_declspec (dllexport) int MyFunction(int n);_declspec (dllimport) int MyFunction(int n);

Continued...

In simple DLL’s contains EXE.In complex, Many DLL’s call function

inside other DLL’s.Declaration of Import and Export

Functions in DLL.

Page 40: Document –View Architecture

Continued…

In C++ Compiler

- Uses Decorated name

-i.e., It is long name the compiler invent based on class name , Function Name and Parameter Name.

- Listed in MAP file.E.g.,extern “c” _declspec(dllexport) int Myfun(int n);extern “c” _declspec(dllimport) int Myfun(int n);

Page 41: Document –View Architecture

Types of Linkage in DLL

Implicit Vs ExplicitSymbolic Vs Ordinal

Implicit Linkage:- E.g., C++ Library Files- Linker produces companion import LIB file- LIB file contains exported symbols, Ordinals,

but no code- When this DLL is added to user program, LIB

is surrogated.

Page 42: Document –View Architecture

Continued…

Explicit Linkage:

- E.g., VB

- here, don’t use any import file.

- Just call win32 Load Library functions with specifying DLL’s

path name and parameters

Page 43: Document –View Architecture

Continued…

Symbolic Vs Ordinal Linkage:

- win16 – ordinal Linkage

- win 32- Symbolic over ordinal Linkage

- In ordinal Linkage, program’s EXE file to be small.

- When build our own DLL, we must specify ordinals in Project’s DEF file

E.g.,

?ReadList @ RecentFileList @@ UAEXXZ @ 5458 NONAME

Ordinals

Page 44: Document –View Architecture

The DLL Entry Point- DllMain

Skeleton of DllMain function:HINSTANCE g_hInstance;extern “c” int APIENTRY DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved) { if (dwReason == DLL_PROCESS_ATTACH) { TRACE0 (“EX22A.DLL Inititalizing !\n”); //Do initialization here } else if (dwReason == DLL_PROCESS_DETACH) { TRACE0 (“EXE22A.DLL Termination!\n”); //Do cleanup here}Return 1;}

Page 45: Document –View Architecture

Instance Handles

Each DLL in a Process is Identified by unique 32-bit HINSTANCE value.

In Win32, HINSTANCE and HMODULE values are Same. But type can be interchangeably.

Base address of Process (EXE) is almost 0x400000

Default Base Address of DLL is loaded at 0x10000000

Page 46: Document –View Architecture

How to get an Instance Handle?

If you want EXE’s handle, call win32 GetModuleHandle funtion with NULL parameter.

If you want DLL’s handle, call win32 GetModuleHandle function with DLL name as Parameter.

Page 47: Document –View Architecture

Steps for Creating DLL Skeleton

Steps for building the EX22A Example.

Step1: Run AppWizard.

Step2:Examine the ex22a.cpp file

Step3:Edit the persist.h fileModify the Line class

CPersistentFrame : public CFrameWnd as class AFX_EXT_CLASS CPersistentFrame : public CFRAMEWND

Step4: Build the project and copy the DLL file.

Page 48: Document –View Architecture

Example: Step1

Page 49: Document –View Architecture

Example: Step1

Page 50: Document –View Architecture

Example: Step1

Page 51: Document –View Architecture

Example: Step2

Page 52: Document –View Architecture

Example: Step2

Page 53: Document –View Architecture

Steps for adding our own dll file to client Program

Step1: Run AppWizardStep2: Copy the file persist.h from

vcpp32\ex22a directory (only header file).Step3:Change CMainFrame base class

to CPersistentFrameStep4:Add the ex22a import library to the

linker’s input library list.Step5: Build and test the Ex22Bprogram

Page 54: Document –View Architecture

Example :step1

Page 55: Document –View Architecture

ToolBar & StatusBar

Page 56: Document –View Architecture

ToolBarA toolbar consists of a number of horizontally (or

vertically) arranged graphical buttons that might be clustered in groups

Pressing a toolbar button is equivalent to choosing a menu item(WM_COMMAND messages).

An update command UI message handler is used to update the button's state

MFC toolbar can “dock” to any side of its parent window or float in its own mini-frame window.

you can change its size and drag it. A toolbar can also display tool tips as the user

moves the mouse over the toolbar’s buttons.

Page 57: Document –View Architecture

ToolBar Bitmap: -Each button on a toolbar appears to have its own

bitmap, but actually a single bitmap serves the entire toolbar.

-has tile, 15 pixels high and 16 pixels wide -The toolbar bitmap is stored in the file

Toolbar.bmp

Page 58: Document –View Architecture

State Meaning0 Normal, unpressed state.

TBSTATE_CHECKED Checked (down) state.

TBSTATE_ENABLED Available for use. Button is grayed and unavailable if this state is not set.

TBSTATE_HIDDEN Not visible.

TBSTATE_INDETERMINATE Grayed.

TBSTATE_PRESSED Currently selected (pressed) with the mouse.

TBSTATE_WRAP Line break follows the button.

Page 59: Document –View Architecture

Locating the Main FrameWindow

The toolbar and status bar objects you'll be working with are attached to the application's main frame window, not to the view window

find the main frame window through the application object.

CMainFrame* pFrame = (CMainFrame*)

AfxGetApp()->m_pMainWnd;

CToolBar* pToolBar = &pFrame->m_wndToolBar;

Page 60: Document –View Architecture

Example

Page 61: Document –View Architecture

RunAppWizard to create an SDI application& Use the resource editor to edit the application's main menu as follows

Page 62: Document –View Architecture

3. Use the resource editor to update the application's toolbar-Edit the IDR_MAINFRAME toolbar resource

4. Give the ID to each Button5. USE ClassWizard to add command and update

command UI messages for ID_CIRCLE,ID_SQUARE &ID_PATTERN

6. In the file ex14aView.h, private: CRect m_rect; BOOL m_bCircle; BOOL m_bPattern;

Page 63: Document –View Architecture

In ex14aView.cpp

5. CEx14aView::CEx14aView() : m_rect(0, 0, 100, 100)

{ m_bCircle = TRUE; m_bPattern = FALSE; }

6. void CEx14aView::OnDraw(CDC* pDC) { CBrush brush(HS_BDIAGONAL, 0L); if (m_bPattern) { pDC->SelectObject(&brush); } else { pDC-

>SelectStockObject(WHITE_BRUSH); } if (m_bCircle) { pDC->Ellipse(m_rect); } else { pDC->Rectangle(m_rect); } }

Page 64: Document –View Architecture

7.void CEx14aView::OnDrawCircle() { m_bCircle = TRUE; m_rect += CPoint(25, 25); InvalidateRect(m_rect); } 8.void CEx14aView::OnDrawSquare() { m_bCircle = FALSE; m_rect += CPoint(25, 25); InvalidateRect(m_rect); } 9. void CEx14aView::OnDrawPattern()

//toggles { m_bPattern ^= 1; }

Page 65: Document –View Architecture

10. void CEx14aView::OnUpdateDrawCircle (CCmdUI*

pCmdUI)

{ pCmdUI->Enable(!m_bCircle); }

11.void CEx14aView::OnUpdateDrawSquare(CCmdUI*

pCmdUI)

{ pCmdUI->Enable(m_bCircle); }

12. void CEx14aView::OnUpdateDrawPattern(CCmdUI*

pCmdUI)

{ pCmdUI->SetCheck(m_bPattern); }

Page 66: Document –View Architecture

StatusBar

neither accepts user input nor generates command messages

to display text in panes under program control

supports two types of text paneso message line panes

o status indicator panes

Page 67: Document –View Architecture

The Status Bar Definition

The static indicators array that AppWizard generates in the MainFrm.cpp file defines the panes for the application's status bar.

The constant ID_SEPARATOR identifies a message line pane;

the other constants are string resource IDs that identify indicator panes

Page 68: Document –View Architecture

The Status Bar Definition

Page 69: Document –View Architecture

Get access to the status bar objectCMainFrame* pFrame = (CMainFrame*) AfxGetApp()-> m_pMainWnd; CStatusBar* pStatus = &pFrame->m_wndStatusBar;

Display String in Massage Line-SetPaneText

pStatus->SetPaneText(0, "message line for first pane");

Pane No.: 0-leftmost pane 1-next pane to the right and so forth.

Page 70: Document –View Architecture

The Status Indicatorstatus indicator pane is linked to a single

resource-supplied string that is displayed or hidden by logic in an associated update command UI message handler function.

–Contains Indicators .An indicator is identified by a string resource

ID.same ID is used to route update command UI

messages.For example Caps Lock indication by status bar

Page 71: Document –View Architecture

In Mainframe.cppON_UPDATE_COMMAND_UI(ID_INDICATOR_CAPS,

OnUpdateKeyCapsLock) void MainFrame::OnUpdateKeyCapsLock(CCmdUI* pCmdUI)

{ pCmdUI->Enable(::GetKeyState(VK_CAPITAL) & 1); }

For Left Button StatusON_UPDATE_COMMAND_UI(ID_LEFT, OnLeft)

void MainFrame::OnLeft(CCmdUI* pCmdUI)

{ pCmdUI->Enable(::GetKeyState(VK_LBUTTON) & 1); } InMainframe.h

void Onleft(CCmdUI* j);

Page 72: Document –View Architecture

Taking Control of the Status Bar

Avoid Default status bar and have your own status bar

To assign your own ID, you must replace this call

m_wndStatusBar.Create(this); with this call m_wndStatusBar.Create(this,

WS_CHILD | WS_VISIBLE | CBRS_BOTTOM, ID_MY_STATUS_BAR);

Page 73: Document –View Architecture

Example

Page 74: Document –View Architecture
Page 75: Document –View Architecture

1. Use the string editor to edit the application's string table resource.

ID Caption

ID_INDICATOR_LEFT -LEFT

ID_INDICATOR_RIGHT -RIGHT

2. Choose Resource Symbols from the View menu. Add the new status bar identifier, ID_MY_STATUS_BAR,

and accept the default value.

Page 76: Document –View Architecture

3. In MainFrame.cpp void CMainFrame::OnUpdateLeft(CCmdUI* pCmdUI) { pCmdUI->Enable(::GetKeyState(VK_LBUTTON) < 0); }

4. void CMainFrame::OnUpdateRight(CCmdUI* pCmdUI) { pCmdUI->Enable(::GetKeyState(VK_RBUTTON) < 0); }

5.In MainFrame.cpp MessageMap Entry ON_UPDATE_COMMAND_UI(ID_INDICATOR_LEFT,

OnUpdateLeft) ON_UPDATE_COMMAND_UI(ID_INDICATOR_RIGHT,

OnUpdateRight)6.In MainFrm.h. afx_msg void OnUpdateLeft(CCmdUI* pCmdUI); afx_msg void OnUpdateRight(CCmdUI*pCmdUI);

Page 77: Document –View Architecture

7.Edit the MainFrm.cpp file.

Replace the original indicators array with the following boldface code:

static UINT indicators[] =

{ ID_SEPARATOR, // first message line pane ID_SEPARATOR, // second message line pane ID_INDICATOR_LEFT,

ID_INDICATOR_RIGHT };

Page 78: Document –View Architecture

8. Use ClassWizard to add View menu command handlers in the class CMainFrame.

1. ID_VIEW_STATUS_BAR - COMMAND -

OnViewStatusBar2. ID_VIEW_STATUS_BAR-- UPDATE_COMMAND_UI -

OnUpdateViewStatusBarvoid CMainFrame::OnViewStatusBar() { m_wndStatusBar.ShowWindow((m_wndStatusBar.GetStyle() &

WS_VISIBLE) == 0); RecalcLayout(); } void CMainFrame::OnUpdateViewStatusBar(CCmdUI* pCmdUI) { pCmdUI- >SetCheck((m_wndStatusBar.GetStyle() &

WS_VISIBLE) != 0); }

Page 79: Document –View Architecture

9.In OnCreate member functionReplace 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 } with the statement shown here: if (!m_wndStatusBar.Create(this, WS_CHILD

| WS_VISIBLE | CBRS_BOTTOM, ID_MY_STATUS_BAR) || !m_wndStatusBar.SetIndicators(indicators, sizeof(indicators)/sizeof(UINT))) { TRACE0("Failed to create status bar\n"); return -1; // fail to create }

Page 80: Document –View Architecture

10. InView.cpp void CEx14bView::OnDraw(CDC* pDC) { pDC->TextOut(0, 0, "Watch the status bar while you

move and click the mouse."); } 11. void CEx14bView::OnMouseMove(UINT nFlags, Cpoint point) { CString str; CMainFrame* pFrame = (CMainFrame*)

AfxGetApp()->m_pMainWnd; CStatusBar* pStatus = &pFrame->m_wndStatusBar; if (pStatus) { str.Format("x = %d", point.x); pStatus->SetPaneText(0, str); str.Format("y = %d", point.y); pStatus->SetPaneText(1, str); }}12 #include "MainFrm.h"

Page 81: Document –View Architecture

Document View Architecture

Menu, Keyboard Accelerators

Status Bar, ToolBar

Reusable Frame Window Class

Page 82: Document –View Architecture

Global Application object

Execution begins- WinMain by MFC

AfxGetApp() – Gets ptr to Applocation object

InitInstance – Executed(Create Window &assigns hInstance,nCmdshow –appln object)

RUN()- Implements Message Loop

Terminate if WM_QUIT Message occurs

ExitInstance()

Page 83: Document –View Architecture

Separating Document from its View

Need: Given set of data can have multiple

representation- best to separate display

from data.Three Objects:

Document - Store the data (responsible for

reading and writing data)View - To display data(each view –one document)

Window - The canvas on which all display

take place

Page 84: Document –View Architecture

Document-View Interaction Functions

The CView::GetDocument Function-provides the

document pointer that can be used to access document

class member functions or public data embers.

CEx13aDoc* pDoc = GetDocument();

m_rich.SetWindowText(pDoc- >m_strText);

The CDocument::GetNextView -navigates from the document to the view, but because a document can have more than one view, it's necessary to call this member function once for each view, inside a loop

Page 85: Document –View Architecture

CDocument::UpdateAllViews -If the document data changes for any reason, all views must be

notified so that they can update their representations of that data.

-GetDocument()->UpdateAllViews(NULL): Update all

associated view .

-GetDocument()->UpdateAllViews(this): - Update all

associated view except current.

Syntax: void UpdateAllViews( CView* pSender, LPARAM lHint = 0L,

CObject* pHint = NULL );

Parameters

pSender-Points to the view that modified the document, or NULL if all views

are to be updated.

lHint - Contains information about the modification.

pHint -Points to an object storing information about the modification.

Page 86: Document –View Architecture

CView::OnUpdate: - virtual function is called by the application framework in

response to your application's call to the

CDocument::UpdateAllViews function.

- view class's OnUpdate function accesses the document, gets the document's data, and then updates the view's data members or controls to reflect the changes.

- OnUpdate can invalidate a portion of the view, causing the view's OnDraw function to use document data to draw in the window.

- Same parameters as UpdateAllViews.

Page 87: Document –View Architecture

CView::OnInitialUpdate -virtual CView function is called when the application

starts, when the user chooses New from the File menu, and when the user chooses Open from the File menu.

-calls OnUpdate. -use your derived class's OnInitialUpdate function to

initialize your view object -When the application starts, the application framework

calls OnInitialUpdate immediately after OnCreate

CDocument::OnNewDocument -The framework calls this virtual function after a

document object is first constructed and when the user chooses New from the File menu in an SDI application.

-to set the initial values of your document's data members.

Page 88: Document –View Architecture

Application starts CMyDocument object constructed CMyView object constructed View window created CMyView::OnCreate called (if mapped) CMyDocument::OnNewDocument called CMyView::OnInitialUpdate called View object initialized View window invalidated CMyView::OnDraw called

User edits data CMyView functions update CMyDocument data members

User exits application CMyView object destroyed

Page 89: Document –View Architecture

Frame Windows

Page 90: Document –View Architecture

Frame Window - Definition

An application or some parts of an application when framed by Windows are called Frame Windows

Frame windows act as containers for other windows such as control bars or child controls.

Page 91: Document –View Architecture

Basic types of Frame Windows

Single Document Interface (SDI) frame windows

Multiple Document Interface (MDI) frame windows.

MDI frame windows can contain MDI child windows

Page 92: Document –View Architecture

Serialization

Serialization is an important concept in MFC programming because it is the basis for MFC's ability to open and save documents in document/view applications.

Page 93: Document –View Architecture

Serialization Process

Page 94: Document –View Architecture

when someone using a document/view application selects Open or Save from the application's File menu, MFC opens the file for reading or writing and passes the application a reference to a CArchive object.

The application, in turn, serializes its persistent data to or from the archive and, by so doing, saves a complete document to disk or reads it back again. A document whose persistent data consists entirely of primitive data types or serializable objects can often be serialized with just a few lines of code.

Page 95: Document –View Architecture

Serialization - Write

Assume that a CFile object named file represents an open file, that the file was opened with write access, and that you want to write a pair of integers named a and b to that file. One way to accomplish this is to call CFile::Write once for each integer:

file.Write (&a, sizeof (a)); file.Write (&b, sizeof (b));

An alternative method is to create a CArchive object, associate it with the CFile object, and use the << operator to serialize the integers into the archive:

CArchive ar (&file, CArchive::store); ar << a << b;

Page 96: Document –View Architecture

Serialization – Read (deserialize)

Assuming file once again represents an open file and that the file is open with read access, the following code snippet attaches a CArchive object to the file and reads, or deserializes, the integers from the file:

CArchive ar (&file, CArchive::load);

ar >> a >> b; MFC allows a wide variety of primitive data

types to be serialized this way, including BYTEs, WORDs, LONGs, DWORDs, floats, doubles, ints, unsigned ints, shorts, and chars.

Page 97: Document –View Architecture

SDI and MDI

MFC supports two types of document/view applications. Single document interface (SDI) applications support just one open document at a time. Multiple document interface (MDI) applications permit two or more documents to be open concurrently and also support multiple views of a given document. The WordPad applet is an SDI application; Microsoft Word is an MDI application.

Page 98: Document –View Architecture

SDI

SDI application frame windows are derived from the class CFrameWnd.

The MFC library supports two distinct application types: Single Document Interface (SDI) and Multiple Document Interface (MDI). An SDI application has, only one window. If the application depends on disk-file "documents," only one document can be loaded at a time. The original Windows Notepad is an example of an SDI application.

Page 99: Document –View Architecture

The standard SDI frame menus

Page 100: Document –View Architecture

The child windows within an SDI main frame window

Page 101: Document –View Architecture

SDI Document View Architecture

Page 102: Document –View Architecture

SDI Application

Startup steps in a Microsoft Windows MFC library application:

Windows loads your program into memory. The global object theApp is constructed. (All

globally declared objects are constructed immediately when the program is loaded.)

Windows calls the global function WinMain, which is part of the MFC library. (WinMain is equivalent to the non-Windows main function—each is a main program entry point.)

Page 103: Document –View Architecture

Steps…

WinMain searches for the one and only instance of a class derived from CWinApp.

WinMain calls the InitInstance member function for theApp, which is overridden in your derived application class.

Your overridden InitInstance function starts the process of loading a document and displaying the main frame and view windows.

WinMain calls the Run member function for theApp, which starts the processes of dispatching window messages and command messages.

Page 104: Document –View Architecture

Class Relationship

Page 105: Document –View Architecture

Object Relationship

Page 106: Document –View Architecture

Routing of command messages sent to an SDI frame window.

Page 107: Document –View Architecture

SDI vs MDI

SDI MDI

Permit the user to have only one document. The user should to close the currently open document before opening another.

Permit the user to have two or more documents open for editing at once.

Feature just one menu. MDI applications have at least two: one that's displayed when no documents are open and another that's displayed when at least one document is open.

SDI applications use just one frame window—the top-level frame window that serves as the application's main window and frames views of open documents.

MDI applications use two: a top-level frame window and child frames or document frames that float within the top-level frame window and frame views of open documents

Page 108: Document –View Architecture

MDI

MDI application frame windows are derived from the class CMDIFrameWnd.

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

Page 109: Document –View Architecture

The parent-child hierarchy of a Windows MDI application.

Page 110: Document –View Architecture

MDI application

Page 111: Document –View Architecture

MDI windows

Page 112: Document –View Architecture

MDI classes

An MDI application has two frame window classes and many frame objects

Base Class CMDIFrameWndCMDIChildWnd

AppWizard-Generated Class CMainFrameCChildFrame

Page 113: Document –View Architecture

The MDI frame-view window relationship

Page 114: Document –View Architecture

Splitter Windows

A splitter window is a window that can be divided into two or more panes horizontally, vertically, or both horizontally and vertically using movable splitter bars. Each pane contains one view of a document's data. The views are children of the splitter window, and the splitter window itself is normally a child of a frame window.

Page 115: Document –View Architecture

Splitter windows

Using splitter windows provided by MFC, a single document interface (SDI) application can present two or more views of the same document in resizeable "panes" that subdivide the frame window's client area

In an SDI application, the splitter window is a child of the top-level frame window.

Page 116: Document –View Architecture

In an MDI application, the splitter window is a child of an MDI document frame.

Page 117: Document –View Architecture

Types of splitter windows

static splitter window: The numbers of rows and columns in a static

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

Page 118: Document –View Architecture

Static splitter window

Page 119: Document –View Architecture

Dynamic Splitter window

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

Page 120: Document –View Architecture

Dynamic Splitter window

Page 121: Document –View Architecture

Procedure for Creating and initializing a dynamic splitter window

1. Add a CSplitterWnd data member to the frame window class.

2. Override the frame window's virtual OnCreateClient function, and call CSplitterWnd::Create to create a dynamic splitter window in the frame window's client area.

Page 122: Document –View Architecture

Creating splitter window…

Assuming m_wndSplitter is a CSplitterWnd object that's a member of the frame window class CMainFrame, the following OnCreateClient override creates a dynamic splitter window inside the frame window: BOOL CMainFrame::OnCreateClient

(LPCREATESTRUCT lpcs,

CCreateContext* pContext)

{

return m_wndSplitter.Create (this, 2, 1, CSize (1, 1), pContext);

}

Page 123: Document –View Architecture

The first parameter to CSplitterWnd::Create identifies the splitter window's parent, which is the frame window.

The second and third parameters specify the maximum number of rows and columns that the window can be split into.

Because a dynamic splitter window supports a maximum of two rows and two columns, these parameter values will always be 1 or 2.

The fourth parameter specifies each pane's minimum width and height in pixels. The framework uses these values to determine when panes should be created and destroyed as splitter bars are moved.

Creating splitter window…

Page 124: Document –View Architecture

Creating splitter window…

CSize values equal to (1,1) specify that panes can be as little as 1 pixel wide and 1 pixel tall.

The fifth parameter is a pointer to a CCreateContext structure provided by the framework. The structure's m_pNewViewClass member identifies the view class used to create views in the splitter's panes.

The framework creates the initial view for you and puts it into the first pane. Other views of the same class are created automatically as additional panes are created.

Page 125: Document –View Architecture

Visual Programming BasicsCreating a Window Based Application Adding an Event Handler Adding Command

Button, Edit Box and static Text controlsCompleting Windows ProgramAdding Check Box, Radio Button and Group Box

Controls

Page 126: Document –View Architecture

Creating Window Based Application Visual C++ Application = Visual Part +

Programming Language Part Although console Programs are extremely

efficient for learning the programming basics of visual c++, the IDE allows you to easily create event-driven WBA that make full use of the visual elements.

Page 127: Document –View Architecture

• A User’s Stand Point

• Fig: A User’s view of an application

• These Visual Elements from the basics of a graphical user interface (GUI).

• This permits the user to see the inputs and outputs provided by the application, within the context of a true window.

Page 128: Document –View Architecture

From a Programmer’s Perspective• The above fig is constructed from a set of visual

objects provided as resources when the program is being developed.

• A Closer look at the elements shown in fig reveals that the application’s main window is defined by its border, which contains the title bar and minimize, resize and close buttons.

• Additionally, although they are not shown scrollbars could also be present

• The area within the main window is referred to as the client area,

• And it is within this area that each application must be individually constructed..

Page 129: Document –View Architecture

For Example• Inside the client area shown in Fig is a dialog box,

which itself contains a number of controls.• Although dialog boxes and controls are usually

considered together, a control is more formally defined as an object such as command button, that provides a unique capability

• to display data,• perform an action (or) make the GUI easier to read

Page 130: Document –View Architecture

Standard VC++ Tool Boxo Dialog boxes, which are also referred to as dialogs, for

short, consist of two general types.o Modal Type – must be closed before any other part of the

program using the dialog can be accessedo Non Modal type – can remain open while other elements in

the same program containing the dialogs are activated.o VC++’s resource editor is activated one of the windows

that is used with it is the controls window, also referred as toolbox..

o each of these objects is a control in that it permits a user to input info or receive the output from an executing application.

o A majority of applications can be constructed using a minimal set of the controls provided in the toolbox window.

o The minimal set consists of the Label, Edit box and Command button objects.

o The next set of Objects that more frequently found in applications include the checkbox, Radio button, Group box, List box and Combo box controls.

Page 131: Document –View Architecture

Object type Use

Check box Select one option from two mutually exclusive options.

Command Button (also called push

button)

Initiate an action, such as a display or calculation.

Edit box Enter and display data

Group box A rectangular area within a dialog box in which logically related controls can be grouped together

Label Create a Text that user can not directly change

Radio Button (also called an option

Button)

Select one option from a group of mutually exclusive options.

List box Display a list of items from which one can be selected

Combo Box Display a list of items from which one can be selected plus permits users to type the value of the desired one.

Page 132: Document –View Architecture

As Objects they are ultimately defined by two features, referred to as Properties and Methods.

An Object’s Properties define its state Which for controls is simply how the object appears on

the screen?

For ExampleThe properties of an edit box includes the location of the edit box within a dialog the color of the box (background color), The color that text will be displayed in the box (foreground color) and whether it is read only or can also be written to by the user Methods

As they apply to controls are predefined procedures that are supplied with the object for performing specific tasks

Page 133: Document –View Architecture

Methods As they apply to controls are predefined procedures that are supplied with the object for performing specific tasks

For ExampleYou can use a method to move an Object to a different location or change its size in general a method is used to alter an object’s properties. Additionally each Object recognizes certain actions.

For ExampleCommand Button recognizes when the mouse pointer is pointing to it and the left mouse button is clicked. This types of action as we have seen are referred to as events.

Page 134: Document –View Architecture

As illustrated in fig an event such as clicking the mouse on a command button, sets in motion a sequence of occurrences.

If code has been written for the event, the code is executed otherwise the event is ignored.

This is of course the essence of GUI and event driven applications.

The selection of which code is executed depends on what events occur which ultimately depends on, what the user does

The code however, must still be written by the programmer.

With these basics in mind, it is now time to create our First VC++ WB Application

Page 135: Document –View Architecture

Although a full featured window application can be developed by using code only.

You would need extensive and advanced knowledge of the MFC Library to produce such a program.

Even Advanced programmers no longer create applications using only code. Because VC++ provides a number of features that permits rapid development of the GUI required for a WBA.

VC++ WBA requires the following 3 steps.

1. Create the GUI

2. Set the properties of each Object on the Interface.

3. Write the code.

Page 136: Document –View Architecture

Dialog and Controls

When designing an application, as dialog is a container upon which other controls are placed. When an application is executed, the dialog becomes a dialog box.

It can either be contained which the client area of an SDI or MDI window or be displayed by itself as a stand alone window.

SDI applications can have multiple windows, but only one window at a time can be viewed by a user.

MDI, which means the applications, consists of a single parent or main window that contains multiple child or internal windows.

Page 137: Document –View Architecture

For Example

Note Pad Application supplied with the windows OS is an SDI Application.

MS Excel and Access are that can be placed on a dialog and has its own set of recognized properties, methods and events.

Controls are used to receive user input and display the output and trigger event programming.

Formally a control is considered as child window

Page 138: Document –View Architecture

Step 1

Visual C++ IDE

Page 139: Document –View Architecture

Step 2

The Standard Menu

Choose File => New

Page 140: Document –View Architecture

Step 3

The New Dialog Box

Page 141: Document –View Architecture

Step 4

The First AppWizard Window

Page 142: Document –View Architecture

The Second

AppWizard Window

Page 143: Document –View Architecture

The Third

AppWizard Window

Page 144: Document –View Architecture

The Fourth

AppWizard Window

Page 145: Document –View Architecture

The Fifth

AppWizard Window

Page 146: Document –View Architecture

Creating

Sample Dialog Based

Application

Page 147: Document –View Architecture

Steps 1. Place the Controls2. Set the Properties

For the Controls using View => Properties

3. Set the Member Variables using Class Wizard

4. Write Code For Compute Button

Page 148: Document –View Architecture

Execute the Application by using Ctrl+ F5

Page 149: Document –View Architecture

This SDI "Hello, world!" example. The application has only one window, an object of a class derived from CFrameWnd. All drawing occurs inside the frame window and all messages are handled there.

Run AppWizard to produce \SeminarSDI.

Page 150: Document –View Architecture

Select the Single Document option in the AppWizard

Step 1 dialog and uncheck the Document/View Architecture Support? option,as shown here.

Page 151: Document –View Architecture

The Second

AppWizard Window

For SDI

Page 152: Document –View Architecture

The Third

AppWizard Window

For SDI

Page 153: Document –View Architecture

The Fourth

AppWizard Window

For SDI

Page 154: Document –View Architecture

The Fifth

AppWizard Window

For SDI

Page 155: Document –View Architecture

The Sixth

AppWizard Window

For SDI

Page 156: Document –View Architecture

The Seventh

AppWizard Window

For SDI

Page 157: Document –View Architecture

Write Code in OnPaint EventIn Code Window

Add code to paint in the dialog. Add the following boldface code to the CChildView::OnPaint function in the ChildView.cpp source code file:

void CChildView::OnPaint() { CPaintDC dc(this); dc.TextOut(0, 0, "Hello, world!"); }

Page 158: Document –View Architecture

Compile and run. You now have a complete SDI application that has no dependencies on the document-view architecture.

Output Window For SDI Application

Page 159: Document –View Architecture

CChildView classContrary to its name, this class is actually a CWnd derivative that is declared in ChildView.h and implemented in ChildView.cpp. CChildView implements only a virtual OnPaint member function, which contains any code that you want to draw in the frame window .

CMainFrame class This class contains a data member, m_wndView, that is created and initialized in the CMainFrame::OnCreate member function.

CMainFrame::OnSetFocus function This function makes sure the focus is translated to the CChildView:

void CMainFrame::OnSetFocus(CWnd* pOldWnd) {

// forward focus to the view window m_wndView.SetFocus(); }

CMainFrame::OnCmdMsg function This function gives the view a chance to handle any command messages first: BOOL CMainFrame::OnCmdMsg(UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo) {// let the view have first crack at the command if (m_wndView.OnCmdMsg(nID, nCode, pExtra, pHandlerInfo)) return TRUE;// otherwise, do default handling return CFrameWnd::OnCmdMsg(nID, nCode, pExtra, pHandlerInfo); }

Page 160: Document –View Architecture

Create an MDI application that doesn't use the document-view architecture.

Run AppWizard to produce \seminarMDI. Select the Multiple Documents option in the AppWizard Step 1 dialog and uncheck the Document/View Architecture Support? option, as shown here.

Page 161: Document –View Architecture

Step 1 using

The AppWizard

To Create MDI Application

Page 162: Document –View Architecture

Step 2 using

The AppWizard

To Create MDI Application

Page 163: Document –View Architecture

Step 3 using

The AppWizard

To Create MDI Application

Page 164: Document –View Architecture

Step 4 using

The AppWizard

To Create MDI Application

Page 165: Document –View Architecture

Step 5 using

The AppWizard

To Create MDI Application

Page 166: Document –View Architecture

Step 6 using

The AppWizard

To Create MDI Application

Page 167: Document –View Architecture

Step 7 using

The AppWizard

To Create MDI Application

Page 168: Document –View Architecture

Step 8 using

The AppWizard

To Create MDI Application

Page 169: Document –View Architecture
Page 170: Document –View Architecture

Add code to paint in the dialog. Add code to the CChildView::OnPaint function in the ChildView.cpp source code file:

void CChildView::OnPaint() { CPaintDC dc(this);dc.TextOut(0, 0, "Hello, world!"); }

Page 171: Document –View Architecture

Compile and run.You now have a complete MDI application without dependencies on the document-view architecture. As in SDI, this example automatically creates a CChildView class. The main difference between SDI and MDI is the fact that in MDI the CChildView class is created in the CChildFrame::OnCreate function instead of in the CMainFrame class.

Page 172: Document –View Architecture

Thank You